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 |
|---|---|---|---|---|---|---|---|---|---|---|
754d1a18da471e10937dad90478cd8368b20f4c5 | tests/test_sqlite.py | tests/test_sqlite.py | # This is an example test settings file for use with the Django test suite.
#
# The 'sqlite3' backend requires only the ENGINE setting (an in-
# memory database will be used). All other backends will require a
# NAME and potentially authentication information. See the
# following section in the docs for more information:
#
# https://docs.djangoproject.com/en/dev/internals/contributing/writing-code/unit-tests/
#
# The different databases that Django supports behave differently in certain
# situations, so it is recommended to run the test suite against as many
# database backends as possible. You may want to create a separate settings
# file for each of the backends you test against.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': '',
},
}
SECRET_KEY = "widgy_tests_secret_key"
# To speed up tests under SQLite we use the MD5 hasher as the default one.
# This should not be needed under other databases, as the relative speedup
# is only marginal there.
PASSWORD_HASHERS = (
'django.contrib.auth.hashers.MD5PasswordHasher',
'django.contrib.auth.hashers.SHA1PasswordHasher',
)
SOUTH_TESTS_MIGRATE = False
URLCONF_INCLUDE_CHOICES = tuple()
| # This is an example test settings file for use with the Django test suite.
#
# The 'sqlite3' backend requires only the ENGINE setting (an in-
# memory database will be used). All other backends will require a
# NAME and potentially authentication information. See the
# following section in the docs for more information:
#
# https://docs.djangoproject.com/en/dev/internals/contributing/writing-code/unit-tests/
#
# The different databases that Django supports behave differently in certain
# situations, so it is recommended to run the test suite against as many
# database backends as possible. You may want to create a separate settings
# file for each of the backends you test against.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': '',
},
}
SECRET_KEY = "widgy_tests_secret_key"
# To speed up tests under SQLite we use the MD5 hasher as the default one.
# This should not be needed under other databases, as the relative speedup
# is only marginal there.
PASSWORD_HASHERS = (
'django.contrib.auth.hashers.MD5PasswordHasher',
'django.contrib.auth.hashers.SHA1PasswordHasher',
)
SOUTH_TESTS_MIGRATE = False
URLCONF_INCLUDE_CHOICES = tuple()
TEST_RUNNER = 'django.test.simple.DjangoTestSuiteRunner'
| Use the old django test runner | Use the old django test runner
We aren't ready to switch to the new unittest discovery in django.
| Python | apache-2.0 | j00bar/django-widgy,j00bar/django-widgy,j00bar/django-widgy | ---
+++
@@ -31,3 +31,4 @@
SOUTH_TESTS_MIGRATE = False
URLCONF_INCLUDE_CHOICES = tuple()
+TEST_RUNNER = 'django.test.simple.DjangoTestSuiteRunner' |
569840b37f9e43bec0de3f6ddadc89d6a2f9e17b | traceview/formatters.py | traceview/formatters.py | # -*- coding: utf-8 -*-
"""
traceview.formatters
This module contains functions used to format TraceView API results.
"""
from collections import namedtuple
def identity(results):
return results
def tuplify(results, class_name='Result'):
if 'fields' in results and 'items' in results:
return _tuplify_timeseries(results, class_name)
return _tuplify_dict(results, class_name)
def _tuplify_timeseries(results, class_name):
tuple_name = '{name}Tuple'.format(name=class_name)
nt = namedtuple(tuple_name, results['fields'])
return map(nt._make, results['items'])
def _tuplify_dict(results, class_name):
tuple_name = '{name}Tuple'.format(name=class_name)
nt = namedtuple(tuple_name, results.keys())
return nt(**results)
| # -*- coding: utf-8 -*-
"""
traceview.formatters
This module contains functions used to format TraceView API results.
"""
from collections import namedtuple
def identity(results):
return results
def tuplify(results, class_name='Result'):
if 'fields' in results and 'items' in results:
return _tuplify_timeseries(results, class_name)
return _tuplify_dict(results, class_name)
def _tuplify_timeseries(results, class_name):
tuple_name = '{name}Tuple'.format(name=class_name)
nt = namedtuple(tuple_name, results['fields'])
return [nt(*item) for item in results['items']]
def _tuplify_dict(results, class_name):
tuple_name = '{name}Tuple'.format(name=class_name)
nt = namedtuple(tuple_name, results.keys())
return nt(**results)
| Replace map with a list comprehension. | Replace map with a list comprehension.
| Python | mit | danriti/python-traceview | ---
+++
@@ -23,7 +23,7 @@
def _tuplify_timeseries(results, class_name):
tuple_name = '{name}Tuple'.format(name=class_name)
nt = namedtuple(tuple_name, results['fields'])
- return map(nt._make, results['items'])
+ return [nt(*item) for item in results['items']]
def _tuplify_dict(results, class_name): |
4d51fad87581281cd98d97a091346018d9784411 | word2vec_api.py | word2vec_api.py | from flask import Flask, request
from flask.ext.restful import reqparse, Api, Resource
from gensim.models.word2vec import Word2Vec
import json
print 'loading model'
MODEL = Word2Vec.load_word2vec_format(
'GoogleNews-vectors-negative300.bin.gz', binary=True)
print 'model loaded'
app = Flask(__name__)
api = Api(app)
class HelloWorld(Resource):
def post(self):
# reqparse didn't work, when a single item was passed in the negative
# field It was splitting the string by character
args = request.get_json()
result = MODEL.most_similar(
positive=args['positive'],
negative=args['negative'],
topn=args['topn'],
)
return {'result': result}, 201
api.add_resource(HelloWorld, '/most_similar')
if __name__ == '__main__':
app.run(debug=True)
| from flask import Flask, request
from flask.ext.restful import reqparse, Api, Resource
from gensim.models.word2vec import Word2Vec
import json
print 'loading model'
MODEL = Word2Vec.load('GoogleNews-vectors-negative300.gensim')
print 'model loaded'
app = Flask(__name__)
api = Api(app)
class HelloWorld(Resource):
def post(self):
# reqparse didn't work, when a single item was passed in the negative
# field It was splitting the string by character
args = request.get_json()
try:
result = MODEL.most_similar(
positive=args['positive'],
negative=args['negative'],
topn=args['topn'],
)
except KeyError:
return {'result': [("Sorry, I haven't learned that word yet", -1)]}, 201
return {'result': result}, 201
api.add_resource(HelloWorld, '/most_similar')
if __name__ == '__main__':
app.run(debug=False)
| Update to use gensim format | api: Update to use gensim format | Python | mit | mdbecker/word2vec_demo,mdbecker/word2vec_demo | ---
+++
@@ -4,8 +4,7 @@
import json
print 'loading model'
-MODEL = Word2Vec.load_word2vec_format(
- 'GoogleNews-vectors-negative300.bin.gz', binary=True)
+MODEL = Word2Vec.load('GoogleNews-vectors-negative300.gensim')
print 'model loaded'
app = Flask(__name__)
@@ -16,14 +15,17 @@
# reqparse didn't work, when a single item was passed in the negative
# field It was splitting the string by character
args = request.get_json()
- result = MODEL.most_similar(
- positive=args['positive'],
- negative=args['negative'],
- topn=args['topn'],
- )
+ try:
+ result = MODEL.most_similar(
+ positive=args['positive'],
+ negative=args['negative'],
+ topn=args['topn'],
+ )
+ except KeyError:
+ return {'result': [("Sorry, I haven't learned that word yet", -1)]}, 201
return {'result': result}, 201
api.add_resource(HelloWorld, '/most_similar')
if __name__ == '__main__':
- app.run(debug=True)
+ app.run(debug=False) |
5ea71effd4fc436eeebb361b73202315a5d57916 | tests/test_modules/test_ADCore/test_infos.py | tests/test_modules/test_ADCore/test_infos.py | import unittest
from malcolm.modules.ADCore.infos import FilePathTranslatorInfo
class TestInfo(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_file_path_translator_drive_mount(self):
info = FilePathTranslatorInfo("C", "/foo", "")
part_info = {"WINPATH": [info]}
win_path = info.translate_filepath(part_info,
"/foo/directory/file:name.xml")
assert "C:\\directory\file_name.xml" == win_path
def test_file_path_translator_network_mount(self):
info = FilePathTranslatorInfo("", "/foo", "//dc")
part_info = {"WINPATH": [info]}
win_path = info.translate_filepath(part_info, "/foo/directory")
assert "\\\\dc\\foo\\directory" == win_path
| import unittest
from malcolm.modules.ADCore.infos import FilePathTranslatorInfo
class TestInfo(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_file_path_translator_drive_mount(self):
info = FilePathTranslatorInfo("C", "/foo", "")
part_info = {"WINPATH": [info]}
win_path = info.translate_filepath(part_info,
"/foo/directory/file:name.xml")
assert "C:\\directory\\file_name.xml" == win_path
def test_file_path_translator_network_mount(self):
info = FilePathTranslatorInfo("", "/foo", "//dc")
part_info = {"WINPATH": [info]}
win_path = info.translate_filepath(part_info, "/foo/directory")
assert "\\\\dc\\foo\\directory" == win_path
| Correct the windows path in test of Windows path translator | Correct the windows path in test of Windows path translator
| Python | apache-2.0 | dls-controls/pymalcolm,dls-controls/pymalcolm,dls-controls/pymalcolm | ---
+++
@@ -17,7 +17,7 @@
win_path = info.translate_filepath(part_info,
"/foo/directory/file:name.xml")
- assert "C:\\directory\file_name.xml" == win_path
+ assert "C:\\directory\\file_name.xml" == win_path
def test_file_path_translator_network_mount(self):
info = FilePathTranslatorInfo("", "/foo", "//dc") |
5a307c9ed6ad00c6df40f505caa9a8dfb432892d | utils.py | utils.py | import os
from google.appengine.api import apiproxy_stub_map
from google.appengine.api.app_identity import get_application_id
have_appserver = bool(apiproxy_stub_map.apiproxy.GetStub('datastore_v3'))
if not have_appserver:
from .boot import PROJECT_DIR
from google.appengine.tools import dev_appserver
appconfig = dev_appserver.LoadAppConfig(PROJECT_DIR, {},
default_partition='dev')[0]
def appid():
if have_appserver:
return get_application_id()
else:
try:
return appconfig.application.split('~', 1)[-1]
except ImportError, e:
raise Exception("Could not get appid. Is your app.yaml file missing? "
"Error was: %s" % e)
on_production_server = have_appserver and \
not os.environ.get('SERVER_SOFTWARE', '').lower().startswith('devel')
| import os
from google.appengine.api import apiproxy_stub_map
from google.appengine.api.app_identity import get_application_id
have_appserver = bool(apiproxy_stub_map.apiproxy.GetStub('datastore_v3'))
if not have_appserver:
from .boot import PROJECT_DIR
from google.appengine.tools import dev_appserver
appconfig = dev_appserver.LoadAppConfig(PROJECT_DIR, {},
default_partition='dev')[0]
def appid():
if have_appserver:
return get_application_id()
else:
try:
return appconfig.application.split('~', 1)[-1]
except ImportError, e:
raise Exception("Could not get appid. Is your app.yaml file missing? "
"Error was: %s" % e)
on_production_server = 'SERVER_SOFTWARE' in os.environ and not os.environ['SERVER_SOFTWARE'].startswith("Development")
| Tweak the way that on_production_server is determined | Tweak the way that on_production_server is determined
| Python | bsd-3-clause | potatolondon/djangoappengine-1-4,potatolondon/djangoappengine-1-4 | ---
+++
@@ -20,5 +20,4 @@
raise Exception("Could not get appid. Is your app.yaml file missing? "
"Error was: %s" % e)
-on_production_server = have_appserver and \
- not os.environ.get('SERVER_SOFTWARE', '').lower().startswith('devel')
+on_production_server = 'SERVER_SOFTWARE' in os.environ and not os.environ['SERVER_SOFTWARE'].startswith("Development") |
6da3b2a09914546bbc29caa9f807e05f0ee66b0d | cybox/objects/port_object.py | cybox/objects/port_object.py | # Copyright (c) 2013, The MITRE Corporation. All rights reserved.
# See LICENSE.txt for complete terms.
import cybox.utils as utils
import cybox.bindings.port_object as port_binding
from cybox.common import ObjectProperties, String, PositiveInteger
class Port(ObjectProperties):
_namespace = 'http://cybox.mitre.org/objects#PortObject-2'
_XSI_NS = "PortObj"
_XSI_TYPE = "PortObjectType"
def __init__(self):
super(Port, self).__init__()
self.port_value = None
self.layer4_protocol = None
def to_obj(self):
port_obj = port_binding.PortObjectType()
super(Port, self).to_obj(port_obj)
if self.port_value is not None:
port_obj.set_Port_Value(self.port_value.to_obj())
if self.layer4_protocol is not None:
port_obj.set_Layer4_Protocol(self.layer4_protocol.to_obj())
return port_obj
def to_dict(self):
port_dict = {}
super(Port, self).to_dict(port_dict)
if self.port_value is not None:
port_dict['port_value'] = self.port_value.to_dict()
if self.layer4_protocol is not None:
port_dict['layer4_protocol'] = self.layer4_protocol.to_dict()
return port_dict
@staticmethod
def from_dict(port_dict):
if not port_dict:
return None
port = Port()
ObjectProperties.from_dict(port_dict, port)
port.port_value = PositiveInteger.from_dict(port_dict.get('port_value'))
port.layer4_protocol = String.from_dict(port_dict.get('layer4_protocol'))
return port
@staticmethod
def from_obj(port_obj):
if not port_obj:
return None
port = Port()
ObjectProperties.from_obj(port_obj, port)
port.port_value = PositiveInteger.from_obj(port_obj.get_Port_Value())
port.layer4_protocol = String.from_obj(port_obj.get_Layer4_Protocol())
return port
| # Copyright (c) 2013, The MITRE Corporation. All rights reserved.
# See LICENSE.txt for complete terms.
import cybox
import cybox.bindings.port_object as port_binding
from cybox.common import ObjectProperties, String, PositiveInteger
class Port(ObjectProperties):
_binding = port_binding
_binding_class = port_binding.PortObjectType
_namespace = 'http://cybox.mitre.org/objects#PortObject-2'
_XSI_NS = "PortObj"
_XSI_TYPE = "PortObjectType"
port_value = cybox.TypedField("Port_Value", PositiveInteger)
layer4_protocol = cybox.TypedField("Layer4_Protocol", String)
| Convert Port object to simpler representation | Convert Port object to simpler representation
| Python | bsd-3-clause | CybOXProject/python-cybox | ---
+++
@@ -1,65 +1,17 @@
# Copyright (c) 2013, The MITRE Corporation. All rights reserved.
# See LICENSE.txt for complete terms.
-import cybox.utils as utils
+import cybox
import cybox.bindings.port_object as port_binding
from cybox.common import ObjectProperties, String, PositiveInteger
class Port(ObjectProperties):
+ _binding = port_binding
+ _binding_class = port_binding.PortObjectType
_namespace = 'http://cybox.mitre.org/objects#PortObject-2'
_XSI_NS = "PortObj"
_XSI_TYPE = "PortObjectType"
- def __init__(self):
- super(Port, self).__init__()
- self.port_value = None
- self.layer4_protocol = None
-
- def to_obj(self):
- port_obj = port_binding.PortObjectType()
- super(Port, self).to_obj(port_obj)
-
- if self.port_value is not None:
- port_obj.set_Port_Value(self.port_value.to_obj())
- if self.layer4_protocol is not None:
- port_obj.set_Layer4_Protocol(self.layer4_protocol.to_obj())
-
- return port_obj
-
- def to_dict(self):
- port_dict = {}
- super(Port, self).to_dict(port_dict)
-
- if self.port_value is not None:
- port_dict['port_value'] = self.port_value.to_dict()
- if self.layer4_protocol is not None:
- port_dict['layer4_protocol'] = self.layer4_protocol.to_dict()
-
- return port_dict
-
- @staticmethod
- def from_dict(port_dict):
- if not port_dict:
- return None
-
- port = Port()
- ObjectProperties.from_dict(port_dict, port)
-
- port.port_value = PositiveInteger.from_dict(port_dict.get('port_value'))
- port.layer4_protocol = String.from_dict(port_dict.get('layer4_protocol'))
-
- return port
-
- @staticmethod
- def from_obj(port_obj):
- if not port_obj:
- return None
-
- port = Port()
- ObjectProperties.from_obj(port_obj, port)
-
- port.port_value = PositiveInteger.from_obj(port_obj.get_Port_Value())
- port.layer4_protocol = String.from_obj(port_obj.get_Layer4_Protocol())
-
- return port
+ port_value = cybox.TypedField("Port_Value", PositiveInteger)
+ layer4_protocol = cybox.TypedField("Layer4_Protocol", String) |
b479fbcbd6aa620d060ea626bd0f0097ec04cf79 | plugins/libs/request.py | plugins/libs/request.py | import urllib
import json
import logging
def quote(text):
try:
return urllib.quote(text.encode('utf-8'))
except UnicodeDecodeError:
return urllib.quote(unicode(text, 'utf-8').encode('utf-8'))
def quote_plus(text):
try:
return urllib.quote_plus(text.encode('utf-8'))
except UnicodeDecodeError:
return urllib.quote_plus(unicode(text, 'utf-8').encode('utf-8'))
def get(url):
try:
return urllib.urlopen(url).read()
except urllib.error.HTTPError as err:
logging.error(err)
def ajax(url):
data = get(url)
if data:
logging.info('got data from ' + url)
logging.info(data)
return json.loads(data)
| import urllib
import json
import logging
def quote(text):
try:
return urllib.quote(text.encode('utf-8'))
except UnicodeDecodeError:
return urllib.quote(unicode(text, 'utf-8').encode('utf-8'))
def quote_plus(text):
try:
return urllib.quote_plus(text.encode('utf-8'))
except UnicodeDecodeError:
return urllib.quote_plus(unicode(text, 'utf-8').encode('utf-8'))
def get(url):
try:
return urllib.urlopen(url).read()
except urllib.error.HTTPError as err:
logging.error(err)
def ajax(url):
data = get(url)
if data:
logging.info('got data from ' + url)
logging.info(data)
try:
return json.loads(data)
except ValueError as err:
logging.error(err)
| Fix crash when invalid json is returned | Fix crash when invalid json is returned
| Python | apache-2.0 | numixproject/numibot,IamRafy/numibot | ---
+++
@@ -31,4 +31,7 @@
logging.info('got data from ' + url)
logging.info(data)
- return json.loads(data)
+ try:
+ return json.loads(data)
+ except ValueError as err:
+ logging.error(err) |
e0119a582ceb6a55123e8d16ccf33a0d52f7a0a9 | server/app/handlers.py | server/app/handlers.py | import os
import aiohttp
import json
from aiohttp import web
from .consts import KUDAGO_API_BASE_URL, CLIENT_DIR
async def serve_api(request):
url = '{}/{}/?{}'.format(
KUDAGO_API_BASE_URL,
request.match_info['path'],
request.query_string,
)
response = await aiohttp.get(url)
body = await response.json()
if isinstance(body, dict):
for field in ('next', 'previous'):
value = body.get(field)
if value:
body[field] = value.replace(KUDAGO_API_BASE_URL, '/api')
return web.Response(
text=json.dumps(body),
content_type='application/json'
)
async def serve_client(request):
filepath = os.path.join(CLIENT_DIR, 'index.html')
stat = os.stat(filepath)
chunk_size = 256 * 1024
response = web.StreamResponse()
response.content_type = 'text/html'
response.last_modified = stat.st_mtime
response.content_length = stat.st_size
response.start(request)
with open(filepath, 'rb') as f:
chunk = f.read(chunk_size)
while chunk:
response.write(chunk)
chunk = f.read(chunk_size)
return response
| import os
import aiohttp
import json
from aiohttp import web
from .consts import KUDAGO_API_BASE_URL, CLIENT_DIR
async def serve_api(request):
url = '{}/{}/?{}'.format(
KUDAGO_API_BASE_URL,
request.match_info['path'],
request.query_string,
)
response = await aiohttp.get(url)
body = await response.json()
if isinstance(body, dict):
for field in ('next', 'previous'):
value = body.get(field)
if value:
body[field] = value.replace(KUDAGO_API_BASE_URL, '/api')
return web.Response(
text=json.dumps(body, ensure_ascii=False),
content_type='application/json'
)
async def serve_client(request):
filepath = os.path.join(CLIENT_DIR, 'index.html')
stat = os.stat(filepath)
chunk_size = 256 * 1024
response = web.StreamResponse()
response.content_type = 'text/html'
response.last_modified = stat.st_mtime
response.content_length = stat.st_size
response.start(request)
with open(filepath, 'rb') as f:
chunk = f.read(chunk_size)
while chunk:
response.write(chunk)
chunk = f.read(chunk_size)
return response
| Return unicode from the server | Return unicode from the server
Fixes #18
| Python | mit | despawnerer/theatrics,despawnerer/theatrics,despawnerer/theatrics | ---
+++
@@ -22,7 +22,7 @@
body[field] = value.replace(KUDAGO_API_BASE_URL, '/api')
return web.Response(
- text=json.dumps(body),
+ text=json.dumps(body, ensure_ascii=False),
content_type='application/json'
)
|
cc2a600a7a68e438aa1dceb43f40c7ccd61b5df9 | apps/innovate/views.py | apps/innovate/views.py | import jingo
from innovate.utils import get_blog_feed_entries
from projects.models import Project
def splash(request):
"""Display splash page. With featured projects and news feed."""
projects = Project.objects.filter(featured=True, inactive=False)[:4]
return jingo.render(request, 'innovate/splash.html', {
'featured_projects': projects,
'blog_entries': get_blog_feed_entries(),
})
def about(request):
"""Display the about page. Simple direct to template."""
# NOTE: can't use ``django.views.generic.simple.direct_to_template``
# because we use jinja2 templates instead of Django templates.
return jingo.render(request, 'innovate/about.html')
def handle404(request):
"""Handle 404 responses."""
return jingo.render(request, 'handlers/404.html', status=404)
def handle500(request):
"""Handle server errors."""
return jingo.render(request, 'handlers/500.html', status=500)
| import jingo
from innovate.utils import get_blog_feed_entries
from projects.models import Project
def splash(request):
"""Display splash page. With featured projects and news feed."""
# refresh cache if requested
force = request.META.get('HTTP_CACHE_CONTROL') == 'no-cache'
entries = get_blog_feed_entries(force_update=force)
projects = Project.objects.filter(featured=True, inactive=False)[:4]
return jingo.render(request, 'innovate/splash.html', {
'featured_projects': projects,
'blog_entries': entries,
})
def about(request):
"""Display the about page. Simple direct to template."""
# NOTE: can't use ``django.views.generic.simple.direct_to_template``
# because we use jinja2 templates instead of Django templates.
return jingo.render(request, 'innovate/about.html')
def handle404(request):
"""Handle 404 responses."""
return jingo.render(request, 'handlers/404.html', status=404)
def handle500(request):
"""Handle server errors."""
return jingo.render(request, 'handlers/500.html', status=500)
| Add shift-refresh to update HP cache on demand. | Add shift-refresh to update HP cache on demand.
| Python | bsd-3-clause | mozilla/betafarm,mozilla/betafarm,mozilla/betafarm,mozilla/betafarm | ---
+++
@@ -6,10 +6,13 @@
def splash(request):
"""Display splash page. With featured projects and news feed."""
+ # refresh cache if requested
+ force = request.META.get('HTTP_CACHE_CONTROL') == 'no-cache'
+ entries = get_blog_feed_entries(force_update=force)
projects = Project.objects.filter(featured=True, inactive=False)[:4]
return jingo.render(request, 'innovate/splash.html', {
'featured_projects': projects,
- 'blog_entries': get_blog_feed_entries(),
+ 'blog_entries': entries,
})
|
f4691dd72c46fdc1a42f454ceec82128be33e907 | twstock/cli/__init__.py | twstock/cli/__init__.py | # -*- coding: utf-8 -*-
import argparse
from twstock.codes import __update_codes
from twstock.cli import best_four_point
from twstock.cli import stock
from twstock.cli import realtime
def run():
parser = argparse.ArgumentParser()
parser.add_argument('-b', '--bfp', nargs='+')
parser.add_argument('-s', '--stock', nargs='+')
parser.add_argument('-r', '--realtime', nargs='+')
parser.add_argument('-U', '--upgrade-codes', action='store_true', help='Update entites codes')
args = parser.parse_args()
if args.bfp:
best_four_point.run(args.bfp)
elif args.stock:
stock.run(args.stock)
elif args.realtime:
realtime.run(args.realtime)
elif args.upgrade_codes:
print('Start to update codes')
__update_codes()
print('Done!')
| # -*- coding: utf-8 -*-
65;5403;1c
import argparse
from twstock.codes import __update_codes
from twstock.cli import best_four_point
from twstock.cli import stock
from twstock.cli import realtime
def run():
parser = argparse.ArgumentParser()
parser.add_argument('-b', '--bfp', nargs='+')
parser.add_argument('-s', '--stock', nargs='+')
parser.add_argument('-r', '--realtime', nargs='+')
parser.add_argument('-U', '--upgrade-codes', action='store_true', help='Update entites codes')
args = parser.parse_args()
if args.bfp:
best_four_point.run(args.bfp)
elif args.stock:
stock.run(args.stock)
elif args.realtime:
realtime.run(args.realtime)
elif args.upgrade_codes:
print('Start to update codes')
__update_codes()
print('Done!')
else:
parser.print_help()
| Add help message to cli tool | Add help message to cli tool
| Python | mit | mlouielu/twstock,TCCinTaiwan/twstock | ---
+++
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-
+65;5403;1c
import argparse
from twstock.codes import __update_codes
from twstock.cli import best_four_point
@@ -26,3 +26,5 @@
print('Start to update codes')
__update_codes()
print('Done!')
+ else:
+ parser.print_help() |
252ffda53d494403133fdb1986c92422264406d8 | tests_app/tests/unit/serializers/models.py | tests_app/tests/unit/serializers/models.py | # -*- coding: utf-8 -*-
import os
from django.db import models
from django.conf import settings
class UserModel(models.Model):
name = models.CharField(max_length=20)
upload_to = os.path.join(settings.FILE_STORAGE_DIR, 'test_serializers')
class CommentModel(models.Model):
user = models.ForeignKey(
UserModel,
related_name='comments',
on_delete=models.CASCADE,
)
users_liked = models.ManyToManyField(UserModel, blank=True, null=True)
title = models.CharField(max_length=20)
text = models.CharField(max_length=200)
attachment = models.FileField(
upload_to=upload_to, blank=True, null=True, max_length=500)
hidden_text = models.CharField(max_length=200, blank=True, null=True)
| # -*- coding: utf-8 -*-
import os
from django.db import models
from django.conf import settings
class UserModel(models.Model):
name = models.CharField(max_length=20)
upload_to = os.path.join(settings.FILE_STORAGE_DIR, 'test_serializers')
class CommentModel(models.Model):
user = models.ForeignKey(
UserModel,
related_name='comments',
on_delete=models.CASCADE,
)
users_liked = models.ManyToManyField(UserModel, blank=True)
title = models.CharField(max_length=20)
text = models.CharField(max_length=200)
attachment = models.FileField(
upload_to=upload_to, blank=True, null=True, max_length=500)
hidden_text = models.CharField(max_length=200, blank=True, null=True)
| Fix CommentModel m2m null warning | Fix CommentModel m2m null warning
| Python | mit | chibisov/drf-extensions | ---
+++
@@ -18,7 +18,7 @@
related_name='comments',
on_delete=models.CASCADE,
)
- users_liked = models.ManyToManyField(UserModel, blank=True, null=True)
+ users_liked = models.ManyToManyField(UserModel, blank=True)
title = models.CharField(max_length=20)
text = models.CharField(max_length=200)
attachment = models.FileField( |
b2c32ac006ac62957f56c2cad90615a8f349cb8e | scanpointgenerator/point.py | scanpointgenerator/point.py | class Point(object):
"""Contains information about for each scan point
Attributes:
positions (dict): Dict of str position_name -> float position for each
scannable dimension. E.g. {"x": 0.1, "y": 2.2}
lower (dict): Dict of str position_name -> float lower_bound for each
scannable dimension. E.g. {"x": 0.95, "y": 2.15}
upper (dict): Dict of str position_name -> float upper_bound for each
scannable dimension. E.g. {"x": 1.05, "y": 2.25}
indexes (list): List of int indexes for each dataset dimension, fastest
changing last. E.g. [15]
"""
def __init__(self):
self.positions = {}
self.lower = {}
self.upper = {}
self.indexes = []
| from collections import OrderedDict
class Point(object):
"""Contains information about for each scan point
Attributes:
positions (dict): Dict of str position_name -> float position for each
scannable dimension. E.g. {"x": 0.1, "y": 2.2}
lower (dict): Dict of str position_name -> float lower_bound for each
scannable dimension. E.g. {"x": 0.95, "y": 2.15}
upper (dict): Dict of str position_name -> float upper_bound for each
scannable dimension. E.g. {"x": 1.05, "y": 2.25}
indexes (list): List of int indexes for each dataset dimension, fastest
changing last. E.g. [15]
"""
def __init__(self):
self.positions = OrderedDict()
self.lower = OrderedDict()
self.upper = OrderedDict()
self.indexes = []
| Refactor Point to use OrderedDict for positions, upper and lower | Refactor Point to use OrderedDict for positions, upper and lower
| Python | apache-2.0 | dls-controls/scanpointgenerator | ---
+++
@@ -1,3 +1,6 @@
+from collections import OrderedDict
+
+
class Point(object):
"""Contains information about for each scan point
@@ -13,7 +16,7 @@
"""
def __init__(self):
- self.positions = {}
- self.lower = {}
- self.upper = {}
+ self.positions = OrderedDict()
+ self.lower = OrderedDict()
+ self.upper = OrderedDict()
self.indexes = [] |
a560868cd6658a4a5134ce8d53a03a5f86d92d6d | dimensionful/common_units.py | dimensionful/common_units.py | """
Define some common units, so users can import the objects directly.
Copyright 2012, Casey W. Stark. See LICENSE.txt for more information.
"""
from sympy.core import Integer
from dimensionful.dimensions import *
from dimensionful.units import Unit, unit_symbols_dict
# cgs base units
g = Unit("g")
cm = Unit("cm")
s = Unit("s")
K = Unit("K")
# other cgs
dyne = Unit("dyne")
erg = Unit("erg")
esu = Unit("esu")
# SI stuff
m = Unit("m")
# times
minute = Unit("min") # can't use `min` because of Python keyword :(
hr = Unit("hr")
day = Unit("day")
yr = Unit("yr")
# solar units
Msun = Unit("Msun")
Rsun = Unit("Rsun")
Lsun = Unit("Lsun")
Tsum = Unit("Tsun")
# astro distances
AU = Unit("AU")
pc = Unit("pc")
ly = Unit("ly")
gauss = Unit("gauss")
| """
Define some common units, so users can import the objects directly.
Copyright 2012, Casey W. Stark. See LICENSE.txt for more information.
"""
from dimensionful.dimensions import *
from dimensionful.units import Unit
# cgs base units
g = Unit("g")
cm = Unit("cm")
s = Unit("s")
K = Unit("K")
# other cgs
dyne = Unit("dyne")
erg = Unit("erg")
esu = Unit("esu")
# SI stuff
m = Unit("m")
# times
minute = Unit("min") # can't use `min` because of Python keyword :(
hr = Unit("hr")
day = Unit("day")
yr = Unit("yr")
# solar units
Msun = Unit("Msun")
Rsun = Unit("Rsun")
Lsun = Unit("Lsun")
Tsum = Unit("Tsun")
# astro distances
AU = Unit("AU")
pc = Unit("pc")
ly = Unit("ly")
gauss = Unit("gauss")
| Remove imports we don't need anymore. | Remove imports we don't need anymore. | Python | bsd-2-clause | caseywstark/dimensionful | ---
+++
@@ -6,10 +6,8 @@
"""
-from sympy.core import Integer
-
from dimensionful.dimensions import *
-from dimensionful.units import Unit, unit_symbols_dict
+from dimensionful.units import Unit
# cgs base units
g = Unit("g") |
e9c45c30203a3b100ab897dd2337985790b07dff | autoload/tsurf/core.py | autoload/tsurf/core.py | # -*- coding: utf-8 -*-
"""
tsurf.core
~~~~~~~~~~
This module defines the TagSurfer class. This class serve two purpose:
1) Defines the methods that are used by tsurf-owned vim commands.
2) Creates all tsurf components and acts as a brigde among them.
"""
import vim
from tsurf import ui
from tsurf import finder
from tsurf import services
class TagSurfer:
def __init__(self):
self.services = services.Services(self)
self.finder = finder.Finder(self)
self.ui = ui.UserInterface(self)
def close(self):
"""To performs cleanup actions."""
self.finder.close()
def Open(self):
"""To open the Tag Surfer user interface."""
self.ui.open()
def SetProjectRoot(self, root=""):
"""To set the current project root to the current working directory or
to the directory passed as argument."""
self.services.curr_project.set_root(
root if root else vim.eval("getcwd()"))
def UnsetProjectRoot(self):
"""To unset the current project root."""
self.services.curr_project.set_root("")
| # -*- coding: utf-8 -*-
"""
tsurf.core
~~~~~~~~~~
This module defines the TagSurfer class. This class serve two purpose:
1) Defines the methods that are used by tsurf-owned vim commands.
2) Creates all tsurf components and acts as a brigde among them.
"""
import os
import vim
from tsurf import ui
from tsurf import finder
from tsurf import services
class TagSurfer:
def __init__(self):
self.services = services.Services(self)
self.finder = finder.Finder(self)
self.ui = ui.UserInterface(self)
def close(self):
"""To performs cleanup actions."""
self.finder.close()
def Open(self):
"""To open the Tag Surfer user interface."""
self.ui.open()
def SetProjectRoot(self, root=""):
"""To set the current project root to the current working directory or
to the directory passed as argument."""
home = os.path.expanduser("~")
if root.startswith("~"):
root = root.replace("~", home)
elif root.startswith("$HOME"):
root = root.replace("$HOME", home)
self.services.curr_project.set_root(
root if root else vim.eval("getcwd()"))
def UnsetProjectRoot(self):
"""To unset the current project root."""
self.services.curr_project.set_root("")
| Improve usability of the command "TsurfSetRoot" | Improve usability of the command "TsurfSetRoot"
| Python | mit | bossmido/tag-surfer,bossmido/tag-surfer,bossmido/tag-surfer | ---
+++
@@ -10,6 +10,7 @@
"""
+import os
import vim
from tsurf import ui
@@ -35,6 +36,11 @@
def SetProjectRoot(self, root=""):
"""To set the current project root to the current working directory or
to the directory passed as argument."""
+ home = os.path.expanduser("~")
+ if root.startswith("~"):
+ root = root.replace("~", home)
+ elif root.startswith("$HOME"):
+ root = root.replace("$HOME", home)
self.services.curr_project.set_root(
root if root else vim.eval("getcwd()"))
|
a2ad75b8dac515d1bbc49c32257c62a7da59e2e1 | semantic_release/helpers.py | semantic_release/helpers.py | import configparser
import semver
from invoke import run
def get_current_version():
return run('python setup.py --version', hide=True).stdout.strip()
def evaluate_version_bump(force=None):
if force:
return force
return 'patch'
def get_new_version(current_version, level_bump):
return getattr(semver, 'bump_{0}'.format(level_bump))(current_version)
def set_new_version(current_version):
return True
def load_config():
config = configparser.ConfigParser()
with open(os.path.join(os.getcwd(), 'setup.cfg')) as f:
config.read_file(f)
return config._sections['semantic_release']
| import configparser
import os
import re
import semver
from invoke import run
def get_current_version():
return run('python setup.py --version', hide=True).stdout.strip()
def evaluate_version_bump(force=None):
if force:
return force
return 'patch'
def get_new_version(current_version, level_bump):
return getattr(semver, 'bump_{0}'.format(level_bump))(current_version)
def set_new_version(new_version):
filename, variable = load_config().get('version_variable').split(':')
variable = variable.strip()
with open(filename, mode='r') as fr:
content = fr.read()
content = re.sub(
r'{} ?= ?["\']\d+\.\d+(?:\.\d+)?["\']'.format(variable),
'{} = \'{}\''.format(variable, new_version),
content
)
with open(filename, mode='w') as fw:
fw.write(content)
return True
def load_config():
config = configparser.ConfigParser()
with open(os.path.join(os.getcwd(), 'setup.cfg')) as f:
config.read_file(f)
return config._sections['semantic_release']
| Implement setting of new version | :sparkles: Implement setting of new version
| Python | mit | riddlesio/python-semantic-release,relekang/python-semantic-release,relekang/python-semantic-release,wlonk/python-semantic-release,jvrsantacruz/python-semantic-release | ---
+++
@@ -1,4 +1,6 @@
import configparser
+import os
+import re
import semver
from invoke import run
@@ -17,7 +19,20 @@
return getattr(semver, 'bump_{0}'.format(level_bump))(current_version)
-def set_new_version(current_version):
+def set_new_version(new_version):
+ filename, variable = load_config().get('version_variable').split(':')
+ variable = variable.strip()
+ with open(filename, mode='r') as fr:
+ content = fr.read()
+
+ content = re.sub(
+ r'{} ?= ?["\']\d+\.\d+(?:\.\d+)?["\']'.format(variable),
+ '{} = \'{}\''.format(variable, new_version),
+ content
+ )
+
+ with open(filename, mode='w') as fw:
+ fw.write(content)
return True
|
25ff50839e50a46b4e973acf0a6ae28472a71473 | wait-for-statuses.py | wait-for-statuses.py | import urllib.request
import json
import subprocess
import time
import os
# We're limited to this number by GH Actions API
# https://docs.github.com/en/free-pro-team@latest/rest/reference/actions#list-jobs-for-a-workflow-run
max_jobs=100
status_url = "https://api.github.com/repos/" \
+ os.environ['GITHUB_REPOSITORY'] \
+ "/actions/runs/" \
+ os.environ['GITHUB_RUN_ID'] \
+ "/jobs" \
+ "?per_page=" + str(max_jobs)
numOfJobs = int(os.environ['NUM_OF_JOBS'])
while(True):
time.sleep(60)
countCompleted = 0
with urllib.request.urlopen(status_url) as url:
data = json.loads(url.read().decode())
for j in data["jobs"]:
if(j["status"] == "completed"):
countCompleted += 1
print("Completed jobs:" + str(countCompleted) + ". Jobs overall: " + str(numOfJobs))
if(countCompleted >= numOfJobs):
break
subprocess.call(os.environ['GITHUB_WORKSPACE'] + "/.github/scripts/master-package.sh")
subprocess.call(os.environ['GITHUB_WORKSPACE'] + "/.github/scripts/cleanup-anaconda.sh")
| import urllib.request
import json
import subprocess
import time
import os
import sys
# We're limited to this number by GH Actions API
# https://docs.github.com/en/free-pro-team@latest/rest/reference/actions#list-jobs-for-a-workflow-run
max_jobs=100
status_url = "https://api.github.com/repos/" \
+ os.environ['GITHUB_REPOSITORY'] \
+ "/actions/runs/" \
+ os.environ['GITHUB_RUN_ID'] \
+ "/jobs" \
+ "?per_page=" + str(max_jobs)
numOfJobs = int(os.environ['NUM_OF_JOBS'])
if(numOfJobs > max_jobs):
sys.exit("ERROR: number of jobs exceeded max_jobs: " + str(max_jobs))
while(True):
time.sleep(60)
countCompleted = 0
with urllib.request.urlopen(status_url) as url:
data = json.loads(url.read().decode())
for j in data["jobs"]:
if(j["status"] == "completed"):
countCompleted += 1
print("Completed jobs:" + str(countCompleted) + ". Jobs overall: " + str(numOfJobs))
if(countCompleted >= numOfJobs):
break
subprocess.call(os.environ['GITHUB_WORKSPACE'] + "/.github/scripts/master-package.sh")
subprocess.call(os.environ['GITHUB_WORKSPACE'] + "/.github/scripts/cleanup-anaconda.sh")
| Return an error when number of jobs exceeds max_jobs | Return an error when number of jobs exceeds max_jobs
ghactions API call we're using limits number of jobs
returned in one call. If jobs exceed this number they are
grouped into "pages". Page handling code shall be added
when we exceed this number.
| Python | apache-2.0 | litex-hub/litex-conda-ci,litex-hub/litex-conda-ci | ---
+++
@@ -3,6 +3,7 @@
import subprocess
import time
import os
+import sys
# We're limited to this number by GH Actions API
# https://docs.github.com/en/free-pro-team@latest/rest/reference/actions#list-jobs-for-a-workflow-run
@@ -16,6 +17,10 @@
+ "?per_page=" + str(max_jobs)
numOfJobs = int(os.environ['NUM_OF_JOBS'])
+
+
+if(numOfJobs > max_jobs):
+ sys.exit("ERROR: number of jobs exceeded max_jobs: " + str(max_jobs))
while(True):
time.sleep(60) |
18e1e0a1c1b4492e623d5b86d7a23fff00d5fa72 | pysingcells/__main__.py | pysingcells/__main__.py | #!/usr/bin/env python3
# std import
import os
import sys
import configparser
from subprocess import call
# project import
from . import logger
from .mapper import hisat2
def main(config_path):
""" Main function of pro'gramme read configuration and run enable step """
config = configparser.ConfigParser()
logger.setup_logging(**config)
config.read(config_path)
print(config.sections())
for key in config['paths']: print(config['paths'][key])
def trimming(files_dir, rep_out , paired=1) :
file_list = os.listdir(files_dir)
for fastq in file_list :
call(['cmd', 'options...'])
if __name__ == "__main__":
main(sys.argv[1])
| #!/usr/bin/env python3
# std import
import os
import sys
import configparser
from subprocess import call
# project import
from . import logger
from .mapper import hisat2
def main(config_path):
""" Main function of pro'gramme read configuration and run enable step """
config = configparser.ConfigParser()
config.read(config_path)
print(config.sections())
logger.setup_logging(**config)
for key in config['paths']: print(config['paths'][key])
mapper = hisat2.Hisat2()
mapper.read_configuration(**config)
if mapper.check_configuration() :
mapper.run()
def trimming(files_dir, rep_out , paired=1) :
file_list = os.listdir(files_dir)
for fastq in file_list :
call(['cmd', 'options...'])
if __name__ == "__main__":
main(sys.argv[1])
| Add test of hisat2 object | Add test of hisat2 object
| Python | mit | Fougere87/pysingcells | ---
+++
@@ -15,13 +15,16 @@
""" Main function of pro'gramme read configuration and run enable step """
config = configparser.ConfigParser()
- logger.setup_logging(**config)
-
config.read(config_path)
print(config.sections())
+ logger.setup_logging(**config)
for key in config['paths']: print(config['paths'][key])
+ mapper = hisat2.Hisat2()
+ mapper.read_configuration(**config)
+ if mapper.check_configuration() :
+ mapper.run()
def trimming(files_dir, rep_out , paired=1) :
file_list = os.listdir(files_dir) |
b67ee17b401df9dec4f76f1a24cef2a7ce25406b | 1-moderate/locks/main.py | 1-moderate/locks/main.py | import sys
def do_lock_pass(locked):
for i in xrange(0, len(locked), 2):
locked[i] = True
def do_flip_pass(locked):
for i in xrange(0, len(locked), 3):
locked[i] = not locked[i]
def count_unlocked(locked):
result = 0
for l in locked:
if not l: result += 1
return result
def main():
test_cases = open(sys.argv[1], 'r')
for test in test_cases:
test = test.strip()
num_locks = int(test.split(' ')[0])
num_iterations = int(test.split(' ')[1])
locked = [False] * num_locks
for i in xrange(num_iterations-1):
do_lock_pass(locked)
do_flip_pass(locked)
locked[-1] = True
print count_unlocked(locked)
test_cases.close()
main()
| import sys
def do_lock_pass(locked):
for i in xrange(1, len(locked), 2):
locked[i] = True
def do_flip_pass(locked):
for i in xrange(2, len(locked), 3):
locked[i] = not locked[i]
def count_unlocked(locked):
result = 0
for l in locked:
if not l: result += 1
return result
def main():
test_cases = open(sys.argv[1], 'r')
for test in test_cases:
test = test.strip()
num_locks = int(test.split(' ')[0])
num_iterations = int(test.split(' ')[1])
locked = [False] * num_locks
for i in xrange(num_iterations-1):
do_lock_pass(locked)
do_flip_pass(locked)
locked[-1] = not locked[-1]
print count_unlocked(locked)
test_cases.close()
main()
| Fix solution to the locks problem. | Fix solution to the locks problem.
| Python | unlicense | mpillar/codeeval,mpillar/codeeval,mpillar/codeeval,mpillar/codeeval | ---
+++
@@ -1,11 +1,11 @@
import sys
def do_lock_pass(locked):
- for i in xrange(0, len(locked), 2):
+ for i in xrange(1, len(locked), 2):
locked[i] = True
def do_flip_pass(locked):
- for i in xrange(0, len(locked), 3):
+ for i in xrange(2, len(locked), 3):
locked[i] = not locked[i]
def count_unlocked(locked):
@@ -26,7 +26,7 @@
do_lock_pass(locked)
do_flip_pass(locked)
- locked[-1] = True
+ locked[-1] = not locked[-1]
print count_unlocked(locked)
test_cases.close() |
4f635c9a90bfa74bb489db1a8a84c5e36d475e5b | scheduling/__init__.py | scheduling/__init__.py | from aiohttp.web import Application
from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from scheduling.deadlines import deadline_scheduler
def setup(app: Application) -> None:
jobstore = SQLAlchemyJobStore(engine=app["db"])
jobstores = {"default": jobstore}
scheduler = AsyncIOScheduler(jobstores=jobstores)
scheduler.start()
scheduler.print_jobs()
app["scheduler"] = scheduler
# TODO: Remove
scheduler.remove_all_jobs()
from db_helper import get_most_recent_group
from datetime import datetime, timedelta
deadlines.schedule_deadline(app,
get_most_recent_group(app["session"]),
"student_choice",
datetime.now()+timedelta(seconds=15),
pester_users=False)
| from aiohttp.web import Application
from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from scheduling.deadlines import deadline_scheduler
def setup(app: Application) -> None:
jobstore = SQLAlchemyJobStore(engine=app["db"])
jobstores = {"default": jobstore}
scheduler = AsyncIOScheduler(jobstores=jobstores,
job_defaults={"misfire_grace_time": 31 * 24 * 60 * 60})
scheduler.start()
scheduler.print_jobs()
app["scheduler"] = scheduler
# TODO: Remove
scheduler.remove_all_jobs()
#from db_helper import get_most_recent_group
#from datetime import datetime, timedelta
#deadlines.schedule_deadline(app,
# get_most_recent_group(app["session"]),
# "student_choice",
# datetime.now()+timedelta(seconds=15),
# pester_users=False)
| Set job misfire time to 31 days so the system will still work if it's inactive for a while | Set job misfire time to 31 days so the system will still work
if it's inactive for a while
| Python | agpl-3.0 | wtsi-hgi/CoGS-Webapp,wtsi-hgi/CoGS-Webapp,wtsi-hgi/CoGS-Webapp | ---
+++
@@ -8,17 +8,19 @@
def setup(app: Application) -> None:
jobstore = SQLAlchemyJobStore(engine=app["db"])
jobstores = {"default": jobstore}
- scheduler = AsyncIOScheduler(jobstores=jobstores)
+ scheduler = AsyncIOScheduler(jobstores=jobstores,
+ job_defaults={"misfire_grace_time": 31 * 24 * 60 * 60})
scheduler.start()
scheduler.print_jobs()
app["scheduler"] = scheduler
# TODO: Remove
scheduler.remove_all_jobs()
- from db_helper import get_most_recent_group
- from datetime import datetime, timedelta
- deadlines.schedule_deadline(app,
- get_most_recent_group(app["session"]),
- "student_choice",
- datetime.now()+timedelta(seconds=15),
- pester_users=False)
+
+ #from db_helper import get_most_recent_group
+ #from datetime import datetime, timedelta
+ #deadlines.schedule_deadline(app,
+ # get_most_recent_group(app["session"]),
+ # "student_choice",
+ # datetime.now()+timedelta(seconds=15),
+ # pester_users=False) |
b5852d1b579325b5ef5d8d7aebca53f1fb9bae04 | pyads/utils.py | pyads/utils.py | # -*- coding: utf-8 -*-
"""Utility functions.
:author: Stefan Lehmann <stlm@posteo.de>
:license: MIT, see license file or https://opensource.org/licenses/MIT
:created on: 2018-06-11 18:15:53
:last modified by: Stefan Lehmann
:last modified time: 2018-07-12 14:11:12
"""
import sys
from ctypes import c_ubyte
def platform_is_linux():
# type: () -> bool
"""Return True if current platform is Linux or Mac OS."""
return sys.platform.startswith('linux') or \
sys.platform.startswith('darwin')
def platform_is_windows():
# type: () -> bool
"""Return True if current platform is Windows."""
return sys.platform == 'win32'
| # -*- coding: utf-8 -*-
"""Utility functions.
:author: Stefan Lehmann <stlm@posteo.de>
:license: MIT, see license file or https://opensource.org/licenses/MIT
:created on: 2018-06-11 18:15:53
:last modified by: Stefan Lehmann
:last modified time: 2018-07-12 14:11:12
"""
import sys
from ctypes import c_ubyte
def platform_is_linux():
# type: () -> bool
"""Return True if current platform is Linux or Mac OS."""
return sys.platform.startswith('linux') or \
sys.platform.startswith('darwin')
def platform_is_windows():
# type: () -> bool
"""Return True if current platform is Windows."""
# cli being .NET (IronPython)
return sys.platform == 'win32' or sys.platform == 'cli'
| Add 'cli' as being a platform recognized as a Windows platform. | Add 'cli' as being a platform recognized as a Windows platform.
This will be the case when using e.g. IronPython (.NET).
| Python | mit | MrLeeh/pyads | ---
+++
@@ -23,4 +23,5 @@
def platform_is_windows():
# type: () -> bool
"""Return True if current platform is Windows."""
- return sys.platform == 'win32'
+ # cli being .NET (IronPython)
+ return sys.platform == 'win32' or sys.platform == 'cli' |
6ca4d689b863aa1caed7d51f8b45951e508fe8bc | tests/test_pandora/test_transport.py | tests/test_pandora/test_transport.py | import time
from unittest import TestCase
from pandora.py2compat import Mock, call
from tests.test_pandora.test_clientbuilder import TestSettingsDictBuilder
class SysCallError(IOError):
pass
class TestTransport(TestCase):
def test_call_should_retry_max_times_on_sys_call_error(self):
with self.assertRaises(SysCallError):
client = TestSettingsDictBuilder._build_minimal()
time.sleep = Mock()
client.transport._make_http_request = Mock(
side_effect=SysCallError("mock_error"))
client.transport._start_request = Mock()
client("method")
client.transport._start_request.assert_has_calls([call("method")])
assert client.transport._start_request.call_count == 5
| import time
from unittest import TestCase
from pandora.py2compat import Mock, call
from tests.test_pandora.test_clientbuilder import TestSettingsDictBuilder
class SysCallError(Exception):
pass
class TestTransport(TestCase):
def test_call_should_retry_max_times_on_sys_call_error(self):
with self.assertRaises(SysCallError):
client = TestSettingsDictBuilder._build_minimal()
time.sleep = Mock()
client.transport._make_http_request = Mock(
side_effect=SysCallError("mock_error"))
client.transport._start_request = Mock()
client("method")
client.transport._start_request.assert_has_calls([call("method")])
assert client.transport._start_request.call_count == 5
| Align base exception for test with what pyOpenSSL uses. | Align base exception for test with what pyOpenSSL uses.
| Python | mit | mcrute/pydora | ---
+++
@@ -6,7 +6,7 @@
from tests.test_pandora.test_clientbuilder import TestSettingsDictBuilder
-class SysCallError(IOError):
+class SysCallError(Exception):
pass
|
952289a08784bc0ee86dee6239025397395f7033 | tests/conftest.py | tests/conftest.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Contains pytest fixtures which are globally available throughout the suite.
"""
import pytest
@pytest.fixture
def foobar():
pass
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
conftest
--------
Contains pytest fixtures which are globally available throughout the suite.
"""
import pytest
@pytest.fixture
def foobar():
pass
| Change doc str to sphinx format | Change doc str to sphinx format
| Python | bsd-3-clause | sp1rs/cookiecutter,vincentbernat/cookiecutter,cguardia/cookiecutter,willingc/cookiecutter,drgarcia1986/cookiecutter,kkujawinski/cookiecutter,drgarcia1986/cookiecutter,michaeljoseph/cookiecutter,ionelmc/cookiecutter,audreyr/cookiecutter,takeflight/cookiecutter,dajose/cookiecutter,letolab/cookiecutter,jhermann/cookiecutter,0k/cookiecutter,janusnic/cookiecutter,willingc/cookiecutter,luzfcb/cookiecutter,foodszhang/cookiecutter,tylerdave/cookiecutter,audreyr/cookiecutter,christabor/cookiecutter,lgp171188/cookiecutter,benthomasson/cookiecutter,terryjbates/cookiecutter,cguardia/cookiecutter,sp1rs/cookiecutter,venumech/cookiecutter,moi65/cookiecutter,stevepiercy/cookiecutter,michaeljoseph/cookiecutter,vincentbernat/cookiecutter,nhomar/cookiecutter,vintasoftware/cookiecutter,pjbull/cookiecutter,jhermann/cookiecutter,janusnic/cookiecutter,cichm/cookiecutter,hackebrot/cookiecutter,moi65/cookiecutter,lgp171188/cookiecutter,Vauxoo/cookiecutter,letolab/cookiecutter,vintasoftware/cookiecutter,lucius-feng/cookiecutter,terryjbates/cookiecutter,hackebrot/cookiecutter,christabor/cookiecutter,pjbull/cookiecutter,kkujawinski/cookiecutter,atlassian/cookiecutter,cichm/cookiecutter,ramiroluz/cookiecutter,0k/cookiecutter,luzfcb/cookiecutter,nhomar/cookiecutter,dajose/cookiecutter,agconti/cookiecutter,tylerdave/cookiecutter,ionelmc/cookiecutter,venumech/cookiecutter,benthomasson/cookiecutter,agconti/cookiecutter,foodszhang/cookiecutter,Springerle/cookiecutter,Springerle/cookiecutter,ramiroluz/cookiecutter,stevepiercy/cookiecutter,lucius-feng/cookiecutter,atlassian/cookiecutter,Vauxoo/cookiecutter,takeflight/cookiecutter | ---
+++
@@ -1,7 +1,11 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
-"""Contains pytest fixtures which are globally available throughout the suite.
+"""
+conftest
+--------
+
+Contains pytest fixtures which are globally available throughout the suite.
"""
import pytest |
725f5b12c43380e239d6a511a9435577dda37b49 | astropy/utils/compat/_subprocess_py2/__init__.py | astropy/utils/compat/_subprocess_py2/__init__.py | from __future__ import absolute_import
from subprocess import *
def check_output(*popenargs, **kwargs):
r"""Run command with arguments and return its output as a byte
string.
If the exit code was non-zero it raises a CalledProcessError. The
CalledProcessError object will have the return code in the
returncode
attribute and output in the output attribute.
The arguments are the same as for the Popen constructor. Example::
>>> check_output(["ls", "-l", "/dev/null"])
'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
The stdout argument is not allowed as it is used internally.
To capture standard error in the result, use stderr=STDOUT.::
>>> check_output(["/bin/sh", "-c",
... "ls -l non_existent_file ; exit 0"],
... stderr=STDOUT)
'ls: non_existent_file: No such file or directory\n'
"""
if 'stdout' in kwargs:
raise ValueError('stdout argument not allowed, it will be overridden.')
process = Popen(stdout=PIPE, *popenargs, **kwargs)
output, unused_err = process.communicate()
retcode = process.poll()
if retcode:
cmd = kwargs.get("args")
if cmd is None:
cmd = popenargs[0]
raise subprocess.CalledProcessError(retcode, cmd)
return output
| from __future__ import absolute_import
from subprocess import *
def check_output(*popenargs, **kwargs):
r"""Run command with arguments and return its output as a byte
string.
If the exit code was non-zero it raises a CalledProcessError. The
CalledProcessError object will have the return code in the
returncode
attribute and output in the output attribute.
The arguments are the same as for the Popen constructor. Example::
>>> check_output(["ls", "-l", "/dev/null"])
'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
The stdout argument is not allowed as it is used internally.
To capture standard error in the result, use stderr=STDOUT.::
>>> check_output(["/bin/sh", "-c",
... "ls -l non_existent_file ; exit 0"],
... stderr=STDOUT)
'ls: non_existent_file: No such file or directory\n'
"""
if 'stdout' in kwargs:
raise ValueError('stdout argument not allowed, it will be overridden.')
process = Popen(stdout=PIPE, *popenargs, **kwargs)
output, unused_err = process.communicate()
retcode = process.poll()
if retcode:
cmd = kwargs.get("args")
if cmd is None:
cmd = popenargs[0]
raise CalledProcessError(retcode, cmd)
return output
| Fix subprocess on Python 2.6 | Fix subprocess on Python 2.6
| Python | bsd-3-clause | bsipocz/astropy,kelle/astropy,lpsinger/astropy,MSeifert04/astropy,AustereCuriosity/astropy,AustereCuriosity/astropy,joergdietrich/astropy,mhvk/astropy,DougBurke/astropy,astropy/astropy,joergdietrich/astropy,StuartLittlefair/astropy,tbabej/astropy,kelle/astropy,stargaser/astropy,funbaker/astropy,AustereCuriosity/astropy,larrybradley/astropy,aleksandr-bakanov/astropy,joergdietrich/astropy,lpsinger/astropy,dhomeier/astropy,saimn/astropy,lpsinger/astropy,stargaser/astropy,stargaser/astropy,mhvk/astropy,mhvk/astropy,funbaker/astropy,larrybradley/astropy,funbaker/astropy,AustereCuriosity/astropy,mhvk/astropy,pllim/astropy,larrybradley/astropy,pllim/astropy,funbaker/astropy,astropy/astropy,bsipocz/astropy,astropy/astropy,stargaser/astropy,saimn/astropy,StuartLittlefair/astropy,DougBurke/astropy,larrybradley/astropy,DougBurke/astropy,kelle/astropy,pllim/astropy,kelle/astropy,joergdietrich/astropy,MSeifert04/astropy,pllim/astropy,MSeifert04/astropy,aleksandr-bakanov/astropy,tbabej/astropy,bsipocz/astropy,lpsinger/astropy,AustereCuriosity/astropy,lpsinger/astropy,mhvk/astropy,astropy/astropy,StuartLittlefair/astropy,aleksandr-bakanov/astropy,tbabej/astropy,aleksandr-bakanov/astropy,kelle/astropy,dhomeier/astropy,StuartLittlefair/astropy,tbabej/astropy,saimn/astropy,larrybradley/astropy,saimn/astropy,DougBurke/astropy,dhomeier/astropy,MSeifert04/astropy,StuartLittlefair/astropy,joergdietrich/astropy,dhomeier/astropy,astropy/astropy,bsipocz/astropy,tbabej/astropy,pllim/astropy,saimn/astropy,dhomeier/astropy | ---
+++
@@ -34,5 +34,5 @@
cmd = kwargs.get("args")
if cmd is None:
cmd = popenargs[0]
- raise subprocess.CalledProcessError(retcode, cmd)
+ raise CalledProcessError(retcode, cmd)
return output |
098044c80fff2ff639da088f87f7fc6952813fc1 | txircd/channel.py | txircd/channel.py | from txircd.utils import CaseInsensitiveDictionary, now()
class IRCChannel(object):
def __init__(self, ircd, name):
self.ircd = ircd
self.name = name
self.created = now()
self.topic = ""
self.topicSetter = ""
self.topicTime = now()
self.mode = {}
self.users = CaseInsensitiveDictionary()
self.metadata = {}
self.cache = {}
def modeString(self, user):
modes = "+"
params = []
for mode, param in self.mode.iteritems():
modetype = self.ircd.channel_mode_type[mode]
if modetype > 0:
modes += mode
if param:
params.append(self.ircd.channel_modes[modetype][mode].showParam(user, param))
return ("{} {}".format(modes, " ".join(params)) if params else modes)
def setTopic(self, topic, setter):
self.topic = topic
self.topicSetter = setter
self.topicTime = now()
def getMetadata(self, key):
if key in self.metadata:
return self.metadata[key]
return "" | from txircd.utils import CaseInsensitiveDictionary, now()
class IRCChannel(object):
def __init__(self, ircd, name):
self.ircd = ircd
self.name = name
self.created = now()
self.topic = ""
self.topicSetter = ""
self.topicTime = now()
self.mode = {}
self.users = CaseInsensitiveDictionary()
self.metadata = {}
self.cache = {}
def modeString(self, user):
modes = [] # Since we're appending characters to this string, it's more efficient to store the array of characters and join it rather than keep making new strings
params = []
for mode, param in self.mode.iteritems():
modetype = self.ircd.channel_mode_type[mode]
if modetype > 0:
modes.append(mode)
if param:
params.append(self.ircd.channel_modes[modetype][mode].showParam(user, param))
return ("+{} {}".format("".join(modes), " ".join(params)) if params else "".join(modes))
def setTopic(self, topic, setter):
self.topic = topic
self.topicSetter = setter
self.topicTime = now()
def getMetadata(self, key):
if key in self.metadata:
return self.metadata[key]
return "" | Change how mode strings are constructed | Change how mode strings are constructed
| Python | bsd-3-clause | DesertBus/txircd,Heufneutje/txircd,ElementalAlchemist/txircd | ---
+++
@@ -14,15 +14,15 @@
self.cache = {}
def modeString(self, user):
- modes = "+"
+ modes = [] # Since we're appending characters to this string, it's more efficient to store the array of characters and join it rather than keep making new strings
params = []
for mode, param in self.mode.iteritems():
modetype = self.ircd.channel_mode_type[mode]
if modetype > 0:
- modes += mode
+ modes.append(mode)
if param:
params.append(self.ircd.channel_modes[modetype][mode].showParam(user, param))
- return ("{} {}".format(modes, " ".join(params)) if params else modes)
+ return ("+{} {}".format("".join(modes), " ".join(params)) if params else "".join(modes))
def setTopic(self, topic, setter):
self.topic = topic |
749aa35a85b6482cfba9dec7d37473a787d73c32 | integration-test/1106-merge-ocean-earth.py | integration-test/1106-merge-ocean-earth.py | # There should be a single (merged) ocean feature in this tile
assert_less_than_n_features(9, 167, 186, 'water', {'kind': 'ocean'}, 2)
# There should be a single (merged) earth feature in this tile
assert_less_than_n_features(9, 170, 186, 'earth', {'kind': 'earth'}, 2)
| # There should be a single, merged feature in each of these tiles
# Natural Earth
assert_less_than_n_features(5, 11, 11, 'water', {'kind': 'ocean'}, 2)
assert_less_than_n_features(5, 8, 11, 'earth', {'kind': 'earth'}, 2)
# OpenStreetMap
assert_less_than_n_features(9, 167, 186, 'water', {'kind': 'ocean'}, 2)
assert_less_than_n_features(9, 170, 186, 'earth', {'kind': 'earth'}, 2)
| Add lowzoom tests for polygon merging | Add lowzoom tests for polygon merging
| Python | mit | mapzen/vector-datasource,mapzen/vector-datasource,mapzen/vector-datasource | ---
+++
@@ -1,4 +1,9 @@
-# There should be a single (merged) ocean feature in this tile
+# There should be a single, merged feature in each of these tiles
+
+# Natural Earth
+assert_less_than_n_features(5, 11, 11, 'water', {'kind': 'ocean'}, 2)
+assert_less_than_n_features(5, 8, 11, 'earth', {'kind': 'earth'}, 2)
+
+# OpenStreetMap
assert_less_than_n_features(9, 167, 186, 'water', {'kind': 'ocean'}, 2)
-# There should be a single (merged) earth feature in this tile
assert_less_than_n_features(9, 170, 186, 'earth', {'kind': 'earth'}, 2) |
7812934504c299464227c4f8cd28cacc2b904008 | test/run_tests.py | test/run_tests.py | import platform
from unittest import main
from test_net_use_table import *
from test_sanitize import *
from test_utils import *
from test_unc_directory import *
if platform.system() == 'Windows':
print 'Including Windows-specific tests'
from test_connecting import *
else:
print 'WARNING: Excluding Windows-specific tests because host is not Windows'
if __name__ == '__main__':
main()
| import platform
from unittest import main
from test_net_use_table import *
from test_sanitize import *
from test_utils import *
from test_unc_directory import *
if platform.system() == 'Windows':
print 'Including Windows-specific tests'
from test_connecting import *
else:
print 'WARNING: Excluding Windows-specific tests because host is not Windows'
if __name__ == '__main__':
main()
| Use spaces instead of tabs | Use spaces instead of tabs
| Python | mit | nithinphilips/py_win_unc,CovenantEyes/py_win_unc | ---
+++
@@ -8,10 +8,10 @@
if platform.system() == 'Windows':
- print 'Including Windows-specific tests'
- from test_connecting import *
+ print 'Including Windows-specific tests'
+ from test_connecting import *
else:
- print 'WARNING: Excluding Windows-specific tests because host is not Windows'
+ print 'WARNING: Excluding Windows-specific tests because host is not Windows'
if __name__ == '__main__': |
6cd640eb09d674afaff1c96e69322705a843dde9 | src/commands/user/user.py | src/commands/user/user.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
User command...
"""
import grp
class User(object):
"""Something, something, something darkside...."""
def __init__(self, settingsInstance, commandInstance, cmdName, *args):
super(User, self).__init__()
self.settingsInstance = settingsInstance
self.commandInstance = commandInstance
if cmdName is not None:
if args[0] is not None:
getattr(self, cmdName)(*args)
else:
getattr(self, cmdName)()
def test(self):
self.commandInstance.replyWithMessage(
self.commandInstance.user
)
def users(self):
"""Get a list of users in the users group."""
self.commandInstance.replyWithMessage(self._users())
def _users(self, output='string'):
for group in grp.getgrall():
if group.gr_name == 'users':
members = group.gr_mem
if output == 'list':
return members
else:
return ', '.join(members)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
User command...
"""
import grp
class User(object):
"""Something, something, something darkside...."""
def __init__(self, settingsInstance, commandInstance, cmdName, *args):
super(User, self).__init__()
self.settingsInstance = settingsInstance
self.commandInstance = commandInstance
if cmdName is not None:
if args[0] is not None:
getattr(self, cmdName)(*args)
else:
getattr(self, cmdName)()
def testuser(self):
self.commandInstance.replyWithMessage(
self.commandInstance.user
)
def testchannel(self):
self.commandInstance.replyWithMessage(
self.commandInstance.channel
)
def users(self):
"""Get a list of users in the users group."""
self.commandInstance.replyWithMessage(self._users())
def _users(self, output='string'):
for group in grp.getgrall():
if group.gr_name == 'users':
members = group.gr_mem
if output == 'list':
return members
else:
return ', '.join(members)
| Test if you can return the channel. | Test if you can return the channel.
| Python | bsd-3-clause | Tehnix/PyIRCb | ---
+++
@@ -21,9 +21,14 @@
else:
getattr(self, cmdName)()
- def test(self):
+ def testuser(self):
self.commandInstance.replyWithMessage(
self.commandInstance.user
+ )
+
+ def testchannel(self):
+ self.commandInstance.replyWithMessage(
+ self.commandInstance.channel
)
def users(self): |
030265cc2dca23e256bdce59b2bd0cb77e88ca74 | InvenTree/stock/forms.py | InvenTree/stock/forms.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django import forms
from InvenTree.forms import HelperForm
from .models import StockLocation, StockItem
class EditStockLocationForm(HelperForm):
class Meta:
model = StockLocation
fields = [
'name',
'parent',
'description'
]
class CreateStockItemForm(HelperForm):
class Meta:
model = StockItem
fields = [
'part',
'supplier_part',
'location',
'belongs_to',
'serial',
'batch',
'quantity',
'status',
# 'customer',
'URL',
]
class MoveStockItemForm(forms.ModelForm):
note = forms.CharField(label='Notes', required=True, help_text='Add note (required)')
class Meta:
model = StockItem
fields = [
'location',
]
class StocktakeForm(forms.ModelForm):
class Meta:
model = StockItem
fields = [
'quantity',
]
class EditStockItemForm(HelperForm):
class Meta:
model = StockItem
fields = [
'supplier_part',
'batch',
'status',
'notes',
'URL',
]
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django import forms
from InvenTree.forms import HelperForm
from .models import StockLocation, StockItem
class EditStockLocationForm(HelperForm):
class Meta:
model = StockLocation
fields = [
'name',
'parent',
'description'
]
class CreateStockItemForm(HelperForm):
class Meta:
model = StockItem
fields = [
'part',
'supplier_part',
'location',
'belongs_to',
'serial',
'batch',
'quantity',
'status',
'notes',
# 'customer',
'URL',
]
class MoveStockItemForm(forms.ModelForm):
note = forms.CharField(label='Notes', required=True, help_text='Add note (required)')
class Meta:
model = StockItem
fields = [
'location',
]
class StocktakeForm(forms.ModelForm):
class Meta:
model = StockItem
fields = [
'quantity',
]
class EditStockItemForm(HelperForm):
class Meta:
model = StockItem
fields = [
'supplier_part',
'batch',
'status',
'notes',
'URL',
]
| Allow editing of 'notes' field when creating new StockItem | Allow editing of 'notes' field when creating new StockItem
| Python | mit | SchrodingersGat/InvenTree,inventree/InvenTree,inventree/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree,SchrodingersGat/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree | ---
+++
@@ -31,6 +31,7 @@
'batch',
'quantity',
'status',
+ 'notes',
# 'customer',
'URL',
] |
c6f65008da2c658d1ebff724d6ca98d67100c161 | chaosmonkey/api/app.py | chaosmonkey/api/app.py | import logging
from flask_cors import CORS
from flask import Flask, json
from flask_hal import HAL, HALResponse
from chaosmonkey.api.attacks_blueprint import attacks
from chaosmonkey.api.executors_blueprint import executors
from chaosmonkey.api.planners_blueprint import planners
from chaosmonkey.api.plans_blueprint import plans
from chaosmonkey.api.api_errors import APIError
log = logging.getLogger(__name__)
# Create FlaskApp
flask_app = Flask("cm_api")
HAL(flask_app, HALResponse)
CORS(flask_app)
# Register blueprints
root = "/api/"
prev1 = root + "1"
flask_app.register_blueprint(executors, url_prefix=prev1 + "/executors")
flask_app.register_blueprint(plans, url_prefix=prev1 + "/plans")
flask_app.register_blueprint(attacks, url_prefix=prev1 + "/attacks")
flask_app.register_blueprint(planners, url_prefix=prev1 + "/planners")
# Register error handler for custom APIError exception
@flask_app.errorhandler(APIError)
def handle_invalid_usage(error):
"""
Handler for APIErrors thrown by API endpoints
"""
log.info('%d %s', error.status_code, error.message)
response = json.jsonify(error.to_dict())
response.status_code = error.status_code
return response
| import logging
from flask_cors import CORS
from flask import Flask, json
from flask_hal import HAL, HALResponse
from chaosmonkey.api.attacks_blueprint import attacks
from chaosmonkey.api.executors_blueprint import executors
from chaosmonkey.api.planners_blueprint import planners
from chaosmonkey.api.plans_blueprint import plans
from chaosmonkey.api.api_errors import APIError
log = logging.getLogger(__name__)
# Create FlaskApp
flask_app = Flask("cm_api")
HAL(flask_app, HALResponse)
CORS(flask_app)
# Register blueprints
root = "/api/"
prev1 = root + "1"
flask_app.register_blueprint(executors, url_prefix=prev1 + "/executors")
flask_app.register_blueprint(plans, url_prefix=prev1 + "/plans")
flask_app.register_blueprint(attacks, url_prefix=prev1 + "/attacks")
flask_app.register_blueprint(planners, url_prefix=prev1 + "/planners")
# Register error handler for custom APIError exception
@flask_app.errorhandler(APIError)
def handle_invalid_usage(error):
"""
Handler for APIErrors thrown by API endpoints
"""
log.info('%d %s', error.status_code, error.message)
response = json.jsonify(error.to_dict())
response.status_code = error.status_code
return response
| Add blank space for PEP8 | Add blank space for PEP8
| Python | apache-2.0 | BBVA/chaos-monkey-engine,BBVA/chaos-monkey-engine | ---
+++
@@ -23,6 +23,7 @@
flask_app.register_blueprint(attacks, url_prefix=prev1 + "/attacks")
flask_app.register_blueprint(planners, url_prefix=prev1 + "/planners")
+
# Register error handler for custom APIError exception
@flask_app.errorhandler(APIError)
def handle_invalid_usage(error): |
cb8bba09372ab85b36dec9ade57e59ed76705f95 | project/project/local_settings_example.py | project/project/local_settings_example.py | DEBUG = True
ADMINS = (
('Zaphod Beeblebrox', 'hoopyfrood@heartofgold.com'),
)
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '^lkajsdlfkjaoif09ijoi23092309i02[93ip2j3[r29u3[0923jorij'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'db_name_here',
'USER': 'db_user_here',
'PASSWORD': 'db_password_here',
'HOST': 'localhost',
'PORT': '3306',
}
}
EMAIL_HOST = ''
EMAIL_HOST_USER = ''
EMAIL_HOST_PASSWORD = ''
EMAIL_PORT = 587
DEFAULT_FROM_EMAIL = 'My Site Admin <me@myproject.com>'
# Because message cookies and BrowserSync don't play nicely
MESSAGE_STORAGE = 'django.contrib.messages.storage.session.SessionStorage'
GOOGLE_ACCOUNT_CODE = "UA-XXXXXXX-XX" | DEBUG = True
ADMINS = (
('Zaphod Beeblebrox', 'hoopyfrood@heartofgold.com'),
)
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '^lkajsdlfkjaoif09ijoi23092309i02[93ip2j3[r29u3[0923jorij'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'db_name_here',
'USER': 'db_user_here',
'PASSWORD': 'db_password_here',
'HOST': 'localhost',
'PORT': '5432',
}
}
EMAIL_HOST = ''
EMAIL_HOST_USER = ''
EMAIL_HOST_PASSWORD = ''
EMAIL_PORT = 587
DEFAULT_FROM_EMAIL = 'My Site Admin <me@myproject.com>'
# Because message cookies and BrowserSync don't play nicely
MESSAGE_STORAGE = 'django.contrib.messages.storage.session.SessionStorage'
GOOGLE_ACCOUNT_CODE = "UA-XXXXXXX-XX" | Change to postgres by default | Change to postgres by default
| Python | mit | colbypalmer/cp-project-template,colbypalmer/cp-project-template,colbypalmer/cp-project-template | ---
+++
@@ -9,12 +9,12 @@
DATABASES = {
'default': {
- 'ENGINE': 'django.db.backends.mysql',
+ 'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'db_name_here',
'USER': 'db_user_here',
'PASSWORD': 'db_password_here',
'HOST': 'localhost',
- 'PORT': '3306',
+ 'PORT': '5432',
}
}
|
ec3a70e038efc565ce88294caf0e78d5efaa9a85 | djangocms_picture/cms_plugins.py | djangocms_picture/cms_plugins.py | from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from .models import Picture
class PicturePlugin(CMSPluginBase):
model = Picture
name = _("Picture")
render_template = "cms/plugins/picture.html"
text_enabled = True
def render(self, context, instance, placeholder):
if instance.url:
link = instance.url
elif instance.page_link:
link = instance.page_link.get_absolute_url()
else:
link = ""
context.update({
'picture': instance,
'link': link,
'placeholder': placeholder
})
return context
def icon_src(self, instance):
# TODO - possibly use 'instance' and provide a thumbnail image
return settings.STATIC_URL + u"cms/img/icons/plugins/image.png"
plugin_pool.register_plugin(PicturePlugin)
| from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from .models import Picture
class PicturePlugin(CMSPluginBase):
model = Picture
name = _("Picture")
render_template = "cms/plugins/picture.html"
text_enabled = True
def render(self, context, instance, placeholder):
if instance.url:
link = instance.url
elif instance.page_link:
link = instance.page_link.get_absolute_url()
else:
link = ""
context.update({
'picture': instance,
'link': link,
'placeholder': placeholder
})
return context
plugin_pool.register_plugin(PicturePlugin)
| Modify the picture plugin slightly | Modify the picture plugin slightly
| Python | mit | okfn/foundation,okfn/website,okfn/website,okfn/foundation,MjAbuz/foundation,MjAbuz/foundation,okfn/website,okfn/foundation,MjAbuz/foundation,okfn/foundation,okfn/website,MjAbuz/foundation | ---
+++
@@ -27,8 +27,5 @@
})
return context
- def icon_src(self, instance):
- # TODO - possibly use 'instance' and provide a thumbnail image
- return settings.STATIC_URL + u"cms/img/icons/plugins/image.png"
plugin_pool.register_plugin(PicturePlugin) |
2fda06e11c9b536a5771d5b7f4fb31e5c20223a0 | run_jstests.py | run_jstests.py | #!/usr/bin/env python
# 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.
"""Runs DomDistillers jstests.
This uses ChromeDriver (https://sites.google.com/a/chromium.org/chromedriver/) to run the jstests.
This requires that the ChromeDriver executable is on the PATH and that Selenium WebDriver is
installed.
In addition, ChromeDriver assumes that Chrome is available at /usr/bin/google-chrome.
"""
import os
import sys
import time
try:
from selenium import webdriver
except:
print 'ERROR:'
print 'Couldn\'t import webdriver. Please run `sudo ./install-build-deps.sh`.'
sys.exit(1)
start = time.time()
test_runner = "return com.dom_distiller.client.JsTestEntry.run()";
test_html = os.path.abspath(os.path.join(os.path.dirname(__file__), "war", "test.html"))
driver = webdriver.Chrome()
driver.get("file://" + test_html)
result = driver.execute_script(test_runner)
driver.quit()
end = time.time()
print result['log']
print 'Tests run: %d, Failures: %d, Skipped: %d, Time elapsed: %0.3f sec' % (result['numTests'],
result['failed'], result['skipped'], end - start)
sys.exit(0 if result['success'] else 1)
| #!/usr/bin/env python
# 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.
"""Runs DomDistillers jstests.
This uses ChromeDriver (https://sites.google.com/a/chromium.org/chromedriver/) to run the jstests.
This requires that the ChromeDriver executable is on the PATH and that Selenium WebDriver is
installed.
In addition, ChromeDriver assumes that Chrome is available at /usr/bin/google-chrome.
"""
import os
import sys
import time
try:
from selenium import webdriver
except:
print 'ERROR:'
print 'Couldn\'t import webdriver. Please run `sudo ./install-build-deps.sh`.'
sys.exit(1)
start = time.time()
test_runner = "return com.dom_distiller.client.JsTestEntry.run()";
test_html = os.path.abspath(os.path.join(os.path.dirname(__file__), "war", "test.html"))
driver = webdriver.Chrome()
driver.get("file://" + test_html)
result = driver.execute_script(test_runner)
driver.quit()
end = time.time()
print result['log'].encode('utf-8')
print 'Tests run: %d, Failures: %d, Skipped: %d, Time elapsed: %0.3f sec' % (result['numTests'],
result['failed'], result['skipped'], end - start)
sys.exit(0 if result['success'] else 1)
| Fix printing of logged non-ascii characters | Fix printing of logged non-ascii characters
webdriver seems to not handle non-ascii characters in the result of an
executed script correctly (python throws an exception when printing the
string). This makes them be printed correctly.
R=mdjones@chromium.org
Review URL: https://codereview.chromium.org/848503003
| Python | apache-2.0 | dalmirdasilva/dom-distiller,dalmirdasilva/dom-distiller,dalmirdasilva/dom-distiller,dalmirdasilva/dom-distiller,dalmirdasilva/dom-distiller | ---
+++
@@ -33,7 +33,7 @@
result = driver.execute_script(test_runner)
driver.quit()
end = time.time()
-print result['log']
+print result['log'].encode('utf-8')
print 'Tests run: %d, Failures: %d, Skipped: %d, Time elapsed: %0.3f sec' % (result['numTests'],
result['failed'], result['skipped'], end - start)
sys.exit(0 if result['success'] else 1) |
4fa40ddbe6eacb33a97eb18719aa7ae61d8c9218 | s3_url_sign.py | s3_url_sign.py | import boto.s3.connection
import optparse
def main():
parser = optparse.OptionParser(
usage='%prog BUCKET [KEY]',
)
parser.add_option(
'--method',
default='GET',
help='HTTP method to use [default: %default]',
)
parser.add_option(
'--expiry',
type='int',
default=60*60*24,
help='seconds before expiry [default: %default]',
)
opts, args = parser.parse_args()
try:
(bucket, key) = args
except ValueError:
try:
(bucket,) = args
except ValueError:
parser.error('Unexpected arguments.')
else:
key = None
conn = boto.s3.connection.S3Connection(
# aws_access_key_id=cfg.get(section, 'access_key'),
# aws_secret_access_key=cfg.get(section, 'secret_key'),
# is_secure=cfg.getboolean(section, 'is_secure'),
# port=port,
# host=cfg.get(section, 'host'),
)
kwargs = {}
if bucket is not None:
kwargs['bucket'] = bucket
if key is not None:
kwargs['key'] = key
url = conn.generate_url(
expires_in=opts.expiry,
method=opts.method,
**kwargs
)
print url
| import boto.s3.connection
import optparse
def main():
parser = optparse.OptionParser(
usage='%prog BUCKET [KEY]',
)
parser.add_option(
'--method',
default='GET',
help='HTTP method to use [default: %default]',
)
parser.add_option(
'--expiry',
type='int',
default=60*60*24,
help='seconds before expiry [default: %default]',
)
opts, args = parser.parse_args()
try:
(bucket, key) = args
except ValueError:
try:
(bucket,) = args
except ValueError:
parser.error('Unexpected arguments.')
else:
key = None
conn_kwargs = {}
host = boto.config.get('Boto', 's3_host')
if host is not None:
conn_kwargs['host'] = host
port = boto.config.getint('Boto', 's3_port')
if port is not None:
conn_kwargs['port'] = port
conn = boto.s3.connection.S3Connection(
calling_format=boto.s3.connection.OrdinaryCallingFormat(),
**conn_kwargs
)
kwargs = {}
if bucket is not None:
kwargs['bucket'] = bucket
if key is not None:
kwargs['key'] = key
url = conn.generate_url(
expires_in=opts.expiry,
method=opts.method,
**kwargs
)
print url
| Allow overriding host/port of S3 service to connect to. | Allow overriding host/port of S3 service to connect to.
Hardcode non-vhost calling convention, at least for now.
(The host name overriding typically doesn't work with vhosts;
"BUCKET.localhost" is not very helpful.)
To use a local S3-compatible service, put something like
this in ~/.boto:
[Boto]
s3_host = localhost
s3_port = 7280
is_secure = no
TODO: Get a patch to uptream Boto to make this unnecessary.
| Python | mit | tv42/s3-url-sign,tv42/s3-url-sign | ---
+++
@@ -27,12 +27,16 @@
else:
key = None
+ conn_kwargs = {}
+ host = boto.config.get('Boto', 's3_host')
+ if host is not None:
+ conn_kwargs['host'] = host
+ port = boto.config.getint('Boto', 's3_port')
+ if port is not None:
+ conn_kwargs['port'] = port
conn = boto.s3.connection.S3Connection(
- # aws_access_key_id=cfg.get(section, 'access_key'),
- # aws_secret_access_key=cfg.get(section, 'secret_key'),
- # is_secure=cfg.getboolean(section, 'is_secure'),
- # port=port,
- # host=cfg.get(section, 'host'),
+ calling_format=boto.s3.connection.OrdinaryCallingFormat(),
+ **conn_kwargs
)
kwargs = {}
if bucket is not None: |
25c0558b0c75306c8d9c547668df9cef25bae786 | symbolset.py | symbolset.py | class SymbolSet():
def __init__(self):
self._address_labels = dict()
self._label_addresses = dict()
self._generic_id = 0
def load(self, config_path):
pass
def add_label(self, address, label):
if address in self._address_labels:
raise TargetRelabelException("{:#04X} has already been given the "
"label {}".format(address, self._address_labels[address]))
if label in self._label_addresses:
raise LabelReuseException('The label "{}" is already used '
'at {:#04X}'.format(label, address))
self._address_labels[address] = label
self._label_addresses[label] = address
def add_generic_label(self, address):
label = "label{:04}".format(self._generic_id)
self.add_label(address, label)
self._generic_id += 1
def get_label(self, address):
return self._address_labels.get(address, None)
def get_address(self, label):
return self._label_addresses.get(label, None)
class TargetRelabelException(Exception):
pass
class LabelReuseException(Exception):
pass
| class SymbolSet():
def __init__(self):
self._address_labels = dict()
self._label_addresses = dict()
self._generic_id = 0
def add_label(self, address, label):
if address in self._address_labels:
raise TargetRelabelException("{:#04X} has already been given the "
"label {}".format(address, self._address_labels[address]))
if label in self._label_addresses:
raise LabelReuseException('The label "{}" is already used '
'at {:#04X}'.format(label, address))
self._address_labels[address] = label
self._label_addresses[label] = address
def add_generic_label(self, address):
label = "label{:04}".format(self._generic_id)
self.add_label(address, label)
self._generic_id += 1
def get_label(self, address):
return self._address_labels.get(address, None)
def get_address(self, label):
return self._label_addresses.get(label, None)
class TargetRelabelException(Exception):
pass
class LabelReuseException(Exception):
pass
| Remove redundant load() method from SymbolSet. | Remove redundant load() method from SymbolSet.
| Python | mit | achan1989/diSMB | ---
+++
@@ -3,9 +3,6 @@
self._address_labels = dict()
self._label_addresses = dict()
self._generic_id = 0
-
- def load(self, config_path):
- pass
def add_label(self, address, label):
if address in self._address_labels: |
322ecf060500e43a05c604be62edefcec48efd5a | bh_sshcmd.py | bh_sshcmd.py | #!/usr/bin/env python
#Black Hat Python; SSH w/ Paramiko (p 26)
import threading, paramiko, subprocess
def banner():
print "############ n1cFury- NetCat tool #################"
print "############ courtesy of Black Hat Python ###########"
print ""
def usage():
print "./bh_sshcmd.py <hostname> <user> <password> <command>"
print ""
def ssh_command(ip, user, passwd, command):
client = paramiko.SSHClient()
#client.load_host_keys('/home/justin/.ssh/known_hosts')
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(ip, username= user, password= passwd)
ssh_session = client.get_transport().open_session()
if ssh_session.active:
ssh_session.exec_command(command)
print ssh_session.recv(1024) #read banner
return
ssh_command('192.168.1.59', 'justin', 'lovesthepython','id')
def main():
if sys.argv == 5:
banner()
ssh_command(ip, user, passwd, command)
else:
print usage
if __name__ == "__main__":
main()
| #!/usr/bin/env python
#Black Hat Python; SSH w/ Paramiko (p 26)
import threading, paramiko, subprocess
host = sys.argv[1]
user = sys.argv[2]
passwd = sys.argv[3]
command = sys.argv[4]
def banner():
print ""
print "############ n1cFury- SSH Client #################"
print ""
def usage():
print "./bh_sshcmd.py <hostname> <user> <password> <command>"
print ""
def ssh_command(ip, user, passwd, command):
client = paramiko.SSHClient()
#client.load_host_keys('/home/justin/.ssh/known_hosts')
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(ip, username= user, password= passwd)
ssh_session = client.get_transport().open_session()
if ssh_session.active:
ssh_session.exec_command(command)
print ssh_session.recv(1024) #read banner
return
#ssh_command('192.168.1.59', 'justin', 'lovesthepython','id') #was manually configured before
def main():
banner()
if sys.argv == 5:
ssh_command(ip, user, passwd, command)
else:
print usage
if __name__ == "__main__":
main()
| DEBUG AND MAKE SURE FUNCTIONS WORK | TODO: DEBUG AND MAKE SURE FUNCTIONS WORK
| Python | mit | n1cfury/BlackHatPython | ---
+++
@@ -4,10 +4,14 @@
import threading, paramiko, subprocess
+host = sys.argv[1]
+user = sys.argv[2]
+passwd = sys.argv[3]
+command = sys.argv[4]
def banner():
- print "############ n1cFury- NetCat tool #################"
- print "############ courtesy of Black Hat Python ###########"
+ print ""
+ print "############ n1cFury- SSH Client #################"
print ""
def usage():
@@ -23,15 +27,17 @@
ssh_session.exec_command(command)
print ssh_session.recv(1024) #read banner
return
-ssh_command('192.168.1.59', 'justin', 'lovesthepython','id')
+#ssh_command('192.168.1.59', 'justin', 'lovesthepython','id') #was manually configured before
def main():
+ banner()
if sys.argv == 5:
- banner()
ssh_command(ip, user, passwd, command)
else:
print usage
-
if __name__ == "__main__":
main()
+
+
+ |
8671a368cff459d5a00c5b43d330d084e2f6ed3d | numpy/_array_api/_types.py | numpy/_array_api/_types.py | """
This file defines the types for type annotations.
These names aren't part of the module namespace, but they are used in the
annotations in the function signatures. The functions in the module are only
valid for inputs that match the given type annotations.
"""
__all__ = ['Literal', 'Optional', 'Tuple', 'Union', 'array', 'device',
'dtype', 'SupportsDLPack', 'SupportsBufferProtocol', 'PyCapsule']
from typing import Literal, Optional, Tuple, Union, TypeVar
import numpy as np
array = np.ndarray
device = TypeVar('device')
dtype = Literal[np.int8, np.int16, np.int32, np.int64, np.uint8, np.uint16,
np.uint32, np.uint64, np.float32, np.float64]
SupportsDLPack = TypeVar('SupportsDLPack')
SupportsBufferProtocol = TypeVar('SupportsBufferProtocol')
PyCapsule = TypeVar('PyCapsule')
| """
This file defines the types for type annotations.
These names aren't part of the module namespace, but they are used in the
annotations in the function signatures. The functions in the module are only
valid for inputs that match the given type annotations.
"""
__all__ = ['Literal', 'Optional', 'Tuple', 'Union', 'array', 'device',
'dtype', 'SupportsDLPack', 'SupportsBufferProtocol', 'PyCapsule']
from typing import Literal, Optional, Tuple, Union, TypeVar
from . import (ndarray, int8, int16, int32, int64, uint8, uint16, uint32,
uint64, float32, float64)
array = ndarray
device = TypeVar('device')
dtype = Literal[int8, int16, int32, int64, uint8, uint16,
uint32, uint64, float32, float64]
SupportsDLPack = TypeVar('SupportsDLPack')
SupportsBufferProtocol = TypeVar('SupportsBufferProtocol')
PyCapsule = TypeVar('PyCapsule')
| Use the array API types for the array API type annotations | Use the array API types for the array API type annotations
| Python | bsd-3-clause | numpy/numpy,mattip/numpy,charris/numpy,simongibbons/numpy,seberg/numpy,charris/numpy,anntzer/numpy,simongibbons/numpy,jakirkham/numpy,numpy/numpy,jakirkham/numpy,endolith/numpy,simongibbons/numpy,jakirkham/numpy,pdebuyl/numpy,rgommers/numpy,seberg/numpy,anntzer/numpy,endolith/numpy,mattip/numpy,numpy/numpy,seberg/numpy,mattip/numpy,charris/numpy,anntzer/numpy,endolith/numpy,rgommers/numpy,jakirkham/numpy,rgommers/numpy,pdebuyl/numpy,mhvk/numpy,numpy/numpy,simongibbons/numpy,mhvk/numpy,endolith/numpy,rgommers/numpy,seberg/numpy,charris/numpy,mattip/numpy,mhvk/numpy,pdebuyl/numpy,anntzer/numpy,mhvk/numpy,jakirkham/numpy,simongibbons/numpy,pdebuyl/numpy,mhvk/numpy | ---
+++
@@ -11,12 +11,13 @@
from typing import Literal, Optional, Tuple, Union, TypeVar
-import numpy as np
+from . import (ndarray, int8, int16, int32, int64, uint8, uint16, uint32,
+ uint64, float32, float64)
-array = np.ndarray
+array = ndarray
device = TypeVar('device')
-dtype = Literal[np.int8, np.int16, np.int32, np.int64, np.uint8, np.uint16,
- np.uint32, np.uint64, np.float32, np.float64]
+dtype = Literal[int8, int16, int32, int64, uint8, uint16,
+ uint32, uint64, float32, float64]
SupportsDLPack = TypeVar('SupportsDLPack')
SupportsBufferProtocol = TypeVar('SupportsBufferProtocol')
PyCapsule = TypeVar('PyCapsule') |
ef6cb74f2d574338d9e225764c4f90bd83fcb47d | typograph.py | typograph.py | import sublime, sublime_plugin
from RemoteTypograf import RemoteTypograf
class TypographCommand(sublime_plugin.TextCommand):
def run(self, edit):
typograph = RemoteTypograf('windows-1251')
typograph.htmlEntities()
typograph.br(0)
typograph.p(0)
typograph.nobr(3)
for region in self.view.sel():
regionText = self.view.substr(region)
processed = typograph.processText(regionText).strip(' \n\r')
self.view.replace(edit, region, processed)
| import sublime, sublime_plugin
from .RemoteTypograf import RemoteTypograf
class TypographCommand(sublime_plugin.TextCommand):
def run(self, edit):
typograph = RemoteTypograf('windows-1251')
typograph.htmlEntities()
typograph.br(0)
typograph.p(0)
typograph.nobr(3)
for region in self.view.sel():
regionText = self.view.substr(region)
processed = typograph.processText(regionText).strip(' \n\r')
self.view.replace(edit, region, processed)
| Change module import for ST3 | Change module import for ST3
| Python | mit | einomi/sublime-text-3-typographer,einomi/sublime-text-3-typographer | ---
+++
@@ -1,6 +1,6 @@
import sublime, sublime_plugin
-from RemoteTypograf import RemoteTypograf
+from .RemoteTypograf import RemoteTypograf
class TypographCommand(sublime_plugin.TextCommand): |
11543deda3222965ee95adc4ea6db5cdec21ac94 | admin_tests/factories.py | admin_tests/factories.py | import factory
from admin.common_auth.models import MyUser
class UserFactory(factory.Factory):
class Meta:
model = MyUser
id = 123
email = 'cello@email.org'
first_name = 'Yo-yo'
last_name = 'Ma'
osf_id = 'abc12'
@classmethod
def is_in_group(cls, value):
return True
| import factory
from admin.common_auth.models import AdminProfile
from osf_tests.factories import UserFactory as OSFUserFactory
class UserFactory(factory.Factory):
class Meta:
model = AdminProfile
user = OSFUserFactory
desk_token = 'el-p'
test_token_secret = 'mike'
@classmethod
def is_in_group(cls, value):
return True
| Fix up admin user factory to reflect model changes | Fix up admin user factory to reflect model changes
| Python | apache-2.0 | alexschiller/osf.io,HalcyonChimera/osf.io,felliott/osf.io,baylee-d/osf.io,mattclark/osf.io,erinspace/osf.io,alexschiller/osf.io,alexschiller/osf.io,leb2dg/osf.io,chrisseto/osf.io,chennan47/osf.io,cslzchen/osf.io,baylee-d/osf.io,CenterForOpenScience/osf.io,acshi/osf.io,caseyrollins/osf.io,aaxelb/osf.io,icereval/osf.io,hmoco/osf.io,adlius/osf.io,cslzchen/osf.io,baylee-d/osf.io,erinspace/osf.io,chennan47/osf.io,leb2dg/osf.io,HalcyonChimera/osf.io,pattisdr/osf.io,caneruguz/osf.io,brianjgeiger/osf.io,caseyrollins/osf.io,binoculars/osf.io,CenterForOpenScience/osf.io,brianjgeiger/osf.io,laurenrevere/osf.io,saradbowman/osf.io,hmoco/osf.io,brianjgeiger/osf.io,alexschiller/osf.io,leb2dg/osf.io,pattisdr/osf.io,cslzchen/osf.io,cwisecarver/osf.io,mfraezz/osf.io,binoculars/osf.io,brianjgeiger/osf.io,crcresearch/osf.io,TomBaxter/osf.io,monikagrabowska/osf.io,saradbowman/osf.io,aaxelb/osf.io,chennan47/osf.io,mluo613/osf.io,mluo613/osf.io,CenterForOpenScience/osf.io,hmoco/osf.io,HalcyonChimera/osf.io,caneruguz/osf.io,laurenrevere/osf.io,cwisecarver/osf.io,Nesiehr/osf.io,Nesiehr/osf.io,adlius/osf.io,caseyrollins/osf.io,icereval/osf.io,TomBaxter/osf.io,icereval/osf.io,Johnetordoff/osf.io,monikagrabowska/osf.io,sloria/osf.io,cwisecarver/osf.io,mfraezz/osf.io,mluo613/osf.io,acshi/osf.io,acshi/osf.io,hmoco/osf.io,cwisecarver/osf.io,acshi/osf.io,Nesiehr/osf.io,cslzchen/osf.io,crcresearch/osf.io,felliott/osf.io,caneruguz/osf.io,adlius/osf.io,adlius/osf.io,mfraezz/osf.io,chrisseto/osf.io,mfraezz/osf.io,crcresearch/osf.io,Johnetordoff/osf.io,Nesiehr/osf.io,alexschiller/osf.io,mluo613/osf.io,chrisseto/osf.io,CenterForOpenScience/osf.io,mattclark/osf.io,monikagrabowska/osf.io,caneruguz/osf.io,Johnetordoff/osf.io,felliott/osf.io,leb2dg/osf.io,sloria/osf.io,erinspace/osf.io,acshi/osf.io,TomBaxter/osf.io,mattclark/osf.io,monikagrabowska/osf.io,HalcyonChimera/osf.io,pattisdr/osf.io,felliott/osf.io,monikagrabowska/osf.io,aaxelb/osf.io,laurenrevere/osf.io,mluo613/osf.io,chrisseto/osf.io,sloria/osf.io,binoculars/osf.io,aaxelb/osf.io,Johnetordoff/osf.io | ---
+++
@@ -1,17 +1,17 @@
import factory
-from admin.common_auth.models import MyUser
+from admin.common_auth.models import AdminProfile
+from osf_tests.factories import UserFactory as OSFUserFactory
class UserFactory(factory.Factory):
class Meta:
- model = MyUser
+ model = AdminProfile
- id = 123
- email = 'cello@email.org'
- first_name = 'Yo-yo'
- last_name = 'Ma'
- osf_id = 'abc12'
+ user = OSFUserFactory
+
+ desk_token = 'el-p'
+ test_token_secret = 'mike'
@classmethod
def is_in_group(cls, value): |
1f3730ac4d531ca0d582a8b8bded871acb409847 | backend/api-server/warehaus_api/events/models.py | backend/api-server/warehaus_api/events/models.py | from .. import db
class Event(db.Model):
timestamp = db.Field()
obj_id = db.Field() # The object for which this event was created about
user_id = db.Field() # The user who performed the action
# A list of IDs which are interested in this event. For example, when creating
# a server we obviously want this event to be shows in the server page, but we
# also want it to be shown in the lab page. So we put two IDs in the list: the
# server ID and the lab ID.
# Another example is when we delete the server. Then we would be able to show
# that event in the lab page although the server is already deleted.
interested_ids = db.Field()
title = db.Field() # Event title
content = db.Field() # Event content
def create_event(obj_id, user_id, interested_ids, title, content=''):
event = Event(
timestamp = db.times.now(),
obj_id = obj_id,
interested_ids = interested_ids,
title = title,
content = content,
)
event.save()
| from .. import db
class Event(db.Model):
timestamp = db.Field()
obj_id = db.Field() # The object for which this event was created about
user_id = db.Field() # The user who performed the action
# A list of IDs which are interested in this event. For example, when creating
# a server we obviously want this event to be shows in the server page, but we
# also want it to be shown in the lab page. So we put two IDs in the list: the
# server ID and the lab ID.
# Another example is when we delete the server. Then we would be able to show
# that event in the lab page although the server is already deleted.
interested_ids = db.Field()
title = db.Field() # Event title
content = db.Field() # Event content
def create_event(obj_id, user_id, interested_ids, title, content=''):
event = Event(
timestamp = db.times.now(),
obj_id = obj_id,
user_id = user_id,
interested_ids = interested_ids,
title = title,
content = content,
)
event.save()
| Fix api-server events not saving the user ID | Fix api-server events not saving the user ID
| Python | agpl-3.0 | labsome/labsome,warehaus/warehaus,warehaus/warehaus,labsome/labsome,warehaus/warehaus,labsome/labsome | ---
+++
@@ -20,6 +20,7 @@
event = Event(
timestamp = db.times.now(),
obj_id = obj_id,
+ user_id = user_id,
interested_ids = interested_ids,
title = title,
content = content, |
4602b19c1bd827c40ddc190c177b71b8922a39f6 | IndexedRedis/fields/raw.py | IndexedRedis/fields/raw.py | # Copyright (c) 2014, 2015, 2016 Timothy Savannah under LGPL version 2.1. See LICENSE for more information.
#
# fields.compressed - Some types and objects related to compressed fields. Use in place of IRField ( in FIELDS array to activate functionality )
#
# vim: set ts=8 shiftwidth=8 softtabstop=8 noexpandtab :
from . import IRField
class IRRawField(IRField):
'''
IRRawField - Return the raw data from Redis, without any extra encoding, decoding, or translation
'''
CAN_INDEX = False
def __init__(self, name=''):
self.valueType = None
def convert(self, value=b''):
return value
def toStorage(self, value=b''):
return value
def __new__(self, name=''):
return IRField.__new__(self, name)
# vim: set ts=8 shiftwidth=8 softtabstop=8 noexpandtab :
| # Copyright (c) 2014, 2015, 2016 Timothy Savannah under LGPL version 2.1. See LICENSE for more information.
#
# fields.raw - Raw field, no encoding or decoding will occur.
#
# vim: set ts=8 shiftwidth=8 softtabstop=8 noexpandtab :
from . import IRField
class IRRawField(IRField):
'''
IRRawField - Return the raw data from Redis, without any extra encoding, decoding, or translation
'''
CAN_INDEX = False
def __init__(self, name=''):
self.valueType = None
def convert(self, value=b''):
return value
def toStorage(self, value=b''):
return value
def __new__(self, name=''):
return IRField.__new__(self, name)
# vim: set ts=8 shiftwidth=8 softtabstop=8 noexpandtab :
| Fix wrong comment in module | Fix wrong comment in module
| Python | lgpl-2.1 | kata198/indexedredis,kata198/indexedredis | ---
+++
@@ -1,6 +1,6 @@
# Copyright (c) 2014, 2015, 2016 Timothy Savannah under LGPL version 2.1. See LICENSE for more information.
#
-# fields.compressed - Some types and objects related to compressed fields. Use in place of IRField ( in FIELDS array to activate functionality )
+# fields.raw - Raw field, no encoding or decoding will occur.
#
|
0a04143c94540d864a288e5c79ade4ba9bf31e37 | src/test/stresstest.py | src/test/stresstest.py | #!/usr/bin/env python
# Copyright 2007 Albert Strasheim <fullung@gmail.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import unittest
if __name__ == '__main__':
testLoader = unittest.defaultTestLoader
module = __import__('__main__')
test = testLoader.loadTestsFromModule(module)
testRunner = unittest.TextTestRunner(verbosity=2)
for i in xrange(100):
result = testRunner.run(test)
| #!/usr/bin/env python
# Copyright 2007 Albert Strasheim <fullung@gmail.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import unittest
from test_openwire_async import *
from test_openwire_sync import *
from test_stomp_async import *
from test_stomp_sync import *
from test_types import *
if __name__ == '__main__':
testLoader = unittest.defaultTestLoader
module = __import__('__main__')
test = testLoader.loadTestsFromModule(module)
testRunner = unittest.TextTestRunner(verbosity=2)
for i in xrange(100):
result = testRunner.run(test)
| Test everything with stress test. | Test everything with stress test.
| Python | apache-2.0 | aberzan/pyactivemq,WilliamFF/pyactivemq,alberts/pyactivemq,cl2dlope/pyactivemq,aberzan/pyactivemq,winking324/pyactivemq,hetian9288/pyactivemq,winking324/pyactivemq,chenrui333/pyactivemq,cleardo/pyactivemq,haofree/pyactivemq,alberts/pyactivemq,hetian9288/pyactivemq,haofree/pyactivemq,cl2dlope/pyactivemq,WilliamFF/pyactivemq,chenrui333/pyactivemq,cleardo/pyactivemq | ---
+++
@@ -16,6 +16,12 @@
import unittest
+from test_openwire_async import *
+from test_openwire_sync import *
+from test_stomp_async import *
+from test_stomp_sync import *
+from test_types import *
+
if __name__ == '__main__':
testLoader = unittest.defaultTestLoader
module = __import__('__main__') |
774a57478d93663968c0ed0e9407785f618b6eae | stackdio/core/middleware.py | stackdio/core/middleware.py | class JSONIndentAcceptHeaderMiddleware(object):
def process_request(self, request):
request.META['HTTP_ACCEPT'] = 'application/json; indent=4'
return None
| class JSONIndentAcceptHeaderMiddleware(object):
def process_request(self, request):
if request.META.get('HTTP_ACCEPT') == 'application/json':
request.META['HTTP_ACCEPT'] = 'application/json; indent=4'
return None
| Apply indenting to only requests that specify application/json accept headers | PI-248: Apply indenting to only requests that specify application/json accept
headers
| Python | apache-2.0 | clarkperkins/stackdio,stackdio/stackdio,stackdio/stackdio,clarkperkins/stackdio,clarkperkins/stackdio,stackdio/stackdio,stackdio/stackdio,clarkperkins/stackdio | ---
+++
@@ -1,5 +1,6 @@
class JSONIndentAcceptHeaderMiddleware(object):
def process_request(self, request):
- request.META['HTTP_ACCEPT'] = 'application/json; indent=4'
+ if request.META.get('HTTP_ACCEPT') == 'application/json':
+ request.META['HTTP_ACCEPT'] = 'application/json; indent=4'
return None |
4460231b1abf053e8e2bb8581007ccb0e61cae50 | main.py | main.py | #!/usr/bin/env python3
# Standard imports
import argparse
import sys
import os.path
# Non-standard imports
import jinja2
import yaml
def main(args):
parser = argparse.ArgumentParser(description="Builds a CV using a YAML database.")
parser.add_argument("source", help="The YAML database to source from.")
parser.add_argument("template", help="The template to build the CV from.")
parser.add_argument("output", help="The file to output.")
args = parser.parse_args(args)
db = None
with open(args.source, "r") as source_file:
db = yaml.load(source_file)
env = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.dirname(args.template)))
template = None
try:
template = env.get_template(os.path.basename(args.template))
except jinja2.TemplateSyntaxError as ex:
print(
("Failed to load template from {filename}. "
"Error on line {lineno}: {message}").format(
filename=ex.filename,
lineno=ex.lineno,
message=ex.message))
sys.exit(1)
with open(args.output, "w") as output_file:
output_file.write(template.render(db))
if __name__ == "__main__":
main(sys.argv[1:])
| #!/usr/bin/env python3
# Standard imports
import argparse
import sys
import os.path
# Non-standard imports
import jinja2
import yaml
def filter_db(db, tags):
return db
def main(args):
parser = argparse.ArgumentParser(description="Builds a CV using a YAML database.")
parser.add_argument("source", help="The YAML database to source from.")
parser.add_argument("template", help="The template to build the CV from.")
parser.add_argument("output", help="The file to output.")
parser.add_argument("--tags", help="A comma-separated list of tags. If present, only items tagged with those specified appear in the output.")
args = parser.parse_args(args)
tags = None
if args.tags is not None:
tags = args.tags.split(",")
db = None
with open(args.source, "r") as source_file:
db = yaml.load(source_file)
if tags is not None:
db = filter_db(db, tags)
env = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.dirname(args.template)))
template = None
try:
template = env.get_template(os.path.basename(args.template))
except jinja2.TemplateSyntaxError as ex:
print(
("Failed to load template from {filename}. "
"Error on line {lineno}: {message}").format(
filename=ex.filename,
lineno=ex.lineno,
message=ex.message))
sys.exit(1)
with open(args.output, "w") as output_file:
output_file.write(template.render(db))
if __name__ == "__main__":
main(sys.argv[1:])
| Tag filtering infrastructure up (currently stubbed). | Tag filtering infrastructure up (currently stubbed).
| Python | apache-2.0 | proaralyst/cvgen | ---
+++
@@ -9,17 +9,28 @@
import jinja2
import yaml
+def filter_db(db, tags):
+ return db
+
def main(args):
parser = argparse.ArgumentParser(description="Builds a CV using a YAML database.")
parser.add_argument("source", help="The YAML database to source from.")
parser.add_argument("template", help="The template to build the CV from.")
parser.add_argument("output", help="The file to output.")
+ parser.add_argument("--tags", help="A comma-separated list of tags. If present, only items tagged with those specified appear in the output.")
args = parser.parse_args(args)
+
+ tags = None
+ if args.tags is not None:
+ tags = args.tags.split(",")
db = None
with open(args.source, "r") as source_file:
db = yaml.load(source_file)
+
+ if tags is not None:
+ db = filter_db(db, tags)
env = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.dirname(args.template)))
template = None |
7c805eecc90ead4e412e091c2500e881f47dd383 | test/tests/__init__.py | test/tests/__init__.py | #
# Sheared -- non-blocking network programming library for Python
# Copyright (C) 2003 Sune Kirkeby <sune@mel.interspace.dk>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
__all__ = [
'reactor', 'database', 'pool', 'commands',
'time_since',
'rfc822', 'rfc1521',
'http', 'querystring', 'cookie', 'virtualhost', 'accept',
'webresource', 'webcollections', 'webentwiner',
'webserver', 'webclient', 'web',
'semaphore', 'logfile',
]
| #
# Sheared -- non-blocking network programming library for Python
# Copyright (C) 2003 Sune Kirkeby <sune@mel.interspace.dk>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
__all__ = [
'database', 'pool', 'commands',
'time_since',
'rfc822', 'rfc1521',
'http', 'querystring', 'cookie', 'virtualhost',
'webresource', 'webcollections', 'webentwiner',
'webserver', 'webclient', 'web',
'semaphore', 'logfile',
]
| Remove tests from __all__ which are no longere here. | Remove tests from __all__ which are no longere here.
git-svn-id: fc68d25ef6d4ed42045cee93f23b6b1994a11c36@1122 5646265b-94b7-0310-9681-9501d24b2df7
| Python | mit | kirkeby/sheared | ---
+++
@@ -17,10 +17,10 @@
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
__all__ = [
- 'reactor', 'database', 'pool', 'commands',
+ 'database', 'pool', 'commands',
'time_since',
'rfc822', 'rfc1521',
- 'http', 'querystring', 'cookie', 'virtualhost', 'accept',
+ 'http', 'querystring', 'cookie', 'virtualhost',
'webresource', 'webcollections', 'webentwiner',
'webserver', 'webclient', 'web',
'semaphore', 'logfile', |
52077ba667efcf596c9186dbbd8d7cedc95d624d | tests/document_test.py | tests/document_test.py | from document import Document
import unittest
class TestDocument(unittest.TestCase):
def _get_document(self):
spec = {
"author": "John Humphreys",
"content": {
"title": "How to make cookies",
"text": "First start by pre-heating the oven..."
},
"category": "cooking",
"comments": [
{
"commenter": "Julio Cesar",
"email": "jcesar@test.com",
"comment": "Great post dude!"
},
{
"commenter": "Michael Andrews",
"comment": "My wife loves these."
}
],
"tags": ["recipe", "cookies"]
}
return Document(spec)
def test_create_with_invalid_key_names(self):
with self.assertRaises(Exception):
Document({'contains space': 34})
def test_creates_nested_document_tree(self):
document = self._get_document()
self.assertIsInstance(document['content'], Document)
self.assertIsInstance(document['comments'][0], Document)
def test_provides_attribute_getters(self):
document = self._get_document()
self.assertEqual("cooking", document.category)
self.assertEqual("Julio Cesar", document.comments[0].commenter)
def test_provides_attribute_setters(self):
document = self._get_document()
document.category = "baking"
self.assertEqual("baking", document['category'])
| from document import Document
import unittest
class TestDocument(unittest.TestCase):
def _get_document(self):
spec = {
"author": "John Humphreys",
"content": {
"title": "How to make cookies",
"text": "First start by pre-heating the oven..."
},
"category": "cooking",
"comments": [
{
"commenter": "Julio Cesar",
"email": "jcesar@test.com",
"comment": "Great post dude!"
},
{
"commenter": "Michael Andrews",
"comment": "My wife loves these."
}
],
"tags": ["recipe", "cookies"]
}
return Document(spec)
def test_create_with_invalid_key_names(self):
with self.assertRaises(Exception):
Document({'contains space': 34})
with self.assertRaises(Exception):
Document({'': 45})
def test_creates_nested_document_tree(self):
document = self._get_document()
self.assertIsInstance(document['content'], Document)
self.assertIsInstance(document['comments'][0], Document)
def test_provides_attribute_getters(self):
document = self._get_document()
self.assertEqual("cooking", document.category)
self.assertEqual("Julio Cesar", document.comments[0].commenter)
def test_provides_attribute_setters(self):
document = self._get_document()
document.category = "baking"
self.assertEqual("baking", document['category'])
| Test blank keys are not allowed. | Test blank keys are not allowed.
| Python | mit | gamechanger/schemer,gamechanger/mongothon | ---
+++
@@ -31,6 +31,9 @@
with self.assertRaises(Exception):
Document({'contains space': 34})
+ with self.assertRaises(Exception):
+ Document({'': 45})
+
def test_creates_nested_document_tree(self):
document = self._get_document()
self.assertIsInstance(document['content'], Document) |
f1496f7f5babdf1f9fa8f527f42442aeccab46d7 | tests/test_location.py | tests/test_location.py | from SUASSystem import *
import math
import numpy
import unittest
from dronekit import LocationGlobalRelative
class locationTestCase(unittest.TestCase):
def setUp(self):
self.position = Location(5, 12, 20)
def test_get_lat(self):
self.assertEquals(5, self.position.get_lat())
| from SUASSystem import *
import math
import numpy
import unittest
from dronekit import LocationGlobalRelative
class locationTestCase(unittest.TestCase):
def setUp(self):
self.position = Location(5, 12, 20)
def test_get_lat(self):
self.assertEquals(5, self.position.get_lat())
def test_get_lon(self):
self.assertEquals(12, self.position.get_lon())
def test_get_alt(self):
self.assertEquals(20, self.position.get_alt())
def test_repr(self):
self.assertEquals('Lat: 5 Lon: 12 Alt: 20', self.position.__repr__())
| Add finished working location unit tests | Add finished working location unit tests
| Python | mit | FlintHill/SUAS-Competition,FlintHill/SUAS-Competition,FlintHill/SUAS-Competition,FlintHill/SUAS-Competition,FlintHill/SUAS-Competition | ---
+++
@@ -11,3 +11,12 @@
def test_get_lat(self):
self.assertEquals(5, self.position.get_lat())
+
+ def test_get_lon(self):
+ self.assertEquals(12, self.position.get_lon())
+
+ def test_get_alt(self):
+ self.assertEquals(20, self.position.get_alt())
+
+ def test_repr(self):
+ self.assertEquals('Lat: 5 Lon: 12 Alt: 20', self.position.__repr__()) |
236c37e39d1c3821b60e183845594195091acd3e | corehq/ex-submodules/pillow_retry/tasks.py | corehq/ex-submodules/pillow_retry/tasks.py | from celery.schedules import crontab
from celery.task import periodic_task
from django.conf import settings
from django.db.models import Count
from corehq.util.datadog.gauges import datadog_gauge
from pillow_retry.models import PillowError
@periodic_task(
run_every=crontab(minute="*/15"),
queue=settings.CELERY_PERIODIC_QUEUE,
)
def record_pillow_error_queue_size():
data = PillowError.objects.values('pillow').annotate(num_errors=Count('id'))
for row in data:
datadog_gauge('commcare.pillowtop.error_queue', row['num_errors'], tags=[
'pillow_name:%s' % row['pillow'],
'host:celery',
'group:celery',
'error_type:%s' % row['error_type']
])
| from celery.schedules import crontab
from celery.task import periodic_task
from django.conf import settings
from django.db.models import Count
from corehq.util.datadog.gauges import datadog_gauge
from pillow_retry.models import PillowError
@periodic_task(
run_every=crontab(minute="*/15"),
queue=settings.CELERY_PERIODIC_QUEUE,
)
def record_pillow_error_queue_size():
data = PillowError.objects.values('pillow').annotate(num_errors=Count('id'))
for row in data:
datadog_gauge('commcare.pillowtop.error_queue', row['num_errors'], tags=[
'pillow_name:%s' % row['pillow'],
'host:celery',
'group:celery'
])
| Revert "Send error-type info to pillow error DD metrics" | Revert "Send error-type info to pillow error DD metrics"
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq | ---
+++
@@ -17,6 +17,5 @@
datadog_gauge('commcare.pillowtop.error_queue', row['num_errors'], tags=[
'pillow_name:%s' % row['pillow'],
'host:celery',
- 'group:celery',
- 'error_type:%s' % row['error_type']
+ 'group:celery'
]) |
4b698854d3dc9a30b507716d839065011b1ac545 | addons/clinic_sale/__openerp__.py | addons/clinic_sale/__openerp__.py | # -*- coding: utf-8 -*-
{'active': False,
'author': 'Ingenieria ADHOC',
'category': 'Clinic',
'demo_xml': [],
'depends': ['clinic', 'sale_dummy_confirmation'],
'description': """
Clinic Sales
=============
""",
'init_xml': [],
'installable': True,
'license': 'AGPL-3',
'name': 'Clinic Sale',
'test': [],
'demo': [
],
'update_xml': [
'res_partner_view.xml',
],
'version': '1.1',
'website': 'www.ingadhoc.com'}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| # -*- coding: utf-8 -*-
{'active': False,
'author': 'Ingenieria ADHOC',
'category': 'Clinic',
'demo_xml': [],
'depends': [
'clinic',
'sale_dummy_confirmation',
'l10n_ar_aeroo_sale',
],
'description': """
Clinic Sales
=============
""",
'init_xml': [],
'installable': True,
'license': 'AGPL-3',
'name': 'Clinic Sale',
'test': [],
'demo': [
],
'update_xml': [
'res_partner_view.xml',
],
'version': '1.1',
'website': 'www.ingadhoc.com'}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| ADD aeroo report to clinic sale | ADD aeroo report to clinic sale
| Python | agpl-3.0 | ingadhoc/odoo-clinic,ingadhoc/odoo-clinic,ingadhoc/odoo-clinic | ---
+++
@@ -3,7 +3,11 @@
'author': 'Ingenieria ADHOC',
'category': 'Clinic',
'demo_xml': [],
- 'depends': ['clinic', 'sale_dummy_confirmation'],
+ 'depends': [
+ 'clinic',
+ 'sale_dummy_confirmation',
+ 'l10n_ar_aeroo_sale',
+ ],
'description': """
Clinic Sales
============= |
79a453f503e0f4283700071d415e32e82d35162b | eadred/management/commands/generatedata.py | eadred/management/commands/generatedata.py | import imp
from django.conf import settings
from django.core.management.base import BaseCommand
from django.utils.importlib import import_module
from optparse import make_option
class Command(BaseCommand):
help = 'Generates sample data.'
option_list = BaseCommand.option_list + (
make_option('--with',
action='append',
dest='param',
help='Pass key=val style param to generate_sampledata'),
)
def handle(self, *args, **options):
for item in options.get('param', []):
if '=' in item:
key, val = item.split('=')
else:
key, val = item, True
options[key] = val
# Allows you to specify which apps to generate sampledata for.
if not args:
args = []
for app in settings.INSTALLED_APPS:
if args and app not in args:
continue
try:
app_path = import_module(app).__path__
except AttributeError:
continue
try:
imp.find_module('sampledata', app_path)
except ImportError:
continue
module = import_module('%s.sampledata' % app)
if hasattr(module, 'generate_sampledata'):
self.stdout.write('Generating sample data from %s...' % app)
module.generate_sampledata(options)
self.stdout.write('Done!\n')
| import imp
from django.conf import settings
from django.core.management.base import BaseCommand
from django.utils.importlib import import_module
from optparse import make_option
class Command(BaseCommand):
help = 'Generates sample data.'
option_list = BaseCommand.option_list + (
make_option('--with',
action='append',
dest='param',
help='Pass key=val style param to generate_sampledata'),
)
def handle(self, *args, **options):
if options.get('param'):
for item in options['param']:
if '=' in item:
key, val = item.split('=')
else:
key, val = item, True
options[key] = val
# Allows you to specify which apps to generate sampledata for.
if not args:
args = []
for app in settings.INSTALLED_APPS:
if args and app not in args:
continue
try:
app_path = import_module(app).__path__
except AttributeError:
continue
try:
imp.find_module('sampledata', app_path)
except ImportError:
continue
module = import_module('%s.sampledata' % app)
if hasattr(module, 'generate_sampledata'):
self.stdout.write('Generating sample data from %s...' % app)
module.generate_sampledata(options)
self.stdout.write('Done!\n')
| Fix issue where options['param'] can be None. | Fix issue where options['param'] can be None.
| Python | bsd-3-clause | willkg/django-eadred | ---
+++
@@ -17,12 +17,13 @@
)
def handle(self, *args, **options):
- for item in options.get('param', []):
- if '=' in item:
- key, val = item.split('=')
- else:
- key, val = item, True
- options[key] = val
+ if options.get('param'):
+ for item in options['param']:
+ if '=' in item:
+ key, val = item.split('=')
+ else:
+ key, val = item, True
+ options[key] = val
# Allows you to specify which apps to generate sampledata for.
if not args: |
5da7189f195d0daf9595c61f05156c85031ba0c5 | tests/testapp/tests/test_scheduling.py | tests/testapp/tests/test_scheduling.py | from django.test import TestCase
from testapp.tests import factories
class SchedulingTestCase(TestCase):
def test_scheduling(self):
for i in range(20):
factories.AssignmentFactory.create()
factories.WaitListFactory.create()
admin = factories.UserFactory.create(is_staff=True, is_superuser=True)
self.client.login(username=admin.username, password='test')
self.client.get('/zivinetz/admin/scheduling/')
| from django.test import TestCase
from zivinetz.models import Assignment
from testapp.tests import factories
class SchedulingTestCase(TestCase):
def test_scheduling(self):
for i in range(20):
factories.AssignmentFactory.create()
factories.WaitListFactory.create()
admin = factories.UserFactory.create(is_staff=True, is_superuser=True)
self.client.login(username=admin.username, password='test')
self.assertEqual(
self.client.get('/zivinetz/admin/scheduling/').status_code,
200)
Assignment.objects.all().delete()
self.assertEqual(
self.client.get('/zivinetz/admin/scheduling/').status_code,
200)
| Test that scheduling does not crash | Test that scheduling does not crash
| Python | mit | matthiask/zivinetz,matthiask/zivinetz,matthiask/zivinetz,matthiask/zivinetz | ---
+++
@@ -1,4 +1,6 @@
from django.test import TestCase
+
+from zivinetz.models import Assignment
from testapp.tests import factories
@@ -12,4 +14,11 @@
admin = factories.UserFactory.create(is_staff=True, is_superuser=True)
self.client.login(username=admin.username, password='test')
- self.client.get('/zivinetz/admin/scheduling/')
+ self.assertEqual(
+ self.client.get('/zivinetz/admin/scheduling/').status_code,
+ 200)
+
+ Assignment.objects.all().delete()
+ self.assertEqual(
+ self.client.get('/zivinetz/admin/scheduling/').status_code,
+ 200) |
3aac4383d53f2c3d45135a68cd18a93957f763c4 | recipe-server/normandy/recipes/migrations/0046_reset_signatures.py | recipe-server/normandy/recipes/migrations/0046_reset_signatures.py | """
Removes signatures, so they can be easily recreated during deployment.
This migration is intended to be used between "eras" of signatures. As
the serialization format of recipes changes, the signatures need to
also change. This could be handled automatically, but it is easier to
deploy if we just remove everything in a migration, and allow the
normal processes to regenerate the signatures.
"""
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
def remove_signatures(apps, schema_editor):
Recipe = apps.get_model('recipes', 'Recipe')
Action = apps.get_model('recipes', 'Action')
Signature = apps.get_model('recipes', 'Signature')
for recipe in Recipe.objects.exclude(signature=None):
sig = recipe.signature
recipe.signature = None
recipe.save()
sig.delete()
for action in Action.objects.exclude(signature=None):
sig = action.signature
action.signature = None
action.save()
action.delete()
for sig in Signature.objects.all():
sig.delete()
class Migration(migrations.Migration):
dependencies = [
('recipes', '0045_update_action_hashes'),
]
operations = [
# This function as both a forward and reverse migration
migrations.RunPython(remove_signatures, remove_signatures),
]
| """
Removes signatures, so they can be easily recreated during deployment.
This migration is intended to be used between "eras" of signatures. As
the serialization format of recipes changes, the signatures need to
also change. This could be handled automatically, but it is easier to
deploy if we just remove everything in a migration, and allow the
normal processes to regenerate the signatures.
"""
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
def remove_signatures(apps, schema_editor):
Recipe = apps.get_model('recipes', 'Recipe')
Action = apps.get_model('recipes', 'Action')
Signature = apps.get_model('recipes', 'Signature')
for recipe in Recipe.objects.exclude(signature=None):
sig = recipe.signature
recipe.signature = None
recipe.save()
sig.delete()
for action in Action.objects.exclude(signature=None):
sig = action.signature
action.signature = None
action.save()
sig.delete()
for sig in Signature.objects.all():
sig.delete()
class Migration(migrations.Migration):
dependencies = [
('recipes', '0045_update_action_hashes'),
]
operations = [
# This function as both a forward and reverse migration
migrations.RunPython(remove_signatures, remove_signatures),
]
| Fix data loss bug in migration. | Fix data loss bug in migration.
We should be deleting the signature to invalidate it, not the action itself.
| Python | mpl-2.0 | mozilla/normandy,mozilla/normandy,mozilla/normandy,mozilla/normandy | ---
+++
@@ -29,7 +29,7 @@
sig = action.signature
action.signature = None
action.save()
- action.delete()
+ sig.delete()
for sig in Signature.objects.all():
sig.delete() |
8e316a4b1305e8fb49e89b867b30bd27b428e689 | test/example/manage.py | test/example/manage.py | #!/usr/bin/env python
from django.core.management import execute_manager
try:
import settings # Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
sys.exit(1)
if __name__ == "__main__":
execute_manager(settings)
| #!/usr/bin/env python
from django.core.management import execute_manager
import sys
sys.path.insert(0, '../../')
try:
import settings # Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
sys.exit(1)
if __name__ == "__main__":
execute_manager(settings)
| Make the test suite use the development version of djqmethod. | Make the test suite use the development version of djqmethod.
| Python | unlicense | zacharyvoase/django-qmethod,fdemmer/django-qmethod | ---
+++
@@ -1,5 +1,7 @@
#!/usr/bin/env python
from django.core.management import execute_manager
+import sys
+sys.path.insert(0, '../../')
try:
import settings # Assumed to be in the same directory.
except ImportError: |
5590582fba18f94bec0fab4bd82982ce7d91de3b | backend/generateGeotiff.py | backend/generateGeotiff.py |
# TODO almost everything
src_ds = gdal.Open( src_filename )
dst_ds = driver.CreateCopy( dst_filename, src_ds, 0 )
# Once we're done, close properly the dataset
dst_ds = None
src_ds = None
| from osgeo import gdal, ogr
src_filename = "../../aineisto/Clc2012_FI20m_Espoo.tif"
dst_filename = "../../output/mustikka.tif"
src_ds = gdal.Open(src_filename)
driver = src_ds.GetDriver()
dst_ds = driver.CreateCopy(dst_filename, src_ds, 0)
# TODO modify the destination dataset
# Once we're done, close properly the dataset
dst_ds = None
src_ds = None
| Save destination dataset (still identical to source dataset) | Save destination dataset (still identical to source dataset)
| Python | mit | lukefi/missamustikka,lukefi/missamustikka,lukefi/missamustikka | ---
+++
@@ -1,8 +1,14 @@
+from osgeo import gdal, ogr
-# TODO almost everything
+src_filename = "../../aineisto/Clc2012_FI20m_Espoo.tif"
+dst_filename = "../../output/mustikka.tif"
-src_ds = gdal.Open( src_filename )
-dst_ds = driver.CreateCopy( dst_filename, src_ds, 0 )
+src_ds = gdal.Open(src_filename)
+driver = src_ds.GetDriver()
+dst_ds = driver.CreateCopy(dst_filename, src_ds, 0)
+
+# TODO modify the destination dataset
+
# Once we're done, close properly the dataset
dst_ds = None
src_ds = None |
0da1f02c0f6bb554a8a093bd4c597ebbe45e479b | tests/unit/test_objector.py | tests/unit/test_objector.py | from . import UnitTest
class TestObjector(UnitTest):
def test_objectify_returns_None_for_None(self):
assert self.reddit._objector.objectify(None) is None
| import pytest
from praw.exceptions import APIException, ClientException
from . import UnitTest
class TestObjector(UnitTest):
def test_objectify_returns_None_for_None(self):
assert self.reddit._objector.objectify(None) is None
def test_parse_error(self):
objector = self.reddit._objector
assert objector.parse_error({}) is None
assert objector.parse_error([]) is None
assert objector.parse_error({"asdf": 1}) is None
error_response = {
"json": {
"errors": [
["USER_REQUIRED", "Please log in to do that.", None]
]
}
}
error = objector.parse_error(error_response)
assert isinstance(error, APIException)
error_response = {"json": {"errors": []}}
with pytest.raises(ClientException):
objector.parse_error(error_response)
error_response = {
"json": {
"errors": [
["USER_REQUIRED", "Please log in to do that.", None],
["NO_SUBJECT", "please enter a subject", "subject"],
]
}
}
with pytest.raises(AssertionError):
objector.parse_error(error_response)
def test_check_error(self):
objector = self.reddit._objector
objector.check_error({"asdf": 1})
error_response = {
"json": {
"errors": [
["USER_REQUIRED", "Please log in to do that.", None]
]
}
}
with pytest.raises(APIException):
objector.check_error(error_response)
| Add tests for `Objector.parse_error()` and `.check_error()` | Add tests for `Objector.parse_error()` and `.check_error()`
| Python | bsd-2-clause | praw-dev/praw,gschizas/praw,leviroth/praw,leviroth/praw,gschizas/praw,praw-dev/praw | ---
+++
@@ -1,6 +1,55 @@
+import pytest
+
+from praw.exceptions import APIException, ClientException
+
from . import UnitTest
class TestObjector(UnitTest):
def test_objectify_returns_None_for_None(self):
assert self.reddit._objector.objectify(None) is None
+
+ def test_parse_error(self):
+ objector = self.reddit._objector
+ assert objector.parse_error({}) is None
+ assert objector.parse_error([]) is None
+ assert objector.parse_error({"asdf": 1}) is None
+
+ error_response = {
+ "json": {
+ "errors": [
+ ["USER_REQUIRED", "Please log in to do that.", None]
+ ]
+ }
+ }
+ error = objector.parse_error(error_response)
+ assert isinstance(error, APIException)
+
+ error_response = {"json": {"errors": []}}
+ with pytest.raises(ClientException):
+ objector.parse_error(error_response)
+
+ error_response = {
+ "json": {
+ "errors": [
+ ["USER_REQUIRED", "Please log in to do that.", None],
+ ["NO_SUBJECT", "please enter a subject", "subject"],
+ ]
+ }
+ }
+ with pytest.raises(AssertionError):
+ objector.parse_error(error_response)
+
+ def test_check_error(self):
+ objector = self.reddit._objector
+ objector.check_error({"asdf": 1})
+
+ error_response = {
+ "json": {
+ "errors": [
+ ["USER_REQUIRED", "Please log in to do that.", None]
+ ]
+ }
+ }
+ with pytest.raises(APIException):
+ objector.check_error(error_response) |
e66894584a3762af2db8ebdbc4269e6aee1bc24e | thesite/thesite/urls.py | thesite/thesite/urls.py | from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns(
'', # First arg to patterns is a namespace parameter.
# A handful of views in a base app.
url(r'^$', 'base_app.views.site_index'),
url(r'^logout/$', 'base_app.views.logout'),
url(r'^create_user/$', 'base_app.views.create_user'),
url(r'^login/$', 'base_app.views.login'),
# Actual pet communication views -- most of the app is here.
url(r'^pets/', include('communication_app.urls')),
# Django admin.
url(r'^admin/', include(admin.site.urls)),
)
| from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns(
'', # First arg to patterns is a namespace parameter.
# A handful of views in a base app.
url(r'^$', 'base_app.views.site_index'),
url(r'^logout/$', 'base_app.views.logout'),
url(r'^create_user/$', 'base_app.views.create_user'),
url(r'^login/$', 'base_app.views.login'),
# Actual pet communication views -- most of the app is here.
url(r'^pets/', include('communication_app.urls')),
# Include the views from Asheesh's Django Optimizer
url(r'^optimizer/', include('asheeshs_django_optimizer.urls')),
# Django admin.
url(r'^admin/', include(admin.site.urls)),
)
| Include views from the Django Optimizer | Include views from the Django Optimizer
| Python | apache-2.0 | petwitter/petwitter,petwitter/petwitter,petwitter/petwitter | ---
+++
@@ -14,6 +14,9 @@
# Actual pet communication views -- most of the app is here.
url(r'^pets/', include('communication_app.urls')),
+ # Include the views from Asheesh's Django Optimizer
+ url(r'^optimizer/', include('asheeshs_django_optimizer.urls')),
+
# Django admin.
url(r'^admin/', include(admin.site.urls)),
) |
249367a835166ca9740cf70f36d6f61c43e0581a | tests/test_encoding.py | tests/test_encoding.py | import os, sys; sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
import codecs
import pytest
from lasio import read
egfn = lambda fn: os.path.join(os.path.dirname(__file__), "examples", fn)
| import os, sys; sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
import codecs
import pytest
from lasio import read
egfn = lambda fn: os.path.join(os.path.dirname(__file__), "examples", fn)
def test_utf8_default():
fn = egfn("sample_extended_chars_utf8.las")
l = read(fn)
def test_utf8wbom_default():
fn = egfn("sample_extended_chars_utf8wbom.las")
l = read(fn)
def test_cp1252_default():
fn = egfn("sample_extended_chars_cp1252.las")
l = read(fn)
def test_utf8_autodetect():
fn = egfn("sample_extended_chars_utf8.las")
l = read(fn, autodetect_encoding=True)
def test_utf8wbom_autodetect():
fn = egfn("sample_extended_chars_utf8wbom.las")
l = read(fn, autodetect_encoding=True)
def test_cp1252_autodetect():
fn = egfn("sample_extended_chars_cp1252.las")
l = read(fn, autodetect_encoding=True)
def test_utf8_encoding_specified():
fn = egfn("sample_extended_chars_utf8.las")
l = read(fn, encoding="utf-8")
def test_utf8wbom_encoding_specified():
fn = egfn("sample_extended_chars_utf8wbom.las")
l = read(fn, encoding="utf-8-sig")
def test_cp1252_encoding_specified():
fn = egfn("sample_extended_chars_cp1252.las")
l = read(fn, encoding="cp1252")
| Add some possibly ineffective tests... | Add some possibly ineffective tests...
| Python | mit | Kramer477/lasio,kwinkunks/lasio,kinverarity1/lasio,kinverarity1/las-reader | ---
+++
@@ -8,3 +8,39 @@
egfn = lambda fn: os.path.join(os.path.dirname(__file__), "examples", fn)
+def test_utf8_default():
+ fn = egfn("sample_extended_chars_utf8.las")
+ l = read(fn)
+
+def test_utf8wbom_default():
+ fn = egfn("sample_extended_chars_utf8wbom.las")
+ l = read(fn)
+
+def test_cp1252_default():
+ fn = egfn("sample_extended_chars_cp1252.las")
+ l = read(fn)
+
+def test_utf8_autodetect():
+ fn = egfn("sample_extended_chars_utf8.las")
+ l = read(fn, autodetect_encoding=True)
+
+def test_utf8wbom_autodetect():
+ fn = egfn("sample_extended_chars_utf8wbom.las")
+ l = read(fn, autodetect_encoding=True)
+
+def test_cp1252_autodetect():
+ fn = egfn("sample_extended_chars_cp1252.las")
+ l = read(fn, autodetect_encoding=True)
+
+def test_utf8_encoding_specified():
+ fn = egfn("sample_extended_chars_utf8.las")
+ l = read(fn, encoding="utf-8")
+
+def test_utf8wbom_encoding_specified():
+ fn = egfn("sample_extended_chars_utf8wbom.las")
+ l = read(fn, encoding="utf-8-sig")
+
+def test_cp1252_encoding_specified():
+ fn = egfn("sample_extended_chars_cp1252.las")
+ l = read(fn, encoding="cp1252")
+ |
45663e1d344e8802db37dfb6e040fbcacce90a0d | tests/test_examples.py | tests/test_examples.py | import os
import re
import sys
import unittest
from functools import partial
class TestExamples(unittest.TestCase):
pass
def test_file(filename):
# Ignore the output
saved = sys.stdout
with open('/dev/null', 'w') as stdout:
sys.stdout = stdout
try:
with open(filename) as f:
code = compile(f.read(), filename, 'exec')
exec(code)
finally:
sys.stdout = saved
def add_tests():
# Filter out all *.py files from the examples directory
examples = 'examples'
regex = re.compile(r'.py$', re.I)
example_filesnames = filter(regex.search, os.listdir(examples))
# Add new test functions to the TestExamples class
for f in example_filesnames:
testname = 'test_' + f[:-3]
testfunc = partial(test_file, examples + '/' + f)
# Get rid of partial() __doc__
testfunc.__doc__ = None
setattr(TestExamples, testname, testfunc)
add_tests()
if __name__ == '__main__':
unittest.main()
| import os
import re
import sys
import unittest
from functools import partial
class TestExamples(unittest.TestCase):
pass
def _test_file(filename):
# Ignore the output
saved = sys.stdout
with open('/dev/null', 'w') as stdout:
sys.stdout = stdout
try:
with open(filename) as f:
code = compile(f.read(), filename, 'exec')
exec(code)
finally:
sys.stdout = saved
def add_tests():
# Filter out all *.py files from the examples directory
examples = 'examples'
regex = re.compile(r'.py$', re.I)
example_filesnames = filter(regex.search, os.listdir(examples))
# Add new test functions to the TestExamples class
for f in example_filesnames:
testname = 'test_' + f[:-3]
testfunc = partial(_test_file, examples + '/' + f)
# Get rid of partial() __doc__
testfunc.__doc__ = None
setattr(TestExamples, testname, testfunc)
add_tests()
if __name__ == '__main__':
unittest.main()
| Rename test_file to make nosetest happy | Rename test_file to make nosetest happy
| Python | bsd-2-clause | nicolaka/troposphere,ikben/troposphere,cloudtools/troposphere,mannytoledo/troposphere,horacio3/troposphere,ptoraskar/troposphere,iblazevic/troposphere,ccortezb/troposphere,kid/troposphere,pas256/troposphere,inetCatapult/troposphere,7digital/troposphere,amosshapira/troposphere,jantman/troposphere,garnaat/troposphere,jdc0589/troposphere,dmm92/troposphere,craigbruce/troposphere,horacio3/troposphere,wangqiang8511/troposphere,xxxVxxx/troposphere,alonsodomin/troposphere,yxd-hde/troposphere,micahhausler/troposphere,dmm92/troposphere,unravelin/troposphere,ikben/troposphere,WeAreCloudar/troposphere,samcrang/troposphere,LouTheBrew/troposphere,cloudtools/troposphere,7digital/troposphere,alonsodomin/troposphere,Yipit/troposphere,pas256/troposphere,DualSpark/troposphere,Hons/troposphere,johnctitus/troposphere,johnctitus/troposphere,cryptickp/troposphere,mhahn/troposphere | ---
+++
@@ -10,7 +10,7 @@
pass
-def test_file(filename):
+def _test_file(filename):
# Ignore the output
saved = sys.stdout
with open('/dev/null', 'w') as stdout:
@@ -32,7 +32,7 @@
# Add new test functions to the TestExamples class
for f in example_filesnames:
testname = 'test_' + f[:-3]
- testfunc = partial(test_file, examples + '/' + f)
+ testfunc = partial(_test_file, examples + '/' + f)
# Get rid of partial() __doc__
testfunc.__doc__ = None
setattr(TestExamples, testname, testfunc) |
1889814dc2c2ecc288cc6672de9aa747f55f3ca2 | tests/test_fei_tiff.py | tests/test_fei_tiff.py | """Test FEI SEM image plugin functionality.
FEI TIFFs contain metadata as ASCII plaintext at the end of the file.
"""
from __future__ import unicode_literals
import os
import numpy as np
from imageio.testing import run_tests_if_main, get_test_dir, need_internet
from imageio.core import get_remote_file
import imageio
def test_fei_file_reading():
need_internet() # We keep a test image in the imageio-binaries repo
fei_filename = get_remote_file('images/fei-sem-rbc.tif')
reader = imageio.get_reader(fei_filename, format='fei')
image = reader.get_data(0) # imageio.Image object
assert image.shape == (1024, 1536)
assert np.round(np.mean(image)) == 137
assert len(image.meta) == 18
assert image.meta['EScan']['PixelHeight'] == '7.70833e-009'
assert reader.get_data(0, discard_watermark=False).shape == (1094, 1536)
def test_fei_file_fail():
normal_tif = os.path.join(get_test_dir(), 'test_tiff.tiff')
bad_reader = imageio.get_reader(normal_tif, format='fei')
np.testing.assert_raises(ValueError, bad_reader._get_meta_data)
run_tests_if_main()
| """Test FEI SEM image plugin functionality.
FEI TIFFs contain metadata as ASCII plaintext at the end of the file.
"""
from __future__ import unicode_literals
import os
import numpy as np
from imageio.testing import run_tests_if_main, get_test_dir, need_internet
from imageio.core import get_remote_file
import imageio
def test_fei_file_reading():
need_internet() # We keep a test image in the imageio-binaries repo
fei_filename = get_remote_file('images/fei-sem-rbc.tif')
reader = imageio.get_reader(fei_filename, format='fei')
image = reader.get_data(0) # imageio.Image object
assert image.shape == (1024, 1536)
assert np.round(np.mean(image)) == 137
assert len(image.meta) == 18
assert image.meta['EScan']['PixelHeight'] == '7.70833e-009'
assert reader.get_data(0, discard_watermark=False).shape == (1094, 1536)
def test_fei_file_fail():
normal_tif = os.path.join(get_test_dir(), 'test_tiff.tiff')
bad_reader = imageio.get_reader(normal_tif, format='fei')
np.testing.assert_raises(ValueError, bad_reader._get_meta_data)
run_tests_if_main()
| Remove stray whitespace in test file | Remove stray whitespace in test file
| Python | bsd-2-clause | imageio/imageio | ---
+++
@@ -16,7 +16,7 @@
def test_fei_file_reading():
need_internet() # We keep a test image in the imageio-binaries repo
- fei_filename = get_remote_file('images/fei-sem-rbc.tif')
+ fei_filename = get_remote_file('images/fei-sem-rbc.tif')
reader = imageio.get_reader(fei_filename, format='fei')
image = reader.get_data(0) # imageio.Image object
assert image.shape == (1024, 1536) |
4bf565e363b96dbc13c7c9ba6f592aac6c98ac09 | competition_settings.py | competition_settings.py | # competition_settings.py
# This file contains settings for the current competition.
# This include start and end dates along with round information.
import datetime # Only used to dynamically set the round dates.
# The start and end date of the competition.
COMPETITION_START = (datetime.date.today() - datetime.timedelta(days=3)).strftime("%Y-%m-%d")
COMPETITION_END = (datetime.date.today() + datetime.timedelta(days=6)).strftime("%Y-%m-%d")
# The rounds of the competition. Specify dates using "yyyy-mm-dd".
# Start means the competition will start at midnight on that date.
# End means the competition will end at midnight of that date.
# This means that a round that ends on "2010-08-02" will end at 11:59pm of August 2nd.
COMPETITION_ROUNDS = {
"Round 1" : {
"start": (datetime.date.today() - datetime.timedelta(days=3)).strftime("%Y-%m-%d"),
"end": (datetime.date.today() + datetime.timedelta(days=3)).strftime("%Y-%m-%d"),
},
}
# When enabled, users who try to access the site before or after the competition ends are blocked.
# Admin users are able to log in at any time.
CAN_ACCESS_OUTSIDE_COMPETITION = False
| # competition_settings.py
# This file contains settings for the current competition.
# This include start and end dates along with round information.
import datetime # Only used to dynamically set the round dates.
# The start and end date of the competition.
COMPETITION_START = (datetime.date.today() - datetime.timedelta(days=3)).strftime("%Y-%m-%d")
COMPETITION_END = (datetime.date.today() + datetime.timedelta(days=6)).strftime("%Y-%m-%d")
# The rounds of the competition. Specify dates using "yyyy-mm-dd".
# Start means the competition will start at midnight on that date.
# End means the competition will end at midnight of that date.
# This means that a round that ends on "2010-08-02" will end at 11:59pm of August 1st.
COMPETITION_ROUNDS = {
"Round 1" : {
"start": (datetime.date.today() - datetime.timedelta(days=3)).strftime("%Y-%m-%d"),
"end": (datetime.date.today() + datetime.timedelta(days=3)).strftime("%Y-%m-%d"),
},
}
# When enabled, users who try to access the site before or after the competition ends are blocked.
# Admin users are able to log in at any time.
CAN_ACCESS_OUTSIDE_COMPETITION = False
| Comment for the competition settings did not make sense. | Comment for the competition settings did not make sense.
| Python | mit | jtakayama/makahiki-draft,yongwen/makahiki,justinslee/Wai-Not-Makahiki,csdl/makahiki,csdl/makahiki,csdl/makahiki,jtakayama/makahiki-draft,jtakayama/ics691-setupbooster,yongwen/makahiki,yongwen/makahiki,jtakayama/ics691-setupbooster,yongwen/makahiki,jtakayama/makahiki-draft,jtakayama/ics691-setupbooster,jtakayama/makahiki-draft,csdl/makahiki | ---
+++
@@ -10,7 +10,7 @@
# The rounds of the competition. Specify dates using "yyyy-mm-dd".
# Start means the competition will start at midnight on that date.
# End means the competition will end at midnight of that date.
-# This means that a round that ends on "2010-08-02" will end at 11:59pm of August 2nd.
+# This means that a round that ends on "2010-08-02" will end at 11:59pm of August 1st.
COMPETITION_ROUNDS = {
"Round 1" : {
"start": (datetime.date.today() - datetime.timedelta(days=3)).strftime("%Y-%m-%d"), |
0ec5b3887e42191f1b1dda3c8b0f199655674394 | main.py | main.py | #! /usr/bin/python
from __future__ import print_function
import db, os, sys, re
import argparse
import json
from collections import namedtuple
tf2_key = namedtuple('tf2_key', "server_account server_token steam_account host")
# Initial setup of DB
# We keep the connection & cursor seperate so we can do commits when we want
dbPath = os.path.join(os.path.dirname(os.path.realpath(__file__)), "tf2_keys.db")
if not os.path.isfile(dbPath):
db.createDB(dbPath)
dbconn = db.startDB(dbPath)
dbcursor = dbconn.cursor()
# End initial setup
parser = argparse.ArgumentParser(description='Manage TF2 keys')
parser.add_argument('-a', '--add', nargs=3,
help="Add key, format: <server_account> <server_token> <steam_account>"
)
parser.add_argument('host', nargs='?', help="Host to retrieve keys for")
args = parser.parse_args()
if args.add:
key = tf2_key(int(args.add[0]), args.add[1], args.add[2], args.host)
db.addKey(dbcursor, key)
elif args.host:
print(json.dumps(tf2_key(*key)))
key = db.getKey(dbcursor, args.host)
else:
sys.exit(1)
# Close the cursor & commit the DB one last time just for good measure
dbcursor.close()
dbconn.commit()
| #! /usr/bin/python
from __future__ import print_function
import db, os, sys, re
import argparse
import json
from collections import namedtuple
tf2_key = namedtuple('tf2_key', "server_account server_token steam_account host")
# Initial setup of DB
# We keep the connection & cursor seperate so we can do commits when we want
dbPath = os.path.join(os.path.dirname(os.path.realpath(__file__)), "tf2_keys.db")
if not os.path.isfile(dbPath):
db.createDB(dbPath)
dbconn = db.startDB(dbPath)
dbcursor = dbconn.cursor()
# End initial setup
parser = argparse.ArgumentParser(description='Manage TF2 keys')
parser.add_argument('-a', '--add', nargs=3,
help="Add key, format: <server_account> <server_token> <steam_account>"
)
parser.add_argument('host', nargs='?', help="Host to retrieve keys for")
args = parser.parse_args()
if args.add:
key = tf2_key(int(args.add[0]), args.add[1], args.add[2], args.host)
db.addKey(dbcursor, key)
elif args.host:
key = db.getKey(dbcursor, args.host)
for entry in key:
print(entry)
else:
sys.exit(1)
# Close the cursor & commit the DB one last time just for good measure
dbcursor.close()
dbconn.commit()
| Print everything on individual lines | Print everything on individual lines
| Python | mit | cloudgameservers/tf2-keyserver | ---
+++
@@ -27,8 +27,9 @@
key = tf2_key(int(args.add[0]), args.add[1], args.add[2], args.host)
db.addKey(dbcursor, key)
elif args.host:
- print(json.dumps(tf2_key(*key)))
key = db.getKey(dbcursor, args.host)
+ for entry in key:
+ print(entry)
else:
sys.exit(1)
# Close the cursor & commit the DB one last time just for good measure |
4ffb58466820cfb2569cf4d4837c8e48caed2c17 | seven23/api/permissions.py | seven23/api/permissions.py |
from itertools import chain
from rest_framework import permissions
from django.utils import timezone
from seven23 import settings
class CanWriteAccount(permissions.BasePermission):
"""
Object-level permission to only allow owners of an object to edit it.
Assumes the model instance has an `owner` attribute.
"""
def has_object_permission(self, request, view, obj):
# Read permissions are allowed to any request,
# so we'll always allow GET, HEAD or OPTIONS requests.
# Instance must have an attribute named `owner`.
return obj.account.id in list(chain(
request.user.accounts.values_list('id', flat=True),
request.user.guests.values_list('account__id', flat=True)
))
class IsPaid(permissions.BasePermission):
"""
Check if user has a paid formula
"""
def has_permission(self, request, view):
# Read permissions are allowed to any request,
# so we'll always allow GET, HEAD or OPTIONS requests.
if not settings.SAAS:
return True
if request.method in permissions.SAFE_METHODS:
return True
return request.user.profile.valid_until > timezone.now() |
from itertools import chain
from rest_framework import permissions
from datetime import datetime
from seven23 import settings
class CanWriteAccount(permissions.BasePermission):
"""
Object-level permission to only allow owners of an object to edit it.
Assumes the model instance has an `owner` attribute.
"""
def has_object_permission(self, request, view, obj):
# Read permissions are allowed to any request,
# so we'll always allow GET, HEAD or OPTIONS requests.
# Instance must have an attribute named `owner`.
return obj.account.id in list(chain(
request.user.accounts.values_list('id', flat=True),
request.user.guests.values_list('account__id', flat=True)
))
class IsPaid(permissions.BasePermission):
"""
Check if user has a paid formula
"""
def has_permission(self, request, view):
# Read permissions are allowed to any request,
# so we'll always allow GET, HEAD or OPTIONS requests.
if not settings.SAAS:
return True
if request.method in permissions.SAFE_METHODS:
return True
return request.user.profile.valid_until > datetime.today() | Fix issue with imezone on IsPaid Permission | Fix issue with imezone on IsPaid Permission
| Python | mit | sebastienbarbier/723e,sebastienbarbier/723e_server,sebastienbarbier/723e_server,sebastienbarbier/723e | ---
+++
@@ -1,7 +1,7 @@
from itertools import chain
from rest_framework import permissions
-from django.utils import timezone
+from datetime import datetime
from seven23 import settings
class CanWriteAccount(permissions.BasePermission):
@@ -34,4 +34,4 @@
if request.method in permissions.SAFE_METHODS:
return True
- return request.user.profile.valid_until > timezone.now()
+ return request.user.profile.valid_until > datetime.today() |
b2bc9a893a8b7fea59759e74be6235b890a1ff96 | keybaseproofbot/models.py | keybaseproofbot/models.py | from sqlalchemy import Column, Integer, String
from keybaseproofbot.database import Base
class Proof(Base):
__tablename__ = 'proofs'
user_id = Column(Integer, primary_key=True)
keybase_username = Column(String)
telegram_username = Column(String)
chat_id = Column(Integer)
message_id = Column(Integer)
proof_object = Column(String)
signed_block = Column(String)
def __init__(self, user_id, keybase_username, telegram_username, chat_id,
message_id, proof_object, signed_block):
self.user_id = user_id
self.keybase_username = keybase_username
self.telegram_username = telegram_username
self.chat_id = chat_id
self.message_id = message_id
self.proof_object = proof_object
self.signed_block = signed_block
| from sqlalchemy import Column, BigInteger, String
from keybaseproofbot.database import Base
class Proof(Base):
__tablename__ = 'proofs'
user_id = Column(BigInteger, primary_key=True)
keybase_username = Column(String)
telegram_username = Column(String)
chat_id = Column(BigInteger)
message_id = Column(BigInteger)
proof_object = Column(String)
signed_block = Column(String)
def __init__(self, user_id, keybase_username, telegram_username, chat_id,
message_id, proof_object, signed_block):
self.user_id = user_id
self.keybase_username = keybase_username
self.telegram_username = telegram_username
self.chat_id = chat_id
self.message_id = message_id
self.proof_object = proof_object
self.signed_block = signed_block
| Make ids BigInteger for postgres | Make ids BigInteger for postgres | Python | mit | pingiun/keybaseproofbot | ---
+++
@@ -1,15 +1,15 @@
-from sqlalchemy import Column, Integer, String
+from sqlalchemy import Column, BigInteger, String
from keybaseproofbot.database import Base
class Proof(Base):
__tablename__ = 'proofs'
- user_id = Column(Integer, primary_key=True)
+ user_id = Column(BigInteger, primary_key=True)
keybase_username = Column(String)
telegram_username = Column(String)
- chat_id = Column(Integer)
- message_id = Column(Integer)
+ chat_id = Column(BigInteger)
+ message_id = Column(BigInteger)
proof_object = Column(String)
signed_block = Column(String)
|
def21e127c287a01fc390b710cdb4fb0806affa5 | ogre.py | ogre.py | #!/usr/bin/python
def ogre_get(kinds, sources, relations):
"""Get local or recent media from a public source and return a dictionary.
kinds -- a medium of content to get
sources -- a source to get content from
relations -- a dictionary of 2-tuples specifying
a location or time and a radius
"""
for kind in kinds:
kind.lower()
if media not in ["image", "sound", "text", "video"]:
print "invalid kind ", kind
return
for source in sources:
source.lower()
if source not in ["twitter"]:
print "invalid source ", source
return
for relation in relations.keys():
if relation not in ["location", "time"]:
print "invalid relation ", relation
return
pass # TODO Call the appropriate handler based on parameters.
return
| #!/usr/bin/python
def get(kinds, sources, relations):
"""Get local or recent media from a public source and return a dictionary.
kinds -- a tuple of content mediums to get
sources -- a tuple of sources to get content from
relations -- a dictionary of 2-tuples specifying
a location or time and a radius
"""
for kind in kinds:
if kind.lower() not in ["image", "sound", "text", "video"]:
print "invalid kind", kind
return
for source in sources:
if source.lower() not in ["twitter"]:
print "invalid source", source
return
for relation in relations.keys():
if relation.lower() not in ["location", "time"]:
print "invalid relation", relation
return
pass # TODO Call the appropriate handler based on parameters.
return
| Fix casing and spacing bugs and rename query-handler. | Fix casing and spacing bugs and rename query-handler.
Unless string concatenation is used, print arguments are automatically
space-delimited. The lower method does not modify the object it is
called on. Since the module is called ogre, forcing developers to call
ogre.ogre_get or import the module/function into their namespace is not
desirable.
| Python | lgpl-2.1 | dmtucker/ogre | ---
+++
@@ -1,28 +1,26 @@
#!/usr/bin/python
-def ogre_get(kinds, sources, relations):
+def get(kinds, sources, relations):
"""Get local or recent media from a public source and return a dictionary.
- kinds -- a medium of content to get
- sources -- a source to get content from
+ kinds -- a tuple of content mediums to get
+ sources -- a tuple of sources to get content from
relations -- a dictionary of 2-tuples specifying
a location or time and a radius
"""
for kind in kinds:
- kind.lower()
- if media not in ["image", "sound", "text", "video"]:
- print "invalid kind ", kind
+ if kind.lower() not in ["image", "sound", "text", "video"]:
+ print "invalid kind", kind
return
for source in sources:
- source.lower()
- if source not in ["twitter"]:
- print "invalid source ", source
+ if source.lower() not in ["twitter"]:
+ print "invalid source", source
return
for relation in relations.keys():
- if relation not in ["location", "time"]:
- print "invalid relation ", relation
+ if relation.lower() not in ["location", "time"]:
+ print "invalid relation", relation
return
pass # TODO Call the appropriate handler based on parameters.
return |
4c4022e3a215b9b591220cd19fedbc501b63a1b2 | virtualenv/builders/base.py | virtualenv/builders/base.py | import sys
class BaseBuilder(object):
def __init__(self, python, system_site_packages=False, clear=False):
# We default to sys.executable if we're not given a Python.
if python is None:
python = sys.executable
self.python = python
self.system_site_packages = system_site_packages
self.clear = clear
def create(self, destination):
# Actually Create the virtual environment
self.create_virtual_environment(destination)
def create_virtual_environment(self, destination):
raise NotImplementedError
| import sys
class BaseBuilder(object):
def __init__(self, python, system_site_packages=False, clear=False):
# We default to sys.executable if we're not given a Python.
if python is None:
python = sys.executable
self.python = python
self.system_site_packages = system_site_packages
self.clear = clear
def create(self, destination):
# Actually Create the virtual environment
self.create_virtual_environment(destination)
# Install our activate scripts into the virtual environment
self.install_scripts(destination)
def create_virtual_environment(self, destination):
raise NotImplementedError
def install_scripts(self, destination):
pass
| Add a hook we'll eventually use to install the activate scripts | Add a hook we'll eventually use to install the activate scripts
| Python | mit | ionelmc/virtualenv,ionelmc/virtualenv,ionelmc/virtualenv | ---
+++
@@ -16,5 +16,11 @@
# Actually Create the virtual environment
self.create_virtual_environment(destination)
+ # Install our activate scripts into the virtual environment
+ self.install_scripts(destination)
+
def create_virtual_environment(self, destination):
raise NotImplementedError
+
+ def install_scripts(self, destination):
+ pass |
c0fd2b981f2657e0a78de028335ea172735c5f6b | zaqar/common/cli.py | zaqar/common/cli.py | # Copyright (c) 2013 Rackspace Hosting, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy
# of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under
# the License.
from __future__ import print_function
import functools
import sys
from zaqar.i18n import _
from zaqar.openstack.common import log as logging
LOG = logging.getLogger(__name__)
def _fail(returncode, ex):
"""Handles terminal errors.
:param returncode: process return code to pass to sys.exit
:param ex: the error that occurred
"""
LOG.exception(ex)
sys.exit(returncode)
def runnable(func):
"""Entry point wrapper.
Note: This call blocks until the process is killed
or interrupted.
"""
@functools.wraps(func)
def _wrapper():
try:
logging.setup('zaqar')
func()
except KeyboardInterrupt:
LOG.info(_(u'Terminating'))
except Exception as ex:
_fail(1, ex)
return _wrapper
| # Copyright (c) 2013 Rackspace Hosting, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy
# of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under
# the License.
from __future__ import print_function
import functools
import sys
from zaqar.i18n import _
from zaqar.openstack.common import log as logging
LOG = logging.getLogger(__name__)
def _fail(returncode, ex):
"""Handles terminal errors.
:param returncode: process return code to pass to sys.exit
:param ex: the error that occurred
"""
print(ex, file=sys.stderr)
LOG.exception(ex)
sys.exit(returncode)
def runnable(func):
"""Entry point wrapper.
Note: This call blocks until the process is killed
or interrupted.
"""
@functools.wraps(func)
def _wrapper():
try:
logging.setup('zaqar')
func()
except KeyboardInterrupt:
LOG.info(_(u'Terminating'))
except Exception as ex:
_fail(1, ex)
return _wrapper
| Fix regression: No handlers could be found for logger when start | Fix regression: No handlers could be found for logger when start
This change fixed a function regression on bug/1201562.
Closes-Bug: #1201562
Change-Id: I3994c97633f5d09cccf6defdf0eac3957d63304e
Signed-off-by: Zhi Yan Liu <98cb9f7b35c45309ab1e4c4eac6ba314b641cf7a@cn.ibm.com>
| Python | apache-2.0 | openstack/zaqar,openstack/zaqar,openstack/zaqar,openstack/zaqar | ---
+++
@@ -30,6 +30,8 @@
:param ex: the error that occurred
"""
+ print(ex, file=sys.stderr)
+
LOG.exception(ex)
sys.exit(returncode)
|
97f507ab5869c306ed468c683ca6e6e9b3266f5e | tests/tests/models/authorization_token.py | tests/tests/models/authorization_token.py | from django.test import TestCase
from django.contrib.auth.models import User
from doac.models import AuthorizationToken, Client, RefreshToken, Scope
class TestAuthorizationTokenModel(TestCase):
def setUp(self):
self.oclient = Client(name="Test Client", access_host="http://localhost/")
self.oclient.save()
self.scope = Scope(short_name="test", full_name="Test Scope", description="Scope for testing")
self.scope.save()
self.user = User(username="test", password="test", email="test@test.com")
self.user.save()
self.token = AuthorizationToken(client=self.oclient, user=self.user)
self.token.save()
self.token.scope = [self.scope]
self.token.save()
def test_unicode(self):
self.assertEqual(unicode(self.token), self.token.token)
def test_generate_refresh_token(self):
rt = self.token.generate_refresh_token()
self.assertEqual(RefreshToken.objects.count(), 1)
self.assertIsInstance(rt, RefreshToken)
rt = self.token.generate_refresh_token()
self.assertEqual(RefreshToken.objects.count(), 1)
self.assertIsNone(rt)
self.token.is_active = True
rt = self.token.generate_refresh_token()
self.assertEqual(RefreshToken.objects.count(), 1)
self.assertIsNone(rt)
| from django.test import TestCase
from django.contrib.auth.models import User
from doac.models import AuthorizationToken, Client, RefreshToken, Scope
class TestAuthorizationTokenModel(TestCase):
def setUp(self):
self.oclient = Client(name="Test Client", access_host="http://localhost/")
self.oclient.save()
self.scope = Scope(short_name="test", full_name="Test Scope", description="Scope for testing")
self.scope.save()
self.user = User(username="test", password="test", email="test@test.com")
self.user.save()
self.token = AuthorizationToken(client=self.oclient, user=self.user)
self.token.save()
self.token.scope = [self.scope]
self.token.save()
def test_unicode(self):
self.assertEqual(unicode(self.token), self.token.token)
def test_generate_refresh_token_creates(self):
rt = self.token.generate_refresh_token()
self.assertEqual(RefreshToken.objects.count(), 1)
self.assertIsInstance(rt, RefreshToken)
def test_generate_refresh_token_no_create_twice(self):
self.token.generate_refresh_token()
rt = self.token.generate_refresh_token()
self.assertEqual(RefreshToken.objects.count(), 1)
self.assertIsNone(rt)
def test_generate_refresh_token_never_creates_twice(self):
self.token.generate_refresh_token()
self.token.is_active = True
rt = self.token.generate_refresh_token()
self.assertEqual(RefreshToken.objects.count(), 1)
self.assertIsNone(rt)
| Split up the tests for AuthorizationToken | Split up the tests for AuthorizationToken
| Python | mit | Rediker-Software/doac | ---
+++
@@ -8,35 +8,39 @@
def setUp(self):
self.oclient = Client(name="Test Client", access_host="http://localhost/")
self.oclient.save()
-
+
self.scope = Scope(short_name="test", full_name="Test Scope", description="Scope for testing")
self.scope.save()
-
+
self.user = User(username="test", password="test", email="test@test.com")
self.user.save()
-
+
self.token = AuthorizationToken(client=self.oclient, user=self.user)
self.token.save()
-
+
self.token.scope = [self.scope]
self.token.save()
def test_unicode(self):
self.assertEqual(unicode(self.token), self.token.token)
-
- def test_generate_refresh_token(self):
+
+ def test_generate_refresh_token_creates(self):
rt = self.token.generate_refresh_token()
-
+
self.assertEqual(RefreshToken.objects.count(), 1)
self.assertIsInstance(rt, RefreshToken)
-
+
+ def test_generate_refresh_token_no_create_twice(self):
+ self.token.generate_refresh_token()
rt = self.token.generate_refresh_token()
-
+
self.assertEqual(RefreshToken.objects.count(), 1)
self.assertIsNone(rt)
-
+
+ def test_generate_refresh_token_never_creates_twice(self):
+ self.token.generate_refresh_token()
self.token.is_active = True
rt = self.token.generate_refresh_token()
-
+
self.assertEqual(RefreshToken.objects.count(), 1)
self.assertIsNone(rt) |
205b71aaad9103a1224a5c2999d66fd25a2714df | feder/teryt/autocomplete_light_registry.py | feder/teryt/autocomplete_light_registry.py | import autocomplete_light
from models import JednostkaAdministracyjna
# This will generate a PersonAutocomplete class
autocomplete_light.register(JednostkaAdministracyjna,
# Just like in ModelAdmin.search_fields
search_fields=['name'],
)
| import autocomplete_light
from .models import JednostkaAdministracyjna
# This will generate a PersonAutocomplete class
autocomplete_light.register(JednostkaAdministracyjna,
# Just like in ModelAdmin.search_fields
search_fields=['name'],
)
| Fix typo in teryt autocomplete | Fix typo in teryt autocomplete
| Python | mit | watchdogpolska/feder,watchdogpolska/feder,watchdogpolska/feder,watchdogpolska/feder | ---
+++
@@ -1,5 +1,5 @@
import autocomplete_light
-from models import JednostkaAdministracyjna
+from .models import JednostkaAdministracyjna
# This will generate a PersonAutocomplete class
autocomplete_light.register(JednostkaAdministracyjna, |
52f585aa3aaaa4f645b61575d6ca307555247bcc | appengine/models/product_group.py | appengine/models/product_group.py | from google.appengine.ext import ndb
from endpoints_proto_datastore.ndb import EndpointsModel
from endpoints_proto_datastore.ndb import EndpointsAliasProperty
from protorpc import messages
class ProductGroup(EndpointsModel):
_message_fields_schema = ('id', 'tag', 'description', 'url', 'image')
_api_key = None
# Hashtag to be used for the product group
tag = ndb.StringProperty()
# Description of the Activity Type / to be displayed in the Front End
description = ndb.StringProperty()
# URL of the Google Developers site for this product
url = ndb.StringProperty()
# Badge-image for this product
image = ndb.StringProperty()
def ApiKeySet(self, value):
self._api_key = value
@EndpointsAliasProperty(setter=ApiKeySet, property_type=messages.StringField)
def api_key(self):
return self._api_key
def IdSet(self, value):
if not isinstance(value, basestring):
raise TypeError('ID must be a string.')
self.UpdateFromKey(ndb.Key(ProductGroup, value))
@EndpointsAliasProperty(setter=IdSet, required=True)
def id(self):
if self.key is not None:
return self.key.string_id()
@classmethod
def all_tags(cls):
return [entity.tag for entity in cls.query()]
| from google.appengine.ext import ndb
from endpoints_proto_datastore.ndb import EndpointsModel
from endpoints_proto_datastore.ndb import EndpointsAliasProperty
from protorpc import messages
class ProductGroup(EndpointsModel):
_message_fields_schema = (
'id', 'tag', 'description', 'url', 'image', 'so_tags')
_api_key = None
# Hashtag to be used for the product group
tag = ndb.StringProperty()
# Description of the Activity Type / to be displayed in the Front End
description = ndb.StringProperty()
# URL of the Google Developers site for this product
url = ndb.StringProperty()
# Badge-image for this product
image = ndb.StringProperty()
# Stack Overflow tags of interest : issue #211 on github
so_tags = ndb.StringProperty(repeated=True)
def ApiKeySet(self, value):
self._api_key = value
@EndpointsAliasProperty(setter=ApiKeySet, property_type=messages.StringField)
def api_key(self):
return self._api_key
def IdSet(self, value):
if not isinstance(value, basestring):
raise TypeError('ID must be a string.')
self.UpdateFromKey(ndb.Key(ProductGroup, value))
@EndpointsAliasProperty(setter=IdSet, required=True)
def id(self):
if self.key is not None:
return self.key.string_id()
@classmethod
def all_tags(cls):
return [entity.tag for entity in cls.query()]
| Add so tags to ProductGroup entity | Add so tags to ProductGroup entity
| Python | apache-2.0 | GoogleDeveloperExperts/experts-app-backend | ---
+++
@@ -6,7 +6,8 @@
class ProductGroup(EndpointsModel):
- _message_fields_schema = ('id', 'tag', 'description', 'url', 'image')
+ _message_fields_schema = (
+ 'id', 'tag', 'description', 'url', 'image', 'so_tags')
_api_key = None
@@ -21,6 +22,9 @@
# Badge-image for this product
image = ndb.StringProperty()
+
+ # Stack Overflow tags of interest : issue #211 on github
+ so_tags = ndb.StringProperty(repeated=True)
def ApiKeySet(self, value):
self._api_key = value |
0a035a93666eb98b460d083e5dd822d7adb0614f | us_ignite/blog/admin.py | us_ignite/blog/admin.py | from django import forms
from django.contrib import admin
from django.contrib.auth.models import User
from us_ignite.common import sanitizer
from us_ignite.blog.models import BlogLink, Post, PostAttachment
from tinymce.widgets import TinyMCE
class PostAdminForm(forms.ModelForm):
author = forms.ModelChoiceField(
queryset=User.objects.filter(is_superuser=True))
def clean_content(self):
if 'content' in self.cleaned_data:
return sanitizer.sanitize(self.cleaned_data['content'])
class Meta:
model = Post
widgets = {
'content': TinyMCE(attrs={'cols': 80, 'rows': 30}),
}
class PostAttachmentInline(admin.StackedInline):
model = PostAttachment
class PostAdmin(admin.ModelAdmin):
list_display = ('title', 'author', 'is_published', 'is_featured', 'status')
list_filter = ('status', 'publication_date')
search_fields = ('slug', 'title', 'body', 'summary')
date_hierarchy = 'publication_date'
prepopulated_fields = {'slug': ('title',)}
form = PostAdminForm
inlines = [PostAttachmentInline]
class BlogLinkAdmin(admin.ModelAdmin):
list_display = ('name', 'url')
search_fields = ('name', 'url')
list_filter = ('created', )
date_hierarchy = 'created'
admin.site.register(Post, PostAdmin)
admin.site.register(BlogLink, BlogLinkAdmin)
| from django import forms
from django.contrib import admin
from django.contrib.auth.models import User
from us_ignite.common import sanitizer
from us_ignite.blog.models import BlogLink, Post, PostAttachment
from tinymce.widgets import TinyMCE
class PostAdminForm(forms.ModelForm):
author = forms.ModelChoiceField(
queryset=User.objects.filter(is_superuser=True), required=False)
def clean_content(self):
if 'content' in self.cleaned_data:
return sanitizer.sanitize(self.cleaned_data['content'])
class Meta:
model = Post
widgets = {
'content': TinyMCE(attrs={'cols': 80, 'rows': 30}),
}
class PostAttachmentInline(admin.StackedInline):
model = PostAttachment
class PostAdmin(admin.ModelAdmin):
list_display = ('title', 'author', 'is_published', 'is_featured', 'status')
list_filter = ('status', 'publication_date')
search_fields = ('slug', 'title', 'body', 'summary')
date_hierarchy = 'publication_date'
prepopulated_fields = {'slug': ('title',)}
form = PostAdminForm
inlines = [PostAttachmentInline]
class BlogLinkAdmin(admin.ModelAdmin):
list_display = ('name', 'url')
search_fields = ('name', 'url')
list_filter = ('created', )
date_hierarchy = 'created'
admin.site.register(Post, PostAdmin)
admin.site.register(BlogLink, BlogLinkAdmin)
| Make the blog author in the form a non required field. | Make the blog author in the form a non required field.
| Python | bsd-3-clause | us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite | ---
+++
@@ -10,7 +10,7 @@
class PostAdminForm(forms.ModelForm):
author = forms.ModelChoiceField(
- queryset=User.objects.filter(is_superuser=True))
+ queryset=User.objects.filter(is_superuser=True), required=False)
def clean_content(self):
if 'content' in self.cleaned_data: |
58e636838b0988814905fc163f369dd837aedfde | mopidy/backends/gstreamer.py | mopidy/backends/gstreamer.py | import logging
from mopidy.backends import BaseBackend, BasePlaybackController
logger = logging.getLogger(u'backends.gstreamer')
class GStreamerBackend(BaseBackend):
def __init__(self, *args, **kwargs):
super(GStreamerBackend, self).__init__(*args, **kwargs)
self.playback = GStreamerPlaybackController(self)
class GStreamerPlaybackController(BasePlaybackController):
def __init__(self, backend):
super(GStreamerPlaybackController, self).__init__(backend)
| import logging
import gst
from mopidy.backends import BaseBackend, BasePlaybackController
logger = logging.getLogger(u'backends.gstreamer')
class GStreamerBackend(BaseBackend):
def __init__(self, *args, **kwargs):
super(GStreamerBackend, self).__init__(*args, **kwargs)
self.playback = GStreamerPlaybackController(self)
class GStreamerPlaybackController(BasePlaybackController):
PAUSED = gst.STATE_PAUSED
PLAYING = gst.STATE_PLAYING
STOPPED = gst.STATE_NULL
def __init__(self, backend):
super(GStreamerPlaybackController, self).__init__(backend)
| Add playback states to GStreamer | Add playback states to GStreamer
| Python | apache-2.0 | abarisain/mopidy,rawdlite/mopidy,jodal/mopidy,SuperStarPL/mopidy,dbrgn/mopidy,hkariti/mopidy,swak/mopidy,jmarsik/mopidy,rawdlite/mopidy,swak/mopidy,adamcik/mopidy,glogiotatidis/mopidy,adamcik/mopidy,ali/mopidy,jmarsik/mopidy,mokieyue/mopidy,vrs01/mopidy,tkem/mopidy,woutervanwijk/mopidy,bencevans/mopidy,priestd09/mopidy,dbrgn/mopidy,jmarsik/mopidy,tkem/mopidy,pacificIT/mopidy,ali/mopidy,ali/mopidy,mokieyue/mopidy,rawdlite/mopidy,mopidy/mopidy,kingosticks/mopidy,bacontext/mopidy,ZenithDK/mopidy,glogiotatidis/mopidy,bacontext/mopidy,tkem/mopidy,kingosticks/mopidy,quartz55/mopidy,vrs01/mopidy,ZenithDK/mopidy,pacificIT/mopidy,mokieyue/mopidy,dbrgn/mopidy,bencevans/mopidy,ZenithDK/mopidy,priestd09/mopidy,bacontext/mopidy,ZenithDK/mopidy,jmarsik/mopidy,dbrgn/mopidy,SuperStarPL/mopidy,glogiotatidis/mopidy,diandiankan/mopidy,bencevans/mopidy,rawdlite/mopidy,jcass77/mopidy,jcass77/mopidy,kingosticks/mopidy,hkariti/mopidy,mokieyue/mopidy,glogiotatidis/mopidy,quartz55/mopidy,vrs01/mopidy,jodal/mopidy,mopidy/mopidy,tkem/mopidy,vrs01/mopidy,SuperStarPL/mopidy,liamw9534/mopidy,swak/mopidy,quartz55/mopidy,bencevans/mopidy,pacificIT/mopidy,diandiankan/mopidy,mopidy/mopidy,diandiankan/mopidy,priestd09/mopidy,quartz55/mopidy,SuperStarPL/mopidy,adamcik/mopidy,swak/mopidy,abarisain/mopidy,jcass77/mopidy,pacificIT/mopidy,hkariti/mopidy,woutervanwijk/mopidy,ali/mopidy,bacontext/mopidy,hkariti/mopidy,jodal/mopidy,diandiankan/mopidy,liamw9534/mopidy | ---
+++
@@ -1,4 +1,6 @@
import logging
+
+import gst
from mopidy.backends import BaseBackend, BasePlaybackController
@@ -11,5 +13,9 @@
self.playback = GStreamerPlaybackController(self)
class GStreamerPlaybackController(BasePlaybackController):
+ PAUSED = gst.STATE_PAUSED
+ PLAYING = gst.STATE_PLAYING
+ STOPPED = gst.STATE_NULL
+
def __init__(self, backend):
super(GStreamerPlaybackController, self).__init__(backend) |
2ac9b826fa56a9b146c90767fe0b7a77b1d7ea5a | test/test_cmdline_main.py | test/test_cmdline_main.py | import textwrap
from pathlib import Path
from unittest.mock import Mock, patch
import pytest
from pyinstrument.__main__ import main
from pyinstrument.renderers.console import ConsoleRenderer
from .util import BUSY_WAIT_SCRIPT
def test_renderer_option(monkeypatch: pytest.MonkeyPatch, tmp_path: Path):
(tmp_path / "test_program.py").write_text(BUSY_WAIT_SCRIPT)
monkeypatch.setattr("sys.argv", ["pyinstrument", "-p", "show_percentages", "test_program.py"])
monkeypatch.chdir(tmp_path)
with patch(
"pyinstrument.renderers.console.ConsoleRenderer", autospec=True
) as mock_renderer_class:
main()
mock_renderer_class.assert_called_once_with(show_percentages=True)
| import textwrap
from pathlib import Path
from unittest.mock import Mock, patch
import pytest
from pyinstrument.__main__ import main
from pyinstrument.renderers.console import ConsoleRenderer
from .util import BUSY_WAIT_SCRIPT
def test_renderer_option(monkeypatch: pytest.MonkeyPatch, tmp_path: Path):
(tmp_path / "test_program.py").write_text(BUSY_WAIT_SCRIPT)
monkeypatch.setattr(
"sys.argv", ["pyinstrument", "-p", "time=percent_of_total", "test_program.py"]
)
monkeypatch.chdir(tmp_path)
with patch(
"pyinstrument.__main__.renderers.ConsoleRenderer",
wraps=ConsoleRenderer,
) as mock_renderer_class:
main()
mock_renderer_class.assert_called_once()
assert mock_renderer_class.call_args.kwargs["time"] == "percent_of_total"
def test_processor_renderer_option(monkeypatch: pytest.MonkeyPatch, tmp_path: Path):
(tmp_path / "test_program.py").write_text(BUSY_WAIT_SCRIPT)
monkeypatch.setattr(
"sys.argv",
["pyinstrument", "-p", 'processor_options={"some_option": 44}', "test_program.py"],
)
monkeypatch.chdir(tmp_path)
with patch(
"pyinstrument.__main__.renderers.ConsoleRenderer",
wraps=ConsoleRenderer,
) as mock_renderer_class:
main()
mock_renderer_class.assert_called_once()
assert mock_renderer_class.call_args.kwargs["processor_options"]["some_option"] == 44
| Add tests for -p option | Add tests for -p option
| Python | bsd-3-clause | joerick/pyinstrument,joerick/pyinstrument,joerick/pyinstrument,joerick/pyinstrument,joerick/pyinstrument,joerick/pyinstrument | ---
+++
@@ -12,12 +12,34 @@
def test_renderer_option(monkeypatch: pytest.MonkeyPatch, tmp_path: Path):
(tmp_path / "test_program.py").write_text(BUSY_WAIT_SCRIPT)
- monkeypatch.setattr("sys.argv", ["pyinstrument", "-p", "show_percentages", "test_program.py"])
+ monkeypatch.setattr(
+ "sys.argv", ["pyinstrument", "-p", "time=percent_of_total", "test_program.py"]
+ )
monkeypatch.chdir(tmp_path)
with patch(
- "pyinstrument.renderers.console.ConsoleRenderer", autospec=True
+ "pyinstrument.__main__.renderers.ConsoleRenderer",
+ wraps=ConsoleRenderer,
) as mock_renderer_class:
main()
- mock_renderer_class.assert_called_once_with(show_percentages=True)
+ mock_renderer_class.assert_called_once()
+ assert mock_renderer_class.call_args.kwargs["time"] == "percent_of_total"
+
+
+def test_processor_renderer_option(monkeypatch: pytest.MonkeyPatch, tmp_path: Path):
+ (tmp_path / "test_program.py").write_text(BUSY_WAIT_SCRIPT)
+ monkeypatch.setattr(
+ "sys.argv",
+ ["pyinstrument", "-p", 'processor_options={"some_option": 44}', "test_program.py"],
+ )
+ monkeypatch.chdir(tmp_path)
+
+ with patch(
+ "pyinstrument.__main__.renderers.ConsoleRenderer",
+ wraps=ConsoleRenderer,
+ ) as mock_renderer_class:
+ main()
+
+ mock_renderer_class.assert_called_once()
+ assert mock_renderer_class.call_args.kwargs["processor_options"]["some_option"] == 44 |
e2f9c0c0e8b96e44c5410c242d0609ef36b5ee4e | tests/test_ghostscript.py | tests/test_ghostscript.py | import subprocess
import unittest
class GhostscriptTest(unittest.TestCase):
def test_installed(self):
process = subprocess.Popen(
['gs', '--version'],
stdin=None,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
stdout, stderr = process.communicate()
self.assertEqual(process.returncode, 0)
self.assertEqual(str(stderr), "")
self.assertRegexpMatches(str(stdout), r'9\.\d\d')
| import subprocess
import unittest
class GhostscriptTest(unittest.TestCase):
def test_installed(self):
process = subprocess.Popen(
['gs', '--version'],
universal_newlines=True,
stdin=None,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
stdout, stderr = process.communicate()
self.assertEqual(process.returncode, 0)
self.assertEqual(stderr, "")
self.assertRegexpMatches(stdout, r'9\.\d\d')
| Make Popen.communicate return output as strings not bytes. | Make Popen.communicate return output as strings not bytes.
| Python | mit | YPlan/treepoem | ---
+++
@@ -7,6 +7,7 @@
def test_installed(self):
process = subprocess.Popen(
['gs', '--version'],
+ universal_newlines=True,
stdin=None,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
@@ -14,5 +15,5 @@
stdout, stderr = process.communicate()
self.assertEqual(process.returncode, 0)
- self.assertEqual(str(stderr), "")
- self.assertRegexpMatches(str(stdout), r'9\.\d\d')
+ self.assertEqual(stderr, "")
+ self.assertRegexpMatches(stdout, r'9\.\d\d') |
6eb4c09cfc43e2f939660525101a1a8fac9c4838 | threadedcomments/forms.py | threadedcomments/forms.py | from django import forms
from django.contrib.comments.forms import CommentForm
from django.conf import settings
from django.utils.hashcompat import sha_constructor
from threadedcomments.models import ThreadedComment
class ThreadedCommentForm(CommentForm):
parent = forms.IntegerField(required=False, widget=forms.HiddenInput)
title = forms.CharField(required=False)
def __init__(self, target_object, parent=None, data=None, initial=None):
self.parent = parent
if initial is None:
initial = {}
initial.update({'parent': self.parent})
super(ThreadedCommentForm, self).__init__(target_object, data=data,
initial=initial)
def get_comment_model(self):
return ThreadedComment
def get_comment_create_data(self):
d = super(ThreadedCommentForm, self).get_comment_create_data()
d['parent_id'] = self.cleaned_data['parent']
d['title'] = self.cleaned_data['title']
return d
| from django import forms
from django.contrib.comments.forms import CommentForm
from django.conf import settings
from django.utils.hashcompat import sha_constructor
from threadedcomments.models import ThreadedComment
class ThreadedCommentForm(CommentForm):
parent = forms.IntegerField(required=False, widget=forms.HiddenInput)
def __init__(self, target_object, parent=None, data=None, initial=None):
self.base_fields.insert(
self.base_fields.keyOrder.index('comment'),
'title', forms.CharField(required=False)
)
self.parent = parent
if initial is None:
initial = {}
initial.update({'parent': self.parent})
super(ThreadedCommentForm, self).__init__(target_object, data=data,
initial=initial)
def get_comment_model(self):
return ThreadedComment
def get_comment_create_data(self):
d = super(ThreadedCommentForm, self).get_comment_create_data()
d['parent_id'] = self.cleaned_data['parent']
d['title'] = self.cleaned_data['title']
return d
| Make title field appear before comment in the form | Make title field appear before comment in the form
Fixes #7
| Python | bsd-3-clause | yrcjaya/django-threadedcomments,coxmediagroup/django-threadedcomments,nikolas/django-threadedcomments,ccnmtl/django-threadedcomments,yrcjaya/django-threadedcomments,nikolas/django-threadedcomments,SmithsonianEnterprises/django-threadedcomments,PolicyStat/django-threadedcomments,ccnmtl/django-threadedcomments,SmithsonianEnterprises/django-threadedcomments,HonzaKral/django-threadedcomments,coxmediagroup/django-threadedcomments,incuna/django-threadedcomments,HonzaKral/django-threadedcomments | ---
+++
@@ -7,9 +7,12 @@
class ThreadedCommentForm(CommentForm):
parent = forms.IntegerField(required=False, widget=forms.HiddenInput)
- title = forms.CharField(required=False)
def __init__(self, target_object, parent=None, data=None, initial=None):
+ self.base_fields.insert(
+ self.base_fields.keyOrder.index('comment'),
+ 'title', forms.CharField(required=False)
+ )
self.parent = parent
if initial is None:
initial = {} |
84a7b7fd8612121379700498c61e7c292eb8262a | malcolm/controllers/builtin/defaultcontroller.py | malcolm/controllers/builtin/defaultcontroller.py | from malcolm.core import Controller, DefaultStateMachine, Hook, \
method_only_in, method_takes
sm = DefaultStateMachine
@sm.insert
@method_takes()
class DefaultController(Controller):
Resetting = Hook()
Disabling = Hook()
@method_takes()
def disable(self):
try:
self.transition(sm.DISABLING, "Disabling")
self.run_hook(self.Disabling)
self.transition(sm.DISABLED, "Done Disabling")
except Exception as e: # pylint:disable=broad-except
self.log_exception("Fault occurred while Disabling")
self.transition(sm.FAULT, str(e))
raise
@method_only_in(sm.DISABLED, sm.FAULT)
def reset(self):
try:
self.transition(sm.RESETTING, "Resetting")
self.run_hook(self.Resetting)
self.transition(sm.AFTER_RESETTING, "Done Resetting")
except Exception as e: # pylint:disable=broad-except
self.log_exception("Fault occurred while Resetting")
self.transition(sm.FAULT, str(e))
raise | from malcolm.core import Controller, DefaultStateMachine, Hook, \
method_only_in, method_takes
sm = DefaultStateMachine
@sm.insert
@method_takes()
class DefaultController(Controller):
Resetting = Hook()
Disabling = Hook()
@method_takes()
def disable(self):
try:
self.transition(sm.DISABLING, "Disabling")
self.run_hook(self.Disabling, self.create_part_tasks())
self.transition(sm.DISABLED, "Done Disabling")
except Exception as e: # pylint:disable=broad-except
self.log_exception("Fault occurred while Disabling")
self.transition(sm.FAULT, str(e))
raise
@method_only_in(sm.DISABLED, sm.FAULT)
def reset(self):
try:
self.transition(sm.RESETTING, "Resetting")
self.run_hook(self.Resetting, self.create_part_tasks())
self.transition(self.stateMachine.AFTER_RESETTING, "Done Resetting")
except Exception as e: # pylint:disable=broad-except
self.log_exception("Fault occurred while Resetting")
self.transition(sm.FAULT, str(e))
raise
| Make part task creation explicit | Make part task creation explicit
| Python | apache-2.0 | dls-controls/pymalcolm,dls-controls/pymalcolm,dls-controls/pymalcolm | ---
+++
@@ -16,7 +16,7 @@
def disable(self):
try:
self.transition(sm.DISABLING, "Disabling")
- self.run_hook(self.Disabling)
+ self.run_hook(self.Disabling, self.create_part_tasks())
self.transition(sm.DISABLED, "Done Disabling")
except Exception as e: # pylint:disable=broad-except
self.log_exception("Fault occurred while Disabling")
@@ -27,8 +27,8 @@
def reset(self):
try:
self.transition(sm.RESETTING, "Resetting")
- self.run_hook(self.Resetting)
- self.transition(sm.AFTER_RESETTING, "Done Resetting")
+ self.run_hook(self.Resetting, self.create_part_tasks())
+ self.transition(self.stateMachine.AFTER_RESETTING, "Done Resetting")
except Exception as e: # pylint:disable=broad-except
self.log_exception("Fault occurred while Resetting")
self.transition(sm.FAULT, str(e)) |
031fffb277fbf86e8aba3d7509823ee7b3acf873 | seleniumbase/config/proxy_list.py | seleniumbase/config/proxy_list.py | """
Proxy Server "Phone Book".
Simplify running browser tests through a proxy server
by adding your frequently-used proxies here.
Now you can do something like this on the command line:
"pytest SOME_TEST.py --proxy=proxy1"
Format of PROXY_LIST server entries:
* "ip_address:port" OR "username:password@ip_address:port"
* "server:port" OR "username:password@server:port"
(Do NOT include the http:// or https:// in your proxy string!)
Example proxies in PROXY_LIST below are not guaranteed to be active or secure.
If you don't already have a proxy server to connect to,
you can try finding one from one of following sites:
* https://www.us-proxy.org/
"""
PROXY_LIST = {
"example1": "40.114.109.214:3128", # (Example) - set your own proxy here
"proxy1": None,
"proxy2": None,
"proxy3": None,
"proxy4": None,
"proxy5": None,
}
| """
Proxy Server "Phone Book".
Simplify running browser tests through a proxy server
by adding your frequently-used proxies here.
Now you can do something like this on the command line:
"pytest SOME_TEST.py --proxy=proxy1"
Format of PROXY_LIST server entries:
* "ip_address:port" OR "username:password@ip_address:port"
* "server:port" OR "username:password@server:port"
(Do NOT include the http:// or https:// in your proxy string!)
Example proxies in PROXY_LIST below are not guaranteed to be active or secure.
If you don't already have a proxy server to connect to,
you can try finding one from one of following sites:
* https://www.us-proxy.org/
"""
PROXY_LIST = {
"example1": "167.99.151.183:8080", # (Example) - set your own proxy here
"proxy1": None,
"proxy2": None,
"proxy3": None,
"proxy4": None,
"proxy5": None,
}
| Update proxy with a currently-working example | Update proxy with a currently-working example
| Python | mit | mdmintz/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,mdmintz/SeleniumBase | ---
+++
@@ -19,7 +19,7 @@
"""
PROXY_LIST = {
- "example1": "40.114.109.214:3128", # (Example) - set your own proxy here
+ "example1": "167.99.151.183:8080", # (Example) - set your own proxy here
"proxy1": None,
"proxy2": None,
"proxy3": None, |
c02d6bef8a91d436e9c26363f810eb8053ca2a69 | fmn/filters/generic.py | fmn/filters/generic.py | # Generic filters for FMN
def user_filter(config, message, fasnick):
""" Filters the messages by the user that performed the action.
Use this filter to filter out messages that are associated with a
specified user.
"""
print config
return fasnick in fedmsg.meta.msg2usernames(message)
| # Generic filters for FMN
import fedmsg
def user_filter(config, message, fasnick=None, *args, **kw):
""" Filters the messages by the user that performed the action.
Use this filter to filter out messages that are associated with a
specified user.
"""
fasnick = kw.get('fasnick', fasnick)
if fasnick:
return fasnick in fedmsg.meta.msg2usernames(message)
| Fix the user_filter to handle arguments properly | Fix the user_filter to handle arguments properly
fasnick=None is required so that the argument is displayed in the UI
*args, **kw is actually how the arguments are passed to the filter for it to run
This **kw is the actual important bit here. | Python | lgpl-2.1 | jeremycline/fmn,jeremycline/fmn,jeremycline/fmn | ---
+++
@@ -1,11 +1,13 @@
# Generic filters for FMN
+import fedmsg
-def user_filter(config, message, fasnick):
+def user_filter(config, message, fasnick=None, *args, **kw):
""" Filters the messages by the user that performed the action.
Use this filter to filter out messages that are associated with a
specified user.
"""
- print config
- return fasnick in fedmsg.meta.msg2usernames(message)
+ fasnick = kw.get('fasnick', fasnick)
+ if fasnick:
+ return fasnick in fedmsg.meta.msg2usernames(message) |
12fbf40ce5ffaab44c7a602925230e0c2d96b9b0 | cameo/strain_design/heuristic/observers.py | cameo/strain_design/heuristic/observers.py | # Copyright 2014 Novo Nordisk Foundation Center for Biosustainability, DTU.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import, print_function
from cameo.visualization import ProgressBar
class ProgressObserver():
"""
Progress bar to in command line
"""
__name__ = "Progress Observer"
def __init__(self):
self.progress = None
def __call__(self, population, num_generations, num_evaluations, args):
if self.progress is None:
self.max_evaluations = args.get('max_evaluations', 50000)
self.progress = ProgressBar()
self.progress.start()
if num_evaluations % args.get('n', 1) == 0:
if num_evaluations < self.max_evaluations:
self.progress.update(self.max_evaluations)
else:
self.progress.update(num_evaluations)
def reset(self):
self.progress = None
def end(self):
self.progress.end() | # Copyright 2014 Novo Nordisk Foundation Center for Biosustainability, DTU.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import, print_function
from cameo.visualization import ProgressBar
class ProgressObserver():
"""
Progress bar to in command line
"""
__name__ = "Progress Observer"
def __init__(self):
self.progress = None
def __call__(self, population, num_generations, num_evaluations, args):
if self.progress is None:
self.max_evaluations = args.get('max_evaluations', 50000)
self.progress = ProgressBar(self.max_evaluations)
self.progress.start()
if num_evaluations % args.get('n', 1) == 0:
if num_evaluations > self.max_evaluations:
self.progress.update(self.max_evaluations)
else:
self.progress.update(num_evaluations)
def reset(self):
self.progress = None
def end(self):
self.progress.end() | Fix the bug fix. Now is really fixed. | Fix the bug fix. Now is really fixed.
| Python | apache-2.0 | biosustain/cameo,biosustain/cameo,KristianJensen/cameo | ---
+++
@@ -29,11 +29,11 @@
def __call__(self, population, num_generations, num_evaluations, args):
if self.progress is None:
self.max_evaluations = args.get('max_evaluations', 50000)
- self.progress = ProgressBar()
+ self.progress = ProgressBar(self.max_evaluations)
self.progress.start()
if num_evaluations % args.get('n', 1) == 0:
- if num_evaluations < self.max_evaluations:
+ if num_evaluations > self.max_evaluations:
self.progress.update(self.max_evaluations)
else:
self.progress.update(num_evaluations) |
ee30d1f8b268f6a5862de0527bc48dd45f59b9f6 | trackingtermites/utils.py | trackingtermites/utils.py | """Utilitary shared functions."""
boolean_parameters = ['show_labels', 'highlight_collisions',
'show_bounding_box', 'show_frame_info',
'show_d_lines', 'show_trails']
tuple_parameters = ['video_source_size', 'arena_size']
integer_parameters = ['n_termites', 'box_size', 'scale', 'trail_size']
list_parameters = ['filters']
def read_config_file(config_path):
"""Read input file and creates parameters dictionary.
Args:
config_path (str): path to configuration file.
Returns:
parameters (dict): loaded parameters.
"""
parameters = {}
with open(config_path, mode='r', encoding='utf-8') as input_file:
for line in input_file:
if not line[0] == '\n' and not line[0] == '#' and not line[0] == ' ':
param, value = line.strip().split(' ')
if param in tuple_parameters:
width, height = value.strip().split(',')
parameters[param] = tuple([int(width), int(height)])
elif param in list_parameters:
values = []
for field in value.strip().split(','):
if field != 'None':
filters.append(field)
parameters[param] = values
elif param in integer_parameters:
parameters[param] = int(value)
elif param in boolean_parameters:
if value.lower() == 'true':
parameters[param] = True
else:
parameters[param] = False
else:
parameters[param] = value
return parameters
| """Utilitary shared functions."""
boolean_parameters = ['show_labels', 'highlight_collisions',
'show_bounding_box', 'show_frame_info',
'show_d_lines', 'show_trails']
tuple_parameters = ['video_source_size', 'arena_size']
integer_parameters = ['n_termites', 'box_size', 'scale', 'trail_size', 'termite_radius']
list_parameters = ['filters']
def read_config_file(config_path):
"""Read input file and creates parameters dictionary.
Args:
config_path (str): path to configuration file.
Returns:
parameters (dict): loaded parameters.
"""
parameters = {}
with open(config_path, mode='r', encoding='utf-8') as input_file:
for line in input_file:
if not line[0] == '\n' and not line[0] == '#' and not line[0] == ' ':
param, value = line.strip().split(' ')
if param in tuple_parameters:
width, height = value.strip().split(',')
parameters[param] = tuple([int(width), int(height)])
elif param in list_parameters:
values = []
for field in value.strip().split(','):
if field != 'None':
filters.append(field)
parameters[param] = values
elif param in integer_parameters:
parameters[param] = int(value)
elif param in boolean_parameters:
if value.lower() == 'true':
parameters[param] = True
else:
parameters[param] = False
else:
parameters[param] = value
return parameters
| Add termite radius to integer parameters | Add termite radius to integer parameters
| Python | mit | dmrib/trackingtermites | ---
+++
@@ -6,7 +6,7 @@
tuple_parameters = ['video_source_size', 'arena_size']
-integer_parameters = ['n_termites', 'box_size', 'scale', 'trail_size']
+integer_parameters = ['n_termites', 'box_size', 'scale', 'trail_size', 'termite_radius']
list_parameters = ['filters']
|
7bdcf639f19c2f1960bd46f7400b8010c5da1de8 | rasterio/rio/main.py | rasterio/rio/main.py | # main: loader of all the command entry points.
import sys
import traceback
from click.formatting import HelpFormatter
from pkg_resources import iter_entry_points
from rasterio.rio.cli import BrokenCommand, cli
# Find and load all entry points in the rasterio.rio_commands group.
# This includes the standard commands included with Rasterio as well
# as commands provided by other packages.
#
# At a mimimum, commands must use the rasterio.rio.cli.cli command
# group decorator like so:
#
# from rasterio.rio.cli import cli
#
# @cli.command()
# def foo(...):
# ...
for entry_point in iter_entry_points('rasterio.rio_commands'):
try:
entry_point.load()
except Exception:
# Catch this so a busted plugin doesn't take down the CLI.
# Handled by registering a dummy command that does nothing
# other than explain the error.
cli.add_command(
BrokenCommand(entry_point.name))
| # main: loader of all the command entry points.
import sys
import traceback
from pkg_resources import iter_entry_points
from rasterio.rio.cli import BrokenCommand, cli
# Find and load all entry points in the rasterio.rio_commands group.
# This includes the standard commands included with Rasterio as well
# as commands provided by other packages.
#
# At a mimimum, commands must use the rasterio.rio.cli.cli command
# group decorator like so:
#
# from rasterio.rio.cli import cli
#
# @cli.command()
# def foo(...):
# ...
for entry_point in iter_entry_points('rasterio.rio_commands'):
try:
entry_point.load()
except Exception:
# Catch this so a busted plugin doesn't take down the CLI.
# Handled by registering a dummy command that does nothing
# other than explain the error.
cli.add_command(
BrokenCommand(entry_point.name))
| Remove unneeded import of HelpFormatter. | Remove unneeded import of HelpFormatter.
| Python | bsd-3-clause | brendan-ward/rasterio,perrygeo/rasterio,clembou/rasterio,perrygeo/rasterio,njwilson23/rasterio,johanvdw/rasterio,njwilson23/rasterio,clembou/rasterio,brendan-ward/rasterio,clembou/rasterio,kapadia/rasterio,perrygeo/rasterio,brendan-ward/rasterio,kapadia/rasterio,njwilson23/rasterio,johanvdw/rasterio,kapadia/rasterio,youngpm/rasterio,youngpm/rasterio,youngpm/rasterio,johanvdw/rasterio | ---
+++
@@ -3,7 +3,6 @@
import sys
import traceback
-from click.formatting import HelpFormatter
from pkg_resources import iter_entry_points
from rasterio.rio.cli import BrokenCommand, cli |
fa0513fe303a0111291d459d3bf275229b1eb052 | main.py | main.py | import datetime
import argparse
from auth import twitter_auth as auth
from twitterbot import TwitterBot
from apscheduler.schedulers.blocking import BlockingScheduler
parser = argparse.ArgumentParser(description='Respond to Twitter mentions.')
parser.add_argument('-l', '--listen', nargs='+', default='happy birthday',
help='phrase(s) to reply to (separate by space)')
parser.add_argument('-r', '--reply', default='HANDLE thanks!',
help='reply text (use HANDLE for user handle)')
args = parser.parse_args()
bot = TwitterBot(auth, args.listen, args.reply.replace('HANDLE', '@{}'))
def reply():
print(' Running...')
bot.reply_to_mention()
print(' Finished running at {}'.format(datetime.datetime.now()))
def main():
print('Starting bot...')
# run once every minute
scheduler = BlockingScheduler()
scheduler.add_job(reply, 'interval', minutes=1)
scheduler.start()
if __name__ == '__main__':
main()
| import sys
import datetime
import argparse
from auth import twitter_auth as auth
from twitterbot import TwitterBot
from apscheduler.schedulers.blocking import BlockingScheduler
parser = argparse.ArgumentParser(description='Respond to Twitter mentions.')
parser.add_argument('-l', '--listen', nargs='+', default=['happy birthday'],
help='phrase(s) to reply to (separate by space)')
parser.add_argument('-r', '--reply', default='HANDLE thanks!',
help='reply text (use HANDLE for user handle)')
args = parser.parse_args()
bot = TwitterBot(auth, args.listen, args.reply.replace('HANDLE', '@{}'))
def reply():
print(' Running...')
bot.reply_to_mention()
print(' Finished running at {}'.format(datetime.datetime.now()))
def main():
print('Starting bot...')
# run once every minute
scheduler = BlockingScheduler()
scheduler.add_job(reply, 'interval', minutes=1)
scheduler.start()
if __name__ == '__main__':
main()
| Change default type for listen argument | Change default type for listen argument
str->list
| Python | mit | kshvmdn/TwitterBirthdayResponder,kshvmdn/twitter-birthday-responder,kshvmdn/twitter-autoreply | ---
+++
@@ -1,3 +1,4 @@
+import sys
import datetime
import argparse
@@ -6,7 +7,7 @@
from apscheduler.schedulers.blocking import BlockingScheduler
parser = argparse.ArgumentParser(description='Respond to Twitter mentions.')
-parser.add_argument('-l', '--listen', nargs='+', default='happy birthday',
+parser.add_argument('-l', '--listen', nargs='+', default=['happy birthday'],
help='phrase(s) to reply to (separate by space)')
parser.add_argument('-r', '--reply', default='HANDLE thanks!',
help='reply text (use HANDLE for user handle)') |
93d6b5e33747169a102629015a63c1d4006cf81e | srsly/about.py | srsly/about.py | __title__ = "srsly"
__version__ = "0.0.4"
__summary__ = "Modern high-performance serialization utilities for Python"
__uri__ = "https://explosion.ai"
__author__ = "Explosion AI"
__email__ = "contact@explosion.ai"
__license__ = "MIT"
| __title__ = "srsly"
__version__ = "0.0.3"
__summary__ = "Modern high-performance serialization utilities for Python"
__uri__ = "https://explosion.ai"
__author__ = "Explosion AI"
__email__ = "contact@explosion.ai"
__license__ = "MIT"
| Revert "Set version to v0.0.4" | Revert "Set version to v0.0.4"
This reverts commit 5d4bfd8e92db765cdf4d7f8948b2293ca73aa245.
| Python | mit | explosion/srsly,explosion/srsly,explosion/srsly,explosion/srsly | ---
+++
@@ -1,5 +1,5 @@
__title__ = "srsly"
-__version__ = "0.0.4"
+__version__ = "0.0.3"
__summary__ = "Modern high-performance serialization utilities for Python"
__uri__ = "https://explosion.ai"
__author__ = "Explosion AI" |
6113788729b6e5c1df44b793f63a7e95caeeb860 | main.py | main.py | from flask import Flask, request, send_file
import json
from src.generate import generate
app = Flask(__name__)
available_settings = ['grammarTitle', 'grammarSubtitle', 'author', 'format',
'theme']
@app.route('/', methods=['POST'])
def index():
# Get all available string settings from posted object
settings = {}
for key in available_settings:
settings[key] = request.form.get(key, None)
# Loop through the files posted to the endpoint, reading all
# files as strings.
markdown_file_strings = []
lexicon_file_string = None
for filename, blob in request.files.items():
if filename.endswith('.csv'):
lexicon_file_string = str(blob.read(), 'utf-8')
else:
markdown_file_strings.append(str(blob.read(), 'utf-8'))
print(markdown_file_strings)
filename = generate(markdown_file_strings, lexicon_file_string, settings)
return filename
@app.route('/download')
def download():
filename = request.args.get('filename')
return send_file(filename)
if __name__ == '__main__':
app.run(debug=True)
| from flask import Flask, request, send_file
import json
from src.generate import generate
app = Flask(__name__)
available_settings = ['grammarTitle', 'grammarSubtitle', 'author', 'format',
'theme']
@app.route('/', methods=['POST'])
def index():
# Get all available string settings from posted object
settings = {}
for key in available_settings:
settings[key] = request.form.get(key, None)
# Loop through the files posted to the endpoint, reading all
# files as strings.
markdown_file_strings = []
lexicon_file_string = None
for filename, blob in request.files.items():
if filename.endswith('.csv'):
lexicon_file_string = str(blob.read(), 'utf-8')
else:
markdown_file_strings.append(str(blob.read(), 'utf-8'))
print(markdown_file_strings)
filename = generate(markdown_file_strings, lexicon_file_string, settings)
return filename
@app.route('/download')
def download():
filename = request.args.get('filename')
print('Received request with filename {0}'.format(filename))
if filename.endswith('.md'):
mimetype = 'text/markdown'
return send_file(filename, mimetype=mimetype)
if __name__ == '__main__':
app.run(debug=True)
| Return file with correct mimetype | Return file with correct mimetype
| Python | mit | kdelwat/Coda,kdelwat/Coda | ---
+++
@@ -35,7 +35,12 @@
@app.route('/download')
def download():
filename = request.args.get('filename')
- return send_file(filename)
+ print('Received request with filename {0}'.format(filename))
+
+ if filename.endswith('.md'):
+ mimetype = 'text/markdown'
+
+ return send_file(filename, mimetype=mimetype)
if __name__ == '__main__': |
0774eea1027bc9bb88b5289854aa26109f258712 | great_expectations/exceptions.py | great_expectations/exceptions.py | class GreatExpectationsError(Exception):
pass
class ExpectationsConfigNotFoundError(GreatExpectationsError):
def __init__(self, data_asset_name):
self.data_asset_name = data_asset_name
self.message = "No expectations config found for data_asset_name %s" % data_asset_name
class BatchKwargsError(GreatExpectationsError):
def __init__(self, message, batch_kwargs):
self.message = message | class GreatExpectationsError(Exception):
pass
class ExpectationsConfigNotFoundError(GreatExpectationsError):
def __init__(self, data_asset_name):
self.data_asset_name = data_asset_name
self.message = "No expectations config found for data_asset_name %s" % data_asset_name
class BatchKwargsError(GreatExpectationsError):
def __init__(self, message, batch_kwargs):
self.message = message
self.batch_kwargs = batch_kwargs | Add batch_kwargs to custom error | Add batch_kwargs to custom error
| Python | apache-2.0 | great-expectations/great_expectations,great-expectations/great_expectations,great-expectations/great_expectations,great-expectations/great_expectations | ---
+++
@@ -11,3 +11,4 @@
class BatchKwargsError(GreatExpectationsError):
def __init__(self, message, batch_kwargs):
self.message = message
+ self.batch_kwargs = batch_kwargs |
30470437a86a58e5d89167f24206227737a04cf8 | src/integration_tests/test_validation.py | src/integration_tests/test_validation.py | import pytest
from tests import base
from buildercore import cfngen, project
import logging
LOG = logging.getLogger(__name__)
logging.disable(logging.NOTSET) # re-enables logging during integration testing
# Depends on talking to AWS.
class TestValidationFixtures(base.BaseCase):
def test_validation(self):
"dummy projects and their alternative configurations pass validation"
for pname in project.aws_projects().keys():
cfngen.validate_project(pname)
class TestValidationElife():
def setUp(self):
# HERE BE DRAGONS
# resets the testing config.SETTINGS_FILE we set in the base.BaseCase class
base.switch_out_test_settings()
def tearDown(self):
base.switch_in_test_settings()
@pytest.mark.parametrize("project_name", project.aws_projects().keys())
def test_validation_elife_projects(self, project_name, filter_project_name):
"elife projects (and their alternative configurations) that come with the builder pass validation"
if filter_project_name:
if project_name != filter_project_name:
pytest.skip("Filtered out through filter_project_name")
cfngen.validate_project(project_name)
| import pytest
from tests import base
from buildercore import cfngen, project
import logging
LOG = logging.getLogger(__name__)
logging.disable(logging.NOTSET) # re-enables logging during integration testing
# Depends on talking to AWS.
class TestValidationFixtures(base.BaseCase):
def test_validation(self):
"dummy projects and their alternative configurations pass validation"
for pname in project.aws_projects().keys():
cfngen.validate_project(pname)
class TestValidationElife():
@classmethod
def setup_class(cls):
# HERE BE DRAGONS
# resets the testing config.SETTINGS_FILE we set in the base.BaseCase class
base.switch_out_test_settings()
@classmethod
def teardown_class(cls):
base.switch_in_test_settings()
@pytest.mark.parametrize("project_name", project.aws_projects().keys())
def test_validation_elife_projects(self, project_name, filter_project_name):
"elife projects (and their alternative configurations) that come with the builder pass validation"
if filter_project_name:
if project_name != filter_project_name:
pytest.skip("Filtered out through filter_project_name")
cfngen.validate_project(project_name)
| Correct pytest setup and teardown | Correct pytest setup and teardown
| Python | mit | elifesciences/builder,elifesciences/builder | ---
+++
@@ -15,12 +15,14 @@
cfngen.validate_project(pname)
class TestValidationElife():
- def setUp(self):
+ @classmethod
+ def setup_class(cls):
# HERE BE DRAGONS
# resets the testing config.SETTINGS_FILE we set in the base.BaseCase class
base.switch_out_test_settings()
- def tearDown(self):
+ @classmethod
+ def teardown_class(cls):
base.switch_in_test_settings()
@pytest.mark.parametrize("project_name", project.aws_projects().keys()) |
a0dd71a6b56ed8f88f29691edd7a65d84656e019 | anki-blitz.py | anki-blitz.py | # -*- coding: utf-8 -*-
# Blitz speed reading trainer add-on for Anki
#
# Copyright (C) 2016 Jakub Szypulka, Dave Shifflett
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from anki.hooks import addHook
from aqt.reviewer import Reviewer
import time
start_time = None
def onShowQuestion():
global start_time
start_time = time.time()
addHook('showQuestion', onShowQuestion)
def myDefaultEase(self):
elapsed_time = time.time() - start_time
if elapsed_time < 1:
return 3
if elapsed_time < 3:
return 2
else:
return 1
Reviewer._defaultEase = myDefaultEase
| # -*- coding: utf-8 -*-
# Blitz speed reading trainer add-on for Anki
#
# Copyright (C) 2016 Jakub Szypulka, Dave Shifflett
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from anki.hooks import addHook
from aqt.reviewer import Reviewer
import time
start_time = None
def onShowQuestion():
global start_time
start_time = time.time()
addHook('showQuestion', onShowQuestion)
def myDefaultEase(self):
elapsed_time = time.time() - start_time
if elapsed_time < 2:
return 3
if elapsed_time < 5:
return 2
else:
return 1
Reviewer._defaultEase = myDefaultEase
| Increase time limits to 2 and 5 seconds | Increase time limits to 2 and 5 seconds
| Python | mit | jaksz/anki-blitz | ---
+++
@@ -32,9 +32,9 @@
def myDefaultEase(self):
elapsed_time = time.time() - start_time
- if elapsed_time < 1:
+ if elapsed_time < 2:
return 3
- if elapsed_time < 3:
+ if elapsed_time < 5:
return 2
else:
return 1 |
760ce74fca8fa9a640167eabb4af83e31e902500 | openedx/core/djangoapps/api_admin/utils.py | openedx/core/djangoapps/api_admin/utils.py | """ Course Discovery API Service. """
from django.conf import settings
from edx_rest_api_client.client import EdxRestApiClient
from openedx.core.djangoapps.theming import helpers
from openedx.core.lib.token_utils import get_id_token
from provider.oauth2.models import Client
CLIENT_NAME = 'course-discovery'
def course_discovery_api_client(user):
""" Returns a Course Discovery API client setup with authentication for the specified user. """
course_discovery_client = Client.objects.get(name=CLIENT_NAME)
secret_key = helpers.get_value('JWT_AUTH', settings.JWT_AUTH)['JWT_SECRET_KEY']
return EdxRestApiClient(
course_discovery_client.url,
jwt=get_id_token(user, CLIENT_NAME, secret_key=secret_key)
)
| """ Course Discovery API Service. """
import datetime
from django.conf import settings
from edx_rest_api_client.client import EdxRestApiClient
import jwt
from openedx.core.djangoapps.theming import helpers
from provider.oauth2.models import Client
from student.models import UserProfile, anonymous_id_for_user
CLIENT_NAME = 'course-discovery'
def get_id_token(user):
"""
Return a JWT for `user`, suitable for use with the course discovery service.
Arguments:
user (User): User for whom to generate the JWT.
Returns:
str: The JWT.
"""
try:
# Service users may not have user profiles.
full_name = UserProfile.objects.get(user=user).name
except UserProfile.DoesNotExist:
full_name = None
now = datetime.datetime.utcnow()
expires_in = getattr(settings, 'OAUTH_ID_TOKEN_EXPIRATION', 30)
payload = {
'preferred_username': user.username,
'name': full_name,
'email': user.email,
'administrator': user.is_staff,
'iss': helpers.get_value('OAUTH_OIDC_ISSUER', settings.OAUTH_OIDC_ISSUER),
'exp': now + datetime.timedelta(seconds=expires_in),
'iat': now,
'aud': helpers.get_value('JWT_AUTH', settings.JWT_AUTH)['JWT_AUDIENCE'],
'sub': anonymous_id_for_user(user, None),
}
secret_key = helpers.get_value('JWT_AUTH', settings.JWT_AUTH)['JWT_SECRET_KEY']
return jwt.encode(payload, secret_key)
def course_discovery_api_client(user):
""" Returns a Course Discovery API client setup with authentication for the specified user. """
course_discovery_client = Client.objects.get(name=CLIENT_NAME)
return EdxRestApiClient(course_discovery_client.url, jwt=get_id_token(user))
| Use correct JWT audience when connecting to course discovery. | Use correct JWT audience when connecting to course discovery.
| Python | agpl-3.0 | cecep-edu/edx-platform,ahmedaljazzar/edx-platform,fintech-circle/edx-platform,waheedahmed/edx-platform,proversity-org/edx-platform,pabloborrego93/edx-platform,mbareta/edx-platform-ft,ESOedX/edx-platform,longmen21/edx-platform,pepeportela/edx-platform,chrisndodge/edx-platform,procangroup/edx-platform,ampax/edx-platform,fintech-circle/edx-platform,Stanford-Online/edx-platform,proversity-org/edx-platform,EDUlib/edx-platform,Edraak/edraak-platform,eduNEXT/edx-platform,eduNEXT/edx-platform,BehavioralInsightsTeam/edx-platform,JioEducation/edx-platform,stvstnfrd/edx-platform,gsehub/edx-platform,mitocw/edx-platform,proversity-org/edx-platform,chrisndodge/edx-platform,mitocw/edx-platform,lduarte1991/edx-platform,jzoldak/edx-platform,mitocw/edx-platform,waheedahmed/edx-platform,prarthitm/edxplatform,Livit/Livit.Learn.EdX,amir-qayyum-khan/edx-platform,CredoReference/edx-platform,appsembler/edx-platform,jjmiranda/edx-platform,amir-qayyum-khan/edx-platform,msegado/edx-platform,gymnasium/edx-platform,mbareta/edx-platform-ft,pepeportela/edx-platform,kmoocdev2/edx-platform,kmoocdev2/edx-platform,angelapper/edx-platform,eduNEXT/edx-platform,ahmedaljazzar/edx-platform,romain-li/edx-platform,philanthropy-u/edx-platform,ahmedaljazzar/edx-platform,Lektorium-LLC/edx-platform,angelapper/edx-platform,arbrandes/edx-platform,edx-solutions/edx-platform,jolyonb/edx-platform,caesar2164/edx-platform,deepsrijit1105/edx-platform,ampax/edx-platform,arbrandes/edx-platform,philanthropy-u/edx-platform,ESOedX/edx-platform,TeachAtTUM/edx-platform,cecep-edu/edx-platform,longmen21/edx-platform,romain-li/edx-platform,raccoongang/edx-platform,a-parhom/edx-platform,procangroup/edx-platform,kmoocdev2/edx-platform,shabab12/edx-platform,pepeportela/edx-platform,TeachAtTUM/edx-platform,jzoldak/edx-platform,proversity-org/edx-platform,jolyonb/edx-platform,appsembler/edx-platform,teltek/edx-platform,caesar2164/edx-platform,ahmedaljazzar/edx-platform,JioEducation/edx-platform,pabloborrego93/edx-platform,Stanford-Online/edx-platform,chrisndodge/edx-platform,mbareta/edx-platform-ft,Edraak/edraak-platform,lduarte1991/edx-platform,cpennington/edx-platform,lduarte1991/edx-platform,deepsrijit1105/edx-platform,deepsrijit1105/edx-platform,Edraak/edraak-platform,procangroup/edx-platform,shabab12/edx-platform,Edraak/edraak-platform,CredoReference/edx-platform,stvstnfrd/edx-platform,longmen21/edx-platform,itsjeyd/edx-platform,naresh21/synergetics-edx-platform,eduNEXT/edunext-platform,gymnasium/edx-platform,louyihua/edx-platform,msegado/edx-platform,louyihua/edx-platform,prarthitm/edxplatform,jjmiranda/edx-platform,msegado/edx-platform,TeachAtTUM/edx-platform,Lektorium-LLC/edx-platform,pabloborrego93/edx-platform,synergeticsedx/deployment-wipro,arbrandes/edx-platform,marcore/edx-platform,naresh21/synergetics-edx-platform,chrisndodge/edx-platform,marcore/edx-platform,louyihua/edx-platform,gymnasium/edx-platform,procangroup/edx-platform,gsehub/edx-platform,amir-qayyum-khan/edx-platform,kmoocdev2/edx-platform,marcore/edx-platform,marcore/edx-platform,eduNEXT/edunext-platform,a-parhom/edx-platform,ESOedX/edx-platform,stvstnfrd/edx-platform,Stanford-Online/edx-platform,BehavioralInsightsTeam/edx-platform,JioEducation/edx-platform,fintech-circle/edx-platform,synergeticsedx/deployment-wipro,msegado/edx-platform,edx/edx-platform,cpennington/edx-platform,TeachAtTUM/edx-platform,longmen21/edx-platform,Stanford-Online/edx-platform,Livit/Livit.Learn.EdX,philanthropy-u/edx-platform,miptliot/edx-platform,raccoongang/edx-platform,EDUlib/edx-platform,synergeticsedx/deployment-wipro,a-parhom/edx-platform,BehavioralInsightsTeam/edx-platform,mbareta/edx-platform-ft,hastexo/edx-platform,jolyonb/edx-platform,Livit/Livit.Learn.EdX,Livit/Livit.Learn.EdX,teltek/edx-platform,kmoocdev2/edx-platform,eduNEXT/edunext-platform,jjmiranda/edx-platform,edx/edx-platform,gymnasium/edx-platform,jolyonb/edx-platform,teltek/edx-platform,waheedahmed/edx-platform,ampax/edx-platform,EDUlib/edx-platform,deepsrijit1105/edx-platform,tanmaykm/edx-platform,Lektorium-LLC/edx-platform,tanmaykm/edx-platform,eduNEXT/edx-platform,philanthropy-u/edx-platform,cpennington/edx-platform,cecep-edu/edx-platform,amir-qayyum-khan/edx-platform,edx-solutions/edx-platform,edx-solutions/edx-platform,cecep-edu/edx-platform,cpennington/edx-platform,CredoReference/edx-platform,romain-li/edx-platform,romain-li/edx-platform,angelapper/edx-platform,edx/edx-platform,eduNEXT/edunext-platform,lduarte1991/edx-platform,waheedahmed/edx-platform,appsembler/edx-platform,miptliot/edx-platform,appsembler/edx-platform,itsjeyd/edx-platform,jzoldak/edx-platform,jjmiranda/edx-platform,pepeportela/edx-platform,ampax/edx-platform,gsehub/edx-platform,pabloborrego93/edx-platform,hastexo/edx-platform,tanmaykm/edx-platform,angelapper/edx-platform,gsehub/edx-platform,teltek/edx-platform,EDUlib/edx-platform,CredoReference/edx-platform,naresh21/synergetics-edx-platform,tanmaykm/edx-platform,arbrandes/edx-platform,hastexo/edx-platform,raccoongang/edx-platform,itsjeyd/edx-platform,raccoongang/edx-platform,Lektorium-LLC/edx-platform,synergeticsedx/deployment-wipro,cecep-edu/edx-platform,shabab12/edx-platform,fintech-circle/edx-platform,edx/edx-platform,naresh21/synergetics-edx-platform,waheedahmed/edx-platform,mitocw/edx-platform,louyihua/edx-platform,prarthitm/edxplatform,romain-li/edx-platform,caesar2164/edx-platform,msegado/edx-platform,caesar2164/edx-platform,miptliot/edx-platform,JioEducation/edx-platform,miptliot/edx-platform,shabab12/edx-platform,hastexo/edx-platform,itsjeyd/edx-platform,stvstnfrd/edx-platform,a-parhom/edx-platform,BehavioralInsightsTeam/edx-platform,ESOedX/edx-platform,longmen21/edx-platform,prarthitm/edxplatform,edx-solutions/edx-platform,jzoldak/edx-platform | ---
+++
@@ -1,19 +1,53 @@
""" Course Discovery API Service. """
+import datetime
+
from django.conf import settings
+from edx_rest_api_client.client import EdxRestApiClient
+import jwt
-from edx_rest_api_client.client import EdxRestApiClient
from openedx.core.djangoapps.theming import helpers
-from openedx.core.lib.token_utils import get_id_token
from provider.oauth2.models import Client
+from student.models import UserProfile, anonymous_id_for_user
CLIENT_NAME = 'course-discovery'
+
+
+def get_id_token(user):
+ """
+ Return a JWT for `user`, suitable for use with the course discovery service.
+
+ Arguments:
+ user (User): User for whom to generate the JWT.
+
+ Returns:
+ str: The JWT.
+ """
+ try:
+ # Service users may not have user profiles.
+ full_name = UserProfile.objects.get(user=user).name
+ except UserProfile.DoesNotExist:
+ full_name = None
+
+ now = datetime.datetime.utcnow()
+ expires_in = getattr(settings, 'OAUTH_ID_TOKEN_EXPIRATION', 30)
+
+ payload = {
+ 'preferred_username': user.username,
+ 'name': full_name,
+ 'email': user.email,
+ 'administrator': user.is_staff,
+ 'iss': helpers.get_value('OAUTH_OIDC_ISSUER', settings.OAUTH_OIDC_ISSUER),
+ 'exp': now + datetime.timedelta(seconds=expires_in),
+ 'iat': now,
+ 'aud': helpers.get_value('JWT_AUTH', settings.JWT_AUTH)['JWT_AUDIENCE'],
+ 'sub': anonymous_id_for_user(user, None),
+ }
+ secret_key = helpers.get_value('JWT_AUTH', settings.JWT_AUTH)['JWT_SECRET_KEY']
+
+ return jwt.encode(payload, secret_key)
def course_discovery_api_client(user):
""" Returns a Course Discovery API client setup with authentication for the specified user. """
course_discovery_client = Client.objects.get(name=CLIENT_NAME)
- secret_key = helpers.get_value('JWT_AUTH', settings.JWT_AUTH)['JWT_SECRET_KEY']
- return EdxRestApiClient(
- course_discovery_client.url,
- jwt=get_id_token(user, CLIENT_NAME, secret_key=secret_key)
- )
+ return EdxRestApiClient(course_discovery_client.url, jwt=get_id_token(user)) |
8f2ca07286bd0950e17c410fc27297775934ba21 | vispy/visuals/graphs/layouts/circular.py | vispy/visuals/graphs/layouts/circular.py | # -*- coding: utf-8 -*-
# Copyright (c) 2015, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
"""
Circular Layout
===============
This module contains several graph layouts which rely heavily on circles.
"""
import numpy as np
from ..util import straight_line_vertices
def circular(adjacency_mat, directed=False):
"""Places all nodes on a single circle.
Parameters
----------
adjacency_mat : matrix
The graph adjacency matrix
Yields
------
(node_vertices, line_vertices, arrow_vertices) : tuple
Yields the node and line vertices in a tuple. This layout only yields a
single time, and has no builtin animation
"""
if adjacency_mat.shape[0] != adjacency_mat.shape[1]:
raise ValueError("Adjacency matrix should be square.")
num_nodes = adjacency_mat.shape[0]
t = np.arange(0, 2.0*np.pi, 2.0*np.pi/num_nodes, dtype=np.float32)
# Visual coordinate system is between 0 and 1, so generate a circle with
# radius 0.5 and center it at the point (0.5, 0.5).
node_coords = np.transpose(0.5 * np.array([np.cos(t), np.sin(t)]) + 0.5)
line_vertices, arrows = straight_line_vertices(adjacency_mat,
node_coords, directed)
yield node_coords, line_vertices, arrows
| # -*- coding: utf-8 -*-
# Copyright (c) 2015, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
"""
Circular Layout
===============
This module contains several graph layouts which rely heavily on circles.
"""
import numpy as np
from ..util import straight_line_vertices
def circular(adjacency_mat, directed=False):
"""Places all nodes on a single circle.
Parameters
----------
adjacency_mat : matrix
The graph adjacency matrix
Yields
------
(node_vertices, line_vertices, arrow_vertices) : tuple
Yields the node and line vertices in a tuple. This layout only yields a
single time, and has no builtin animation
"""
if adjacency_mat.shape[0] != adjacency_mat.shape[1]:
raise ValueError("Adjacency matrix should be square.")
num_nodes = adjacency_mat.shape[0]
t = np.arange(0, 2.0*np.pi, 2.0*np.pi/num_nodes, dtype=np.float32)
# Visual coordinate system is between 0 and 1, so generate a circle with
# radius 0.5 and center it at the point (0.5, 0.5).
node_coords = (0.5 * np.array([np.cos(t), np.sin(t)]) + 0.5).T
line_vertices, arrows = straight_line_vertices(adjacency_mat,
node_coords, directed)
yield node_coords, line_vertices, arrows
| Use T attribute to get transpose | Use T attribute to get transpose
| Python | bsd-3-clause | drufat/vispy,michaelaye/vispy,drufat/vispy,ghisvail/vispy,Eric89GXL/vispy,Eric89GXL/vispy,ghisvail/vispy,michaelaye/vispy,Eric89GXL/vispy,michaelaye/vispy,drufat/vispy,ghisvail/vispy | ---
+++
@@ -37,7 +37,7 @@
# Visual coordinate system is between 0 and 1, so generate a circle with
# radius 0.5 and center it at the point (0.5, 0.5).
- node_coords = np.transpose(0.5 * np.array([np.cos(t), np.sin(t)]) + 0.5)
+ node_coords = (0.5 * np.array([np.cos(t), np.sin(t)]) + 0.5).T
line_vertices, arrows = straight_line_vertices(adjacency_mat,
node_coords, directed) |
bf7dd8bb6ff3e4a8f6412122ca23829c35554082 | contrib/examples/sensors/echo_flask_app.py | contrib/examples/sensors/echo_flask_app.py | from flask import request, Flask
from st2reactor.sensor.base import Sensor
class EchoFlaskSensor(Sensor):
def __init__(self, sensor_service, config):
super(EchoFlaskSensor, self).__init__(
sensor_service=sensor_service,
config=config
)
self._host = '127.0.0.1'
self._port = '5000'
self._path = '/echo'
self._log = self._sensor_service.get_logger(__name__)
self._app = Flask(__name__)
def setup(self):
pass
def run(self):
@self._app.route(self._path, methods=['POST'])
def echo():
payload = request.get_json(force=True)
self._sensor_service.dispatch(trigger="examples.echo_flask",
payload=payload)
return request.data
self._log.info('Listening for payload on http://%s:%s%s' %
(self._host, self._port, self._path))
self._app.run(host=self._host, port=self._port, threaded=True)
def cleanup(self):
pass
def add_trigger(self, trigger):
# This method is called when trigger is created
pass
def update_trigger(self, trigger):
# This method is called when trigger is updated
pass
def remove_trigger(self, trigger):
# This method is called when trigger is deleted
pass
| from flask import request, Flask
from st2reactor.sensor.base import Sensor
class EchoFlaskSensor(Sensor):
def __init__(self, sensor_service, config):
super(EchoFlaskSensor, self).__init__(
sensor_service=sensor_service,
config=config
)
self._host = '127.0.0.1'
self._port = 5000
self._path = '/echo'
self._log = self._sensor_service.get_logger(__name__)
self._app = Flask(__name__)
def setup(self):
pass
def run(self):
@self._app.route(self._path, methods=['POST'])
def echo():
payload = request.get_json(force=True)
self._sensor_service.dispatch(trigger="examples.echo_flask",
payload=payload)
return request.data
self._log.info('Listening for payload on http://{}:{}{}'.format(
self._host, self._port, self._path))
self._app.run(host=self._host, port=self._port, threaded=True)
def cleanup(self):
pass
def add_trigger(self, trigger):
# This method is called when trigger is created
pass
def update_trigger(self, trigger):
# This method is called when trigger is updated
pass
def remove_trigger(self, trigger):
# This method is called when trigger is deleted
pass
| Update the port to be an integer. | Update the port to be an integer.
Fix the port to be an integer. Use the format function for string formatting. | Python | apache-2.0 | StackStorm/st2,StackStorm/st2,nzlosh/st2,StackStorm/st2,StackStorm/st2,Plexxi/st2,nzlosh/st2,Plexxi/st2,Plexxi/st2,nzlosh/st2,nzlosh/st2,Plexxi/st2 | ---
+++
@@ -4,7 +4,6 @@
class EchoFlaskSensor(Sensor):
-
def __init__(self, sensor_service, config):
super(EchoFlaskSensor, self).__init__(
sensor_service=sensor_service,
@@ -12,7 +11,7 @@
)
self._host = '127.0.0.1'
- self._port = '5000'
+ self._port = 5000
self._path = '/echo'
self._log = self._sensor_service.get_logger(__name__)
@@ -29,8 +28,8 @@
payload=payload)
return request.data
- self._log.info('Listening for payload on http://%s:%s%s' %
- (self._host, self._port, self._path))
+ self._log.info('Listening for payload on http://{}:{}{}'.format(
+ self._host, self._port, self._path))
self._app.run(host=self._host, port=self._port, threaded=True)
def cleanup(self): |
55b878bae84fea91bf210e3b30a726877990732e | config.py | config.py | # -*- coding: utf-8 -*-
import os
#
# This is the configuration file of the application
#
# Please make sure you don't store here any secret information and use environment
# variables
#
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL')
SENDGRID_USERNAME = os.environ.get('SENDGRID_USERNAME')
SENDGRID_PASSWORD = os.environ.get('SENDGRID_PASSWORD')
SQLALCHEMY_POOL_RECYCLE = 60
SECRET_KEY = 'aiosdjsaodjoidjioewnioewfnoeijfoisdjf'
# available languages
LANGUAGES = {
'en': 'English',
'he': 'עברית',
} | # -*- coding: utf-8 -*-
import os
#
# This is the configuration file of the application
#
# Please make sure you don't store here any secret information and use environment
# variables
#
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL')
SQLALCHEMY_TRACK_MODIFICATIONS = True
SENDGRID_USERNAME = os.environ.get('SENDGRID_USERNAME')
SENDGRID_PASSWORD = os.environ.get('SENDGRID_PASSWORD')
SQLALCHEMY_POOL_RECYCLE = 60
SECRET_KEY = 'aiosdjsaodjoidjioewnioewfnoeijfoisdjf'
# available languages
LANGUAGES = {
'en': 'English',
'he': 'עברית',
}
| Set SQLALCHEMY_TRACK_MODIFICATIONS = True to avoid warnings | Set SQLALCHEMY_TRACK_MODIFICATIONS = True to avoid warnings
| Python | bsd-3-clause | boazin/anyway,yosinv/anyway,hasadna/anyway,yosinv/anyway,hasadna/anyway,boazin/anyway,hasadna/anyway,hasadna/anyway,boazin/anyway,yosinv/anyway | ---
+++
@@ -10,6 +10,7 @@
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL')
+SQLALCHEMY_TRACK_MODIFICATIONS = True
SENDGRID_USERNAME = os.environ.get('SENDGRID_USERNAME')
SENDGRID_PASSWORD = os.environ.get('SENDGRID_PASSWORD')
SQLALCHEMY_POOL_RECYCLE = 60 |
aa5d4e965868d139f32a3d143725e6fe674f95f9 | config.py | config.py | import argparse
import sys
class TerseHelpFormatter(argparse.HelpFormatter):
def _format_action_invocation(self, action):
if not action.option_strings or action.nargs == 0:
super()._format_action_invocation(action)
default = self._get_default_metavar_for_optional(action)
args_string = self._format_args(action, default)
return '{} {}'.format(', '.join(action.option_strings), args_string)
output_formats = ('text', 'wiki', 'json')
def parse_args():
parser = argparse.ArgumentParser(formatter_class=TerseHelpFormatter)
parser.add_argument('files', metavar='FILE', nargs='+', help='ROMs, discs, etc.')
parser.add_argument('-x', '--extract', action='store_true', help='extract files from disc data tracks')
parser.add_argument('-f', '--format', action='store', default='text', choices=output_formats, metavar='FORMAT',
help='use output format: text (default), wiki, json', dest='output_format')
parser.add_argument('--skip-sector-errors', action='store_true', help='skip sector error checks') # TODO temporary
current_module = sys.modules[__name__]
parser.parse_args(namespace=current_module)
| import argparse
import sys
class TerseHelpFormatter(argparse.HelpFormatter):
def _format_action_invocation(self, action):
if not action.option_strings or action.nargs == 0:
super()._format_action_invocation(action)
default = self._get_default_metavar_for_optional(action)
args_string = self._format_args(action, default)
return '{} {}'.format(', '.join(action.option_strings), args_string)
output_formats = ('text', 'wiki', 'json')
def parse_args(args=None):
parser = argparse.ArgumentParser(formatter_class=TerseHelpFormatter)
parser.add_argument('files', metavar='FILE', nargs='+', help='ROMs, discs, etc.')
parser.add_argument('-x', '--extract', action='store_true', help='extract files from disc data tracks')
parser.add_argument('-f', '--format', action='store', default='text', choices=output_formats, metavar='FORMAT',
help='use output format: text (default), wiki, json', dest='output_format')
parser.add_argument('--skip-sector-errors', action='store_true', help='skip sector error checks') # TODO temporary
current_module = sys.modules[__name__]
parser.parse_args(namespace=current_module, args=args)
| Add args parameter to parse_args for manually specifying args | Add args parameter to parse_args for manually specifying args
| Python | mit | drx/rom-info | ---
+++
@@ -15,7 +15,7 @@
output_formats = ('text', 'wiki', 'json')
-def parse_args():
+def parse_args(args=None):
parser = argparse.ArgumentParser(formatter_class=TerseHelpFormatter)
parser.add_argument('files', metavar='FILE', nargs='+', help='ROMs, discs, etc.')
@@ -27,4 +27,4 @@
parser.add_argument('--skip-sector-errors', action='store_true', help='skip sector error checks') # TODO temporary
current_module = sys.modules[__name__]
- parser.parse_args(namespace=current_module)
+ parser.parse_args(namespace=current_module, args=args) |
8d18eeabcb17a11ca6f0d63fc9021aa3a369e958 | config.py | config.py | SQLALCHEMY_DATABASE_URI = 'sqlite:///test.db'
SECRET_KEY = 'dummy - change me'
| DEBUG=False
SQLALCHEMY_DATABASE_URI = 'sqlite:///prod.db'
SECRET_KEY = 'dummy - change me'
| Make this resembling more of production settings. | Make this resembling more of production settings.
| Python | agpl-3.0 | okin/sookie,okin/sookie,okin/sookie,okin/sookie | ---
+++
@@ -1,2 +1,3 @@
-SQLALCHEMY_DATABASE_URI = 'sqlite:///test.db'
+DEBUG=False
+SQLALCHEMY_DATABASE_URI = 'sqlite:///prod.db'
SECRET_KEY = 'dummy - change me' |
ccf9240f36cbdc9cd44b4bc862ca71538ca17310 | salt/engines/test.py | salt/engines/test.py | # -*- coding: utf-8 -*-
'''
A simple test engine, not intended for real use but as an example
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import salt libs
import salt.utils.event
import salt.utils.json
log = logging.getLogger(__name__)
def event_bus_context(opts):
if opts['__role'] == 'master':
event_bus = salt.utils.event.get_master_event(
opts,
opts['sock_dir'],
listen=True)
else:
event_bus = salt.utils.event.get_event(
'minion',
transport=opts['transport'],
opts=opts,
sock_dir=opts['sock_dir'],
listen=True)
log.debug('test engine started')
def start():
'''
Listen to events and write them to a log file
'''
with event_bus_context(__opts__) as event:
while True:
event = event_bus.get_event()
jevent = salt.utils.json.dumps(event)
if event:
log.debug(jevent)
| # -*- coding: utf-8 -*-
'''
A simple test engine, not intended for real use but as an example
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import salt libs
import salt.utils.event
import salt.utils.json
log = logging.getLogger(__name__)
def event_bus_context(opts):
if opts['__role'] == 'master':
event_bus = salt.utils.event.get_master_event(
opts,
opts['sock_dir'],
listen=True)
else:
event_bus = salt.utils.event.get_event(
'minion',
transport=opts['transport'],
opts=opts,
sock_dir=opts['sock_dir'],
listen=True)
log.debug('test engine started')
return event_bus
def start():
'''
Listen to events and write them to a log file
'''
with event_bus_context(__opts__) as event_bus:
while True:
event = event_bus.get_event()
jevent = salt.utils.json.dumps(event)
if event:
log.debug(jevent)
| Fix wart in event bus context | Fix wart in event bus context
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | ---
+++
@@ -28,13 +28,14 @@
sock_dir=opts['sock_dir'],
listen=True)
log.debug('test engine started')
+ return event_bus
def start():
'''
Listen to events and write them to a log file
'''
- with event_bus_context(__opts__) as event:
+ with event_bus_context(__opts__) as event_bus:
while True:
event = event_bus.get_event()
jevent = salt.utils.json.dumps(event) |
f2a7fe543aa338e81bea692b8267154e64e7478d | polling_stations/apps/file_uploads/utils.py | polling_stations/apps/file_uploads/utils.py | import os
from django.db.models import Q
from councils.models import Council, UserCouncils
def get_domain(request):
return os.environ.get("APP_DOMAIN", request.META.get("HTTP_HOST"))
def assign_councils_to_user(user):
"""
Adds rows to the join table between User and Council
"""
email_domain = user.email.rsplit("@", 1)[1]
councils = Council.objects.filter(
Q(electoral_services_email__contains=email_domain)
| Q(registration_email__contains=email_domain)
)
for council in councils:
UserCouncils.objects.update_or_create(user=user, council=council)
| import os
from django.db.models import Q
from councils.models import Council, UserCouncils
def get_domain(request):
return os.environ.get("APP_DOMAIN", request.META.get("HTTP_HOST"))
def assign_councils_to_user(user):
"""
Adds rows to the join table between User and Council
"""
email_domain = user.email.rsplit("@", 1)[1]
councils = Council.objects.using("logger").filter(
Q(electoral_services_email__contains=email_domain)
| Q(registration_email__contains=email_domain)
)
for council in councils:
UserCouncils.objects.using("logger").update_or_create(
user=user, council=council
)
| Make sure UserCouncil is created in logger db | Make sure UserCouncil is created in logger db
| Python | bsd-3-clause | DemocracyClub/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations | ---
+++
@@ -14,10 +14,12 @@
Adds rows to the join table between User and Council
"""
email_domain = user.email.rsplit("@", 1)[1]
- councils = Council.objects.filter(
+ councils = Council.objects.using("logger").filter(
Q(electoral_services_email__contains=email_domain)
| Q(registration_email__contains=email_domain)
)
for council in councils:
- UserCouncils.objects.update_or_create(user=user, council=council)
+ UserCouncils.objects.using("logger").update_or_create(
+ user=user, council=council
+ ) |
e71c2c5e593be6d6aef04d9752a675bde3ea3150 | ramicova_debug.py | ramicova_debug.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from pynux import utils
from os.path import expanduser
import collections
import pprint
pp = pprint.PrettyPrinter(indent=4)
CHILD_NXQL = "SELECT * FROM Document WHERE ecm:parentId = '{}' AND " \
"ecm:currentLifeCycleState != 'deleted' ORDER BY ecm:pos"
nx = utils.Nuxeo(rcfile=open(expanduser('~/.pynuxrc'), 'r'))
query = CHILD_NXQL.format('afa37e7d-051f-4fbc-a5b4-e83aa6171aef')
uids = []
for child in nx.nxql(query):
uids.append(child['uid'])
#pp.pprint(uids)
count = len(uids)
dups = [item for item, count in collections.Counter(uids).items() if count > 1]
#pp.pprint(dups)
print len(uids)
print len(dups)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from pynux import utils
from os.path import expanduser
import collections
import pprint
pp = pprint.PrettyPrinter(indent=4)
CHILD_NXQL = "SELECT * FROM Document WHERE ecm:parentId = '{}' AND " \
"ecm:isTrashed = 0 ORDER BY ecm:pos"
nx = utils.Nuxeo(rcfile=open(expanduser('~/.pynuxrc'), 'r'))
query = CHILD_NXQL.format('afa37e7d-051f-4fbc-a5b4-e83aa6171aef')
uids = []
for child in nx.nxql(query):
uids.append(child['uid'])
#pp.pprint(uids)
count = len(uids)
dups = [item for item, count in collections.Counter(uids).items() if count > 1]
#pp.pprint(dups)
print len(uids)
print len(dups)
| Update query for new trash handling | Update query for new trash handling
| Python | bsd-3-clause | ucldc/ucldc-merritt | ---
+++
@@ -8,7 +8,7 @@
pp = pprint.PrettyPrinter(indent=4)
CHILD_NXQL = "SELECT * FROM Document WHERE ecm:parentId = '{}' AND " \
- "ecm:currentLifeCycleState != 'deleted' ORDER BY ecm:pos"
+ "ecm:isTrashed = 0 ORDER BY ecm:pos"
nx = utils.Nuxeo(rcfile=open(expanduser('~/.pynuxrc'), 'r'))
|
b8291dd5bee21ea2dfb77f0fc5b6756773eb5798 | scripts/add_identifiers_to_existing_preprints.py | scripts/add_identifiers_to_existing_preprints.py | import logging
import time
from website.app import init_app
from website.identifiers.utils import get_or_create_identifiers
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
def add_identifiers_to_preprints():
from osf.models import PreprintService
preprints_without_identifiers = PreprintService.objects.filter(identifiers__isnull=True)
logger.info('About to add identifiers to {} preprints.'.format(preprints_without_identifiers.count()))
for preprint in preprints_without_identifiers:
new_identifiers = get_or_create_identifiers(preprint)
logger.info('Saving identifier for preprint {}'.format(preprint.node.title))
preprint.set_preprint_identifiers(new_identifiers)
preprint.save()
time.sleep(1)
logger.info('Finished Adding identifiers to {} preprints.'.format(preprints_without_identifiers.count()))
if __name__ == '__main__':
init_app(routes=False)
add_identifiers_to_preprints()
| import logging
import time
from website.app import init_app
from website.identifiers.utils import get_or_create_identifiers, get_subdomain
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
def add_identifiers_to_preprints():
from osf.models import PreprintService
preprints_without_identifiers = PreprintService.objects.filter(identifiers__isnull=True)
logger.info('About to add identifiers to {} preprints.'.format(preprints_without_identifiers.count()))
for preprint in preprints_without_identifiers:
new_identifiers = get_or_create_identifiers(preprint)
logger.info('Saving identifier for preprint {} from source {}'.format(preprint.node.title, preprint.provider.name))
preprint.set_preprint_identifiers(new_identifiers)
preprint.save()
doi = preprint.get_identifier('doi')
subdomain = get_subdomain(preprint)
assert subdomain.upper() in doi.value
assert preprint._id.upper() in doi.value
logger.info('Created DOI {} for Preprint from service {}'.format(doi.value, preprint.provider.name))
time.sleep(1)
logger.info('Finished Adding identifiers to {} preprints.'.format(preprints_without_identifiers.count()))
if __name__ == '__main__':
init_app(routes=False)
add_identifiers_to_preprints()
| Add more logging and asserts to script | Add more logging and asserts to script
| Python | apache-2.0 | erinspace/osf.io,brianjgeiger/osf.io,caseyrollins/osf.io,chennan47/osf.io,pattisdr/osf.io,mfraezz/osf.io,Johnetordoff/osf.io,saradbowman/osf.io,saradbowman/osf.io,TomBaxter/osf.io,aaxelb/osf.io,felliott/osf.io,pattisdr/osf.io,leb2dg/osf.io,leb2dg/osf.io,HalcyonChimera/osf.io,caneruguz/osf.io,CenterForOpenScience/osf.io,TomBaxter/osf.io,adlius/osf.io,chrisseto/osf.io,caneruguz/osf.io,mattclark/osf.io,crcresearch/osf.io,cslzchen/osf.io,caneruguz/osf.io,crcresearch/osf.io,felliott/osf.io,cslzchen/osf.io,leb2dg/osf.io,chennan47/osf.io,brianjgeiger/osf.io,icereval/osf.io,aaxelb/osf.io,Johnetordoff/osf.io,Johnetordoff/osf.io,baylee-d/osf.io,adlius/osf.io,HalcyonChimera/osf.io,caseyrollins/osf.io,aaxelb/osf.io,sloria/osf.io,HalcyonChimera/osf.io,crcresearch/osf.io,brianjgeiger/osf.io,mfraezz/osf.io,cslzchen/osf.io,mattclark/osf.io,caneruguz/osf.io,chennan47/osf.io,CenterForOpenScience/osf.io,HalcyonChimera/osf.io,adlius/osf.io,chrisseto/osf.io,mattclark/osf.io,laurenrevere/osf.io,felliott/osf.io,cwisecarver/osf.io,erinspace/osf.io,erinspace/osf.io,mfraezz/osf.io,caseyrollins/osf.io,leb2dg/osf.io,cslzchen/osf.io,sloria/osf.io,binoculars/osf.io,baylee-d/osf.io,Johnetordoff/osf.io,binoculars/osf.io,laurenrevere/osf.io,felliott/osf.io,baylee-d/osf.io,adlius/osf.io,binoculars/osf.io,aaxelb/osf.io,chrisseto/osf.io,chrisseto/osf.io,TomBaxter/osf.io,laurenrevere/osf.io,sloria/osf.io,cwisecarver/osf.io,cwisecarver/osf.io,CenterForOpenScience/osf.io,icereval/osf.io,mfraezz/osf.io,brianjgeiger/osf.io,pattisdr/osf.io,CenterForOpenScience/osf.io,cwisecarver/osf.io,icereval/osf.io | ---
+++
@@ -2,7 +2,7 @@
import time
from website.app import init_app
-from website.identifiers.utils import get_or_create_identifiers
+from website.identifiers.utils import get_or_create_identifiers, get_subdomain
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
@@ -14,12 +14,18 @@
preprints_without_identifiers = PreprintService.objects.filter(identifiers__isnull=True)
logger.info('About to add identifiers to {} preprints.'.format(preprints_without_identifiers.count()))
-
for preprint in preprints_without_identifiers:
new_identifiers = get_or_create_identifiers(preprint)
- logger.info('Saving identifier for preprint {}'.format(preprint.node.title))
+ logger.info('Saving identifier for preprint {} from source {}'.format(preprint.node.title, preprint.provider.name))
preprint.set_preprint_identifiers(new_identifiers)
preprint.save()
+
+ doi = preprint.get_identifier('doi')
+ subdomain = get_subdomain(preprint)
+ assert subdomain.upper() in doi.value
+ assert preprint._id.upper() in doi.value
+
+ logger.info('Created DOI {} for Preprint from service {}'.format(doi.value, preprint.provider.name))
time.sleep(1)
logger.info('Finished Adding identifiers to {} preprints.'.format(preprints_without_identifiers.count())) |
c43b69174e44e3de4888b31d70d3dd8939160988 | alexandria/views/user.py | alexandria/views/user.py | from pyramid.view import (
view_config,
view_defaults,
)
from pyramid.httpexceptions import HTTPSeeOther
from pyramid.security import (
remember,
forget,
)
@view_defaults(accept='application/json', renderer='json', context='..traversal.User')
class User(object):
def __init__(self, context, request):
self.request = request
self.context = context
@view_config()
def info(self):
if self.request.authenticated_userid is None:
ret = {
'authenticated': False,
}
else:
ret = {
'authenticated': True,
'user': {
'username': 'example@example.com',
}
}
return ret
@view_config(name='login')
def login(self):
if self.request.body:
print(self.request.json_body)
headers = remember(self.request, "example@example.com")
return HTTPSeeOther(location=self.request.route_url('main', traverse='user'), headers=headers)
return {}
@view_config(name='logout')
def logout(self):
headers = forget(self.request)
return HTTPSeeOther(location=self.request.route_url('main', traverse='user'), headers=headers)
| from pyramid.view import (
view_config,
view_defaults,
)
from pyramid.httpexceptions import HTTPSeeOther
from pyramid.security import (
remember,
forget,
)
@view_defaults(accept='application/json', renderer='json', context='..traversal.User')
class User(object):
def __init__(self, context, request):
self.request = request
self.context = context
@view_config()
def info(self):
if self.request.authenticated_userid is None:
ret = {
'authenticated': False,
}
else:
ret = {
'authenticated': True,
'user': {
'username': 'example@example.com',
}
}
return ret
@view_config(name='login', check_csrf=True, request_method='POST')
def login(self):
if self.request.body:
print(self.request.json_body)
headers = remember(self.request, "example@example.com")
return HTTPSeeOther(location=self.request.route_url('main', traverse='user'), headers=headers)
return {}
@view_config(name='logout', check_csrf=True, request_method='POST')
def logout(self):
headers = forget(self.request)
return HTTPSeeOther(location=self.request.route_url('main', traverse='user'), headers=headers)
| Add predicate to check CSRF token | Add predicate to check CSRF token
| Python | isc | bertjwregeer/alexandria,cdunklau/alexandria,cdunklau/alexandria,cdunklau/alexandria,bertjwregeer/alexandria | ---
+++
@@ -31,7 +31,7 @@
}
return ret
- @view_config(name='login')
+ @view_config(name='login', check_csrf=True, request_method='POST')
def login(self):
if self.request.body:
print(self.request.json_body)
@@ -39,7 +39,7 @@
return HTTPSeeOther(location=self.request.route_url('main', traverse='user'), headers=headers)
return {}
- @view_config(name='logout')
+ @view_config(name='logout', check_csrf=True, request_method='POST')
def logout(self):
headers = forget(self.request)
return HTTPSeeOther(location=self.request.route_url('main', traverse='user'), headers=headers) |
769348413bce3ddc0e5214bb170ad8c5e4a78946 | run_web_client.py | run_web_client.py | # Run a test server.
from app import app
app.run(host='0.0.0.0', port=5000, debug=False)
| # Run a test server.
from app import app
import os
port = int(os.environ.get("PORT", 5000))
app.run(host='0.0.0.0', port=port, debug=True)
| Add os import to fix port from env | Add os import to fix port from env
| Python | isc | appletonmakerspace/madlib,mikeputnam/madlib | ---
+++
@@ -1,3 +1,6 @@
# Run a test server.
from app import app
-app.run(host='0.0.0.0', port=5000, debug=False)
+import os
+
+port = int(os.environ.get("PORT", 5000))
+app.run(host='0.0.0.0', port=port, debug=True) |
b95503f38f8a9b8333c864446dca90e104075059 | sahara/api/acl.py | sahara/api/acl.py | #
# Copyright (c) 2014 Mirantis Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""Policy Engine For Sahara"""
import functools
from oslo_config import cfg
from oslo_policy import policy
from sahara.common import policies
from sahara import context
from sahara import exceptions
ENFORCER = None
def setup_policy():
global ENFORCER
ENFORCER = policy.Enforcer(cfg.CONF)
ENFORCER.register_defaults(policies.list_rules())
def enforce(rule):
def decorator(func):
@functools.wraps(func)
def handler(*args, **kwargs):
ctx = context.ctx()
ENFORCER.enforce(rule, {}, ctx.to_dict(), do_raise=True,
exc=exceptions.Forbidden)
return func(*args, **kwargs)
return handler
return decorator
| #
# Copyright (c) 2014 Mirantis Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""Policy Engine For Sahara"""
import functools
from oslo_config import cfg
from oslo_policy import policy
from sahara.common import policies
from sahara import context
from sahara import exceptions
ENFORCER = None
def setup_policy():
global ENFORCER
ENFORCER = policy.Enforcer(cfg.CONF)
ENFORCER.register_defaults(policies.list_rules())
def enforce(rule):
def decorator(func):
@functools.wraps(func)
def handler(*args, **kwargs):
ctx = context.ctx()
ENFORCER.authorize(rule, {}, ctx.to_dict(), do_raise=True,
exc=exceptions.Forbidden)
return func(*args, **kwargs)
return handler
return decorator
| Use authorize instead of enforce for policies | Use authorize instead of enforce for policies
After fully implementing policies in code, the authorize method
can be safely used and its a safeguard against introducing
policies for some API which are not properly defined in the code.
Change-Id: I499f13c34027b217bf1de905f829f36ef919e3b8
| Python | apache-2.0 | openstack/sahara,openstack/sahara | ---
+++
@@ -39,8 +39,8 @@
@functools.wraps(func)
def handler(*args, **kwargs):
ctx = context.ctx()
- ENFORCER.enforce(rule, {}, ctx.to_dict(), do_raise=True,
- exc=exceptions.Forbidden)
+ ENFORCER.authorize(rule, {}, ctx.to_dict(), do_raise=True,
+ exc=exceptions.Forbidden)
return func(*args, **kwargs)
return handler |
dfac2339c1d667beef5df5e11b74e451e3e35a02 | tests/tests.py | tests/tests.py | import datetime
from importlib import import_module
from django.conf import settings
from django.test import TestCase
from django.test.utils import override_settings
from django.utils import timezone
from session_cleanup.tasks import cleanup
class CleanupTest(TestCase):
@override_settings(SESSION_ENGINE="django.contrib.sessions.backends.file")
def test_session_cleanup(self):
"""
Tests that sessions are deleted by the task
"""
engine = import_module(settings.SESSION_ENGINE)
SessionStore = engine.SessionStore
now = timezone.now()
last_week = now - datetime.timedelta(days=7)
stores = []
unexpired_stores = []
expired_stores = []
# create unexpired sessions
for i in range(20):
store = SessionStore()
store.save()
stores.append(store)
for store in stores:
self.assertEqual(store.exists(store.session_key), True,
"Session store could not be created.")
unexpired_stores = stores[:10]
expired_stores = stores[10:]
# expire some sessions
for store in expired_stores:
store.set_expiry(last_week)
store.save()
cleanup()
for store in unexpired_stores:
self.assertEqual(store.exists(store.session_key), True,
"Unexpired session was deleted by cleanup.")
for store in expired_stores:
self.assertEqual(store.exists(store.session_key), False,
"Expired session was not deleted by cleanup.")
| import datetime
from importlib import import_module
from django.conf import settings
from django.test import TestCase
from django.test.utils import override_settings
from django.utils import timezone
from session_cleanup.tasks import cleanup
class CleanupTest(TestCase):
@override_settings(SESSION_ENGINE="django.contrib.sessions.backends.file")
@override_settings(SESSION_SERIALIZER="django.contrib.sessions.serializers.PickleSerializer") # noqa: E501
def test_session_cleanup(self):
"""
Tests that sessions are deleted by the task
"""
engine = import_module(settings.SESSION_ENGINE)
SessionStore = engine.SessionStore
now = timezone.now()
last_week = now - datetime.timedelta(days=7)
stores = []
unexpired_stores = []
expired_stores = []
# create unexpired sessions
for i in range(20):
store = SessionStore()
store.save()
stores.append(store)
for store in stores:
self.assertEqual(store.exists(store.session_key), True,
"Session store could not be created.")
unexpired_stores = stores[:10]
expired_stores = stores[10:]
# expire some sessions
for store in expired_stores:
store.set_expiry(last_week)
store.save()
cleanup()
for store in unexpired_stores:
self.assertEqual(store.exists(store.session_key), True,
"Unexpired session was deleted by cleanup.")
for store in expired_stores:
self.assertEqual(store.exists(store.session_key), False,
"Expired session was not deleted by cleanup.")
| Use PickleSerializer to serialize test sessions. | Use PickleSerializer to serialize test sessions.
Use PickleSerializer so that we can serialize datetimes in sessions
(this is necessary to set expired sessions in automated tests). See
https://docs.djangoproject.com/en/2.0/topics/http/sessions/#write-your-own-serializer.
| Python | bsd-2-clause | sandersnewmedia/django-session-cleanup | ---
+++
@@ -11,6 +11,7 @@
class CleanupTest(TestCase):
@override_settings(SESSION_ENGINE="django.contrib.sessions.backends.file")
+ @override_settings(SESSION_SERIALIZER="django.contrib.sessions.serializers.PickleSerializer") # noqa: E501
def test_session_cleanup(self):
"""
Tests that sessions are deleted by the task |
25aa6fb5887f1f60c833299c379bbf03cc794e45 | src/inbox/util/__init__.py | src/inbox/util/__init__.py | # Don't add new code here! Find the relevant submodule, or use misc.py if
# there's really no other place.
| """ Non-server-specific utility modules. These shouldn't depend on any code
from the inbox.server module tree!
Don't add new code here! Find the relevant submodule, or use misc.py if
there's really no other place.
"""
| Clarify the role of inbox.util module. | Clarify the role of inbox.util module.
| Python | agpl-3.0 | jobscore/sync-engine,jobscore/sync-engine,closeio/nylas,rmasters/inbox,wakermahmud/sync-engine,Eagles2F/sync-engine,Eagles2F/sync-engine,EthanBlackburn/sync-engine,gale320/sync-engine,ErinCall/sync-engine,wakermahmud/sync-engine,gale320/sync-engine,nylas/sync-engine,PriviPK/privipk-sync-engine,rmasters/inbox,closeio/nylas,PriviPK/privipk-sync-engine,nylas/sync-engine,Eagles2F/sync-engine,EthanBlackburn/sync-engine,PriviPK/privipk-sync-engine,ErinCall/sync-engine,EthanBlackburn/sync-engine,gale320/sync-engine,wakermahmud/sync-engine,rmasters/inbox,ErinCall/sync-engine,closeio/nylas,EthanBlackburn/sync-engine,jobscore/sync-engine,wakermahmud/sync-engine,gale320/sync-engine,gale320/sync-engine,PriviPK/privipk-sync-engine,jobscore/sync-engine,closeio/nylas,wakermahmud/sync-engine,Eagles2F/sync-engine,rmasters/inbox,ErinCall/sync-engine,nylas/sync-engine,PriviPK/privipk-sync-engine,EthanBlackburn/sync-engine,ErinCall/sync-engine,Eagles2F/sync-engine,nylas/sync-engine | ---
+++
@@ -1,2 +1,6 @@
-# Don't add new code here! Find the relevant submodule, or use misc.py if
-# there's really no other place.
+""" Non-server-specific utility modules. These shouldn't depend on any code
+ from the inbox.server module tree!
+
+ Don't add new code here! Find the relevant submodule, or use misc.py if
+ there's really no other place.
+""" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.