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 |
|---|---|---|---|---|---|---|---|---|---|---|
86f9fb93725da3ccc308d1957a64e932835f1823 | server.py | server.py | from fickle import API
from fickle.classifier import GenericSVMClassifier
backend = GenericSVMClassifier()
app = API(__name__, backend)
app.run(debug = True)
| from fickle import API
from fickle.classifier import GenericSVMClassifier
backend = GenericSVMClassifier()
app = API(__name__, backend)
if __name__ == '__main__':
host = '0.0.0.0'
port = int(os.environ.get('PORT', 5000))
debug = bool(os.environ.get('FICKLE_DEBUG'))
app.run(host = host, port = port, d... | Copy run section from Heroku example | Copy run section from Heroku example
| Python | mit | norbert/fickle | ---
+++
@@ -4,4 +4,9 @@
backend = GenericSVMClassifier()
app = API(__name__, backend)
-app.run(debug = True)
+
+if __name__ == '__main__':
+ host = '0.0.0.0'
+ port = int(os.environ.get('PORT', 5000))
+ debug = bool(os.environ.get('FICKLE_DEBUG'))
+ app.run(host = host, port = port, debug = debug) |
06ef36df365bc54159d1600d53134e8c70ef50c4 | spider.py | spider.py | from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import Selector
class DatasetSpider(CrawlSpider):
name = 'dataset'
allowed_domains = ['data.gc.ca']
start_urls = ['http://data.gc.ca/data/en/dataset?page=1']
| from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import Selector
class DatasetSpider(CrawlSpider):
name = 'dataset'
allowed_domains = ['data.gc.ca/data/en']
start_urls = ['http://data.gc.ca/data/en/dataset?page=1']
| Modify allowable domain to restrict crawling | Modify allowable domain to restrict crawling
| Python | mit | MaxLikelihood/CODE | ---
+++
@@ -5,6 +5,6 @@
class DatasetSpider(CrawlSpider):
name = 'dataset'
- allowed_domains = ['data.gc.ca']
+ allowed_domains = ['data.gc.ca/data/en']
start_urls = ['http://data.gc.ca/data/en/dataset?page=1']
|
345d7dda5b48633d5532c6a1ad1d94749f528668 | pskb_website/__init__.py | pskb_website/__init__.py | import os
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
# Running on heroku
if 'HEROKU' in os.environ:
from example_config import HEROKU_ENV_REQUIREMENTS
# example_config.py provides a blueprint for which variables to look for in
# the environment and set in o... | import os
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
# Running on heroku
if 'HEROKU' in os.environ:
from example_config import HEROKU_ENV_REQUIREMENTS
# example_config.py provides a blueprint for which variables to look for in
# the environment and set in o... | Add ability to set debug on heroku staging server | Add ability to set debug on heroku staging server
| Python | agpl-3.0 | paulocheque/guides-cms,pluralsight/guides-cms,paulocheque/guides-cms,pluralsight/guides-cms,paulocheque/guides-cms,pluralsight/guides-cms | ---
+++
@@ -13,6 +13,10 @@
# the environment and set in our app config.
for var in HEROKU_ENV_REQUIREMENTS:
app.config.setdefault(var, os.environ[var])
+
+ if 'DEBUG' in os.environ:
+ app.config.setdefault('debug', True)
+
else:
app.config.from_object(os.environ['APP_SETTINGS'])
... |
64ec292206f4690ae6a8e85f4a7e7e9853d55f32 | project_template/config/urls.py | project_template/config/urls.py | from django.conf.urls.defaults import patterns, include, url
from django.view.generic import TemplateView
# ADMIN_BASE is the base URL for your Armstrong admin. It is highly
# recommended that you change this to a different URL unless you enforce a
# strict password-strength policy for your users.
ADMIN_BASE = "admin... | from django.conf.urls.defaults import patterns, include, url
from django.views.generic import TemplateView
# ADMIN_BASE is the base URL for your Armstrong admin. It is highly
# recommended that you change this to a different URL unless you enforce a
# strict password-strength policy for your users.
ADMIN_BASE = "admi... | Fix typo in import and bump to 0.3.1 | Fix typo in import and bump to 0.3.1
| Python | apache-2.0 | armstrong/armstrong.templates.standard,armstrong/armstrong.templates.standard | ---
+++
@@ -1,5 +1,5 @@
from django.conf.urls.defaults import patterns, include, url
-from django.view.generic import TemplateView
+from django.views.generic import TemplateView
# ADMIN_BASE is the base URL for your Armstrong admin. It is highly
# recommended that you change this to a different URL unless you e... |
4d06890ae7223a61147da857d8cdfb6c208dfc52 | lib/pegasus/python/Pegasus/cli/pegasus-init.py | lib/pegasus/python/Pegasus/cli/pegasus-init.py | #!/usr/bin/env python3
import sys
import os
import subprocess
# Use pegasus-config to find our lib path
bin_dir = os.path.normpath(os.path.join(os.path.dirname(sys.argv[0])))
pegasus_config = os.path.join(bin_dir, "pegasus-config") + " --python-dump"
exec(subprocess.Popen(pegasus_config, stdout=subprocess.PIPE, shell=... | #!/usr/bin/env python3
import os
from pathlib import Path
from Pegasus.init import main
pegasus_share_dir = (Path(os.environ["PEGASUS_HOME"]) / "share" / "pegasus").resolve()
main(str(pegasus_share_dir))
| Remove call to p-config, as it is handled in p-python-wrapper | Remove call to p-config, as it is handled in p-python-wrapper
| Python | apache-2.0 | pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus | ---
+++
@@ -1,18 +1,10 @@
#!/usr/bin/env python3
-import sys
+
import os
-import subprocess
-
-# Use pegasus-config to find our lib path
-bin_dir = os.path.normpath(os.path.join(os.path.dirname(sys.argv[0])))
-pegasus_config = os.path.join(bin_dir, "pegasus-config") + " --python-dump"
-exec(subprocess.Popen(pegasus... |
e2efb3855cd7888b778c3c7ff343c2bdcb942ab0 | pushmanager/testing/__init__.py | pushmanager/testing/__init__.py | #!/usr/bin/env python
import testify
# don't want all of testify's modules, just its goodies
from testify.__init__ import *
from mocksettings import MockedSettings
from testservlet import AsyncTestCase
from testservlet import ServletTestMixin
from testservlet import TemplateTestCase
from testdb import *
__all__ = ... | #!/usr/bin/python
# don't want all of testify's modules, just its goodies
from testify import TestCase
from testify import teardown
from testify import class_teardown
from testify import class_setup_teardown
from testify import setup_teardown
from testify import setup
from testify import class_setup
from testify impor... | Make pushmanager.testing more explicit in imports | Make pushmanager.testing more explicit in imports
| Python | apache-2.0 | Yelp/pushmanager,YelpArchive/pushmanager,asottile/pushmanager,Yelp/pushmanager,asottile/pushmanager,YelpArchive/pushmanager,YelpArchive/pushmanager,asottile/pushmanager,Yelp/pushmanager,Yelp/pushmanager,YelpArchive/pushmanager | ---
+++
@@ -1,21 +1,41 @@
-#!/usr/bin/env python
-
-import testify
+#!/usr/bin/python
# don't want all of testify's modules, just its goodies
-from testify.__init__ import *
-
-from mocksettings import MockedSettings
-from testservlet import AsyncTestCase
-from testservlet import ServletTestMixin
-from testservlet... |
06968396f475cf881adcab06272df6de4f94f3ff | scripts/master/factory/dart/channels.py | scripts/master/factory/dart/channels.py | # Copyright 2013 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.
class Channel(object):
def __init__(self, name, branch, position, category_postfix, priority):
self.branch = branch
self.builder_postfix = '-' + na... | # Copyright 2013 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.
class Channel(object):
def __init__(self, name, branch, position, category_postfix, priority):
self.branch = branch
self.builder_postfix = '-' + na... | Make dart master pull stable from 1.7 | Make dart master pull stable from 1.7
Review URL: https://codereview.chromium.org/638823002
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@292365 0039d316-1c4b-4281-b951-d872f2087c98
| Python | bsd-3-clause | eunchong/build,eunchong/build,eunchong/build,eunchong/build | ---
+++
@@ -19,7 +19,7 @@
CHANNELS = [
Channel('be', 'branches/bleeding_edge', 0, '', 4),
Channel('dev', 'trunk', 1, '-dev', 2),
- Channel('stable', 'branches/1.6', 2, '-stable', 1),
+ Channel('stable', 'branches/1.7', 2, '-stable', 1),
Channel('integration', 'branches/dartium_integration', 3, '-integrati... |
c6a517717083eedffeb7b70bfdf6cbf7049516e4 | main.py | main.py | # Import blockmodels file
import BlockModels
import webapp2, jinja2, os
from datetime import *
jinja_environment = jinja2.Environment(autoescape=True,
loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates')))
class CST(tzinfo):
def utcoffset(self, dt):
return timedelta(hour... | # Import blockmodels file
import BlockModels
import webapp2, jinja2, os
from datetime import *
jinja_environment = jinja2.Environment(autoescape=True,
loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates')))
class CST(tzinfo):
def utcoffset(self, dt):
return timedelta(hour... | Create new Class MainHandler with the template values with the variable block and made it into index.html | Create new Class MainHandler with the template values with the variable block and made it into index.html
| Python | mit | shickey/BearStatus,shickey/BearStatus,shickey/BearStatus | ---
+++
@@ -18,6 +18,15 @@
cst = CST()
+class MainHandler(webapp2.RequestHandler):
+ def get(self):
+ template_values = {
+ 'block': block,
+ }
+
+ template = jinja_environment.get_template('index.html')
+ self.response.out.write(template.render(template_values))... |
e6f7c6657485b33760e2522afb6b25ba5ed405fd | pyramid_zipkin/zipkin.py | pyramid_zipkin/zipkin.py | # -*- coding: utf-8 -*-
from py_zipkin.zipkin import create_http_headers_for_new_span \
as create_headers_for_new_span # pragma: no cover
| # -*- coding: utf-8 -*-
from py_zipkin.zipkin import create_http_headers_for_new_span # pragma: no cover
# Backwards compatibility for places where pyramid_zipkin is unpinned
create_headers_for_new_span = create_http_headers_for_new_span # pragma: no cover
| Split import into 2 lines to make flake8 happy | Split import into 2 lines to make flake8 happy
| Python | apache-2.0 | bplotnick/pyramid_zipkin,Yelp/pyramid_zipkin | ---
+++
@@ -1,3 +1,6 @@
# -*- coding: utf-8 -*-
-from py_zipkin.zipkin import create_http_headers_for_new_span \
- as create_headers_for_new_span # pragma: no cover
+from py_zipkin.zipkin import create_http_headers_for_new_span # pragma: no cover
+
+
+# Backwards compatibility for places where pyramid_zipki... |
b6c0a85a3199499b607ebb9ecc057434a9ea2fe5 | mizani/__init__.py | mizani/__init__.py | from importlib.metadata import version, PackageNotFoundError
try:
__version__ = version('plotnine')
except PackageNotFoundError:
# package is not installed
pass
| from importlib.metadata import version, PackageNotFoundError
try:
__version__ = version('mizani')
except PackageNotFoundError:
# package is not installed
pass
| Fix version number to check for mizani | Fix version number to check for mizani
and not plotnine. Copypaste error!
| Python | bsd-3-clause | has2k1/mizani,has2k1/mizani | ---
+++
@@ -2,7 +2,7 @@
try:
- __version__ = version('plotnine')
+ __version__ = version('mizani')
except PackageNotFoundError:
# package is not installed
pass |
53bed4837805fa304153622689abb7c4c581ec73 | registration/__init__.py | registration/__init__.py | from django.utils.version import get_version as django_get_version
VERSION = (0, 9, 0, 'beta', 1)
def get_version():
return django_get_version(VERSION) # pragma: no cover
| VERSION = (0, 9, 0, 'beta', 1)
def get_version():
from django.utils.version import get_version as django_get_version
return django_get_version(VERSION) # pragma: no cover
| Move import of Django's get_version into django-registration's get_version, to avoid dependency-order problems. | Move import of Django's get_version into django-registration's get_version, to avoid dependency-order problems.
| Python | bsd-3-clause | Geffersonvivan/django-registration,ei-grad/django-registration,nikolas/django-registration,kinsights/django-registration,alawnchen/django-registration,Geffersonvivan/django-registration,wda-hb/test,arpitremarkable/django-registration,yorkedork/django-registration,maitho/django-registration,percipient/django-registratio... | ---
+++
@@ -1,8 +1,6 @@
-from django.utils.version import get_version as django_get_version
-
-
VERSION = (0, 9, 0, 'beta', 1)
def get_version():
+ from django.utils.version import get_version as django_get_version
return django_get_version(VERSION) # pragma: no cover |
a1903c3e7d8bd8f7421a9665039ee66e387d19d4 | django_bleach/templatetags/bleach_tags.py | django_bleach/templatetags/bleach_tags.py | import bleach
from django import template
from django.conf import settings
from django.utils.safestring import mark_safe
register = template.Library()
bleach_args = {}
possible_settings = {
'BLEACH_ALLOWED_TAGS': 'tags',
'BLEACH_ALLOWED_ATTRIBUTES': 'attributes',
'BLEACH_ALLOWED_STYLES': 'styles',
... | import bleach
from django import template
from django.conf import settings
from django.utils.safestring import mark_safe
register = template.Library()
bleach_args = {}
possible_settings = {
'BLEACH_ALLOWED_TAGS': 'tags',
'BLEACH_ALLOWED_ATTRIBUTES': 'attributes',
'BLEACH_ALLOWED_STYLES': 'styles',
... | Use items() instead of iteritems() for Python 2 and 3 compatibility | Use items() instead of iteritems() for Python 2 and 3 compatibility
| Python | bsd-2-clause | python-force/django-bleach | ---
+++
@@ -17,7 +17,7 @@
'BLEACH_STRIP_COMMENTS': 'strip_comments',
}
-for setting, kwarg in possible_settings.iteritems():
+for setting, kwarg in possible_settings.items():
if hasattr(settings, setting):
bleach_args[kwarg] = getattr(settings, setting)
|
b9e61db86efd788f8ee321a3dbfcf09293d92337 | speedinfo/conf.py | speedinfo/conf.py | # coding: utf-8
from django.conf import settings
DEFAULTS = {
"SPEEDINFO_TESTS": False,
"SPEEDINFO_CACHED_RESPONSE_ATTR_NAME": "is_cached",
"SPEEDINFO_STORAGE": None,
"SPEEDINFO_CACHE_STORAGE_CACHE_ALIAS": "default",
"SPEEDINFO_PROFILING_CONDITIONS": [],
"SPEEDINFO_EXCLUDE_URLS": [],
"SPEE... | # coding: utf-8
from django.conf import settings
DEFAULTS = {
"SPEEDINFO_TESTS": False,
"SPEEDINFO_CACHED_RESPONSE_ATTR_NAME": "_is_cached",
"SPEEDINFO_STORAGE": None,
"SPEEDINFO_CACHE_STORAGE_CACHE_ALIAS": "default",
"SPEEDINFO_PROFILING_CONDITIONS": [],
"SPEEDINFO_EXCLUDE_URLS": [],
"SPE... | Change SPEEDINFO_CACHED_RESPONSE_ATTR_NAME default value to `_is_cached` | Change SPEEDINFO_CACHED_RESPONSE_ATTR_NAME default value to `_is_cached`
| Python | mit | catcombo/django-speedinfo,catcombo/django-speedinfo,catcombo/django-speedinfo | ---
+++
@@ -4,7 +4,7 @@
DEFAULTS = {
"SPEEDINFO_TESTS": False,
- "SPEEDINFO_CACHED_RESPONSE_ATTR_NAME": "is_cached",
+ "SPEEDINFO_CACHED_RESPONSE_ATTR_NAME": "_is_cached",
"SPEEDINFO_STORAGE": None,
"SPEEDINFO_CACHE_STORAGE_CACHE_ALIAS": "default",
"SPEEDINFO_PROFILING_CONDITIONS": [], |
ce3fb7643e5c75a1f5fdae77a6667df407cb55b1 | interface.py | interface.py | # -*- coding: utf-8 -*-
"""
Created on Thu Jul 21 13:53:47 2016
@author: mela
"""
| # -*- coding: utf-8 -*-
"""
Created on Thu Jul 21 13:53:47 2016
@author: mela
"""
print(adfadsfad);
| Test commit on new branch, change to username and email. | Test commit on new branch, change to username and email.
| Python | mit | akmelkonian/city-in-purple | ---
+++
@@ -5,3 +5,5 @@
@author: mela
"""
+print(adfadsfad);
+ |
69fc2eccaa88189fd0de86d11206fa24d1508819 | tools/np_suppressions.py | tools/np_suppressions.py | suppressions = [
[ ".*/multiarray/mapping\.", "PyArray_MapIterReset" ],
# PyArray_Std trivially forwards to and appears to be superceded by
# __New_PyArray_Std, which is exercised by the test framework.
[ ".*/multiarray/calculation\.", "PyArray_Std" ],
# PyCapsule_Check is declared in a header, an... | suppressions = [
# This one cannot be covered by any Python language test because there is
# no code pathway to it. But it is part of the C API, so must not be
# excised from the code.
[ r".*/multiarray/mapping\.", "PyArray_MapIterReset" ],
# PyArray_Std trivially forwards to and appears to be sup... | Add documentation on one assertion, convert RE's to raw strings. | Add documentation on one assertion, convert RE's to raw strings.
| Python | bsd-3-clause | teoliphant/numpy-refactor,teoliphant/numpy-refactor,jasonmccampbell/numpy-refactor-sprint,jasonmccampbell/numpy-refactor-sprint,teoliphant/numpy-refactor,jasonmccampbell/numpy-refactor-sprint,jasonmccampbell/numpy-refactor-sprint,teoliphant/numpy-refactor,teoliphant/numpy-refactor | ---
+++
@@ -1,11 +1,14 @@
suppressions = [
- [ ".*/multiarray/mapping\.", "PyArray_MapIterReset" ],
+ # This one cannot be covered by any Python language test because there is
+ # no code pathway to it. But it is part of the C API, so must not be
+ # excised from the code.
+ [ r".*/multiarray/mapping... |
ab828ae56d79a280b5330144ace771badbe5eb3f | samples/shopping/main.py | samples/shopping/main.py | #!/usr/bin/python2.4
# -*- coding: utf-8 -*-
#
# Copyright 2010 Google Inc. All Rights Reserved.
"""Simple command-line example for The Google Shopping API.
Command-line application that does a search for products.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
from apiclient.discovery import build
import... | #!/usr/bin/python2.4
# -*- coding: utf-8 -*-
#
# Copyright 2010 Google Inc. All Rights Reserved.
"""Simple command-line example for The Google Search
API for Shopping.
Command-line application that does a search for products.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
from apiclient.discovery import bu... | Correct name for the shopping search api | Correct name for the shopping search api
| Python | apache-2.0 | google/oauth2client,google/oauth2client,googleapis/google-api-python-client,jonparrott/oauth2client,googleapis/oauth2client,googleapis/google-api-python-client,jonparrott/oauth2client,clancychilds/oauth2client,googleapis/oauth2client,clancychilds/oauth2client | ---
+++
@@ -3,7 +3,8 @@
#
# Copyright 2010 Google Inc. All Rights Reserved.
-"""Simple command-line example for The Google Shopping API.
+"""Simple command-line example for The Google Search
+API for Shopping.
Command-line application that does a search for products.
""" |
e3312c773e9e3ac9b939bc3e0ca6a872dae5cdef | pre_commit_hooks/trailing_whitespace_fixer.py | pre_commit_hooks/trailing_whitespace_fixer.py | from __future__ import print_function
import argparse
import sys
from plumbum import local
from pre_commit_hooks.util import entry
@entry
def fix_trailing_whitespace(argv):
parser = argparse.ArgumentParser()
parser.add_argument('filenames', nargs='*', help='Filenames to fix')
args = parser.parse_args(ar... | from __future__ import print_function
import argparse
import fileinput
import sys
from plumbum import local
from pre_commit_hooks.util import entry
def _fix_file(filename):
for line in fileinput.input([filename], inplace=True):
print(line.rstrip())
@entry
def fix_trailing_whitespace(argv):
parser ... | Use fileinput instead of sed. | Use fileinput instead of sed.
| Python | mit | Coverfox/pre-commit-hooks,Harwood/pre-commit-hooks,bgschiller/pre-commit-hooks,pre-commit/pre-commit-hooks,jordant/pre-commit-hooks,jordant/pre-commit-hooks,chriskuehl/pre-commit-hooks,dupuy/pre-commit-hooks,arahayrabedian/pre-commit-hooks | ---
+++
@@ -1,10 +1,16 @@
from __future__ import print_function
import argparse
+import fileinput
import sys
from plumbum import local
from pre_commit_hooks.util import entry
+
+
+def _fix_file(filename):
+ for line in fileinput.input([filename], inplace=True):
+ print(line.rstrip())
@entry
@@... |
705af291a4e7ddbb366671757ca647bcd56b8e24 | twitter_api/twitterApi.py | twitter_api/twitterApi.py | #!/usr/bin/env python
import twitter
class Twitter:
def __init__(self):
consumer_key = "WXfZoJi7i8TFmrGOK5Y7dVHon"
consumer_secret = "EE46ezCkgKwy8GaKOFFCuMMoZbwDprnEXjhVMn7vI7cYaTbdcA"
access_key = "867082422885785600-AJ0LdE8vc8uMs21VDv2jrkwkQg9PClG"
access_secret = "qor8vV5kGqQ7... | #!/usr/bin/env python
import twitter
import json
class Twitter:
def __init__(self):
with open('/etc/twitter.json') as data_file:
data = json.load(data_file)
encoding = None
self.api = twitter.Api(consumer_key=data["consumer_key"], consumer_secret=data["consumer_secret"],
... | Use setting file on /etc | Use setting file on /etc
| Python | mit | phil-r/chaos,eukaryote31/chaos,phil-r/chaos,chaosbot/Chaos,botchaos/Chaos,mark-i-m/Chaos,mpnordland/chaos,mark-i-m/Chaos,hongaar/chaos,phil-r/chaos,mpnordland/chaos,rudehn/chaos,rudehn/chaos,botchaos/Chaos,Chaosthebot/Chaos,eukaryote31/chaos,g19fanatic/chaos,botchaos/Chaos,g19fanatic/chaos,hongaar/chaos,mpnordland/chao... | ---
+++
@@ -1,17 +1,16 @@
#!/usr/bin/env python
import twitter
+import json
class Twitter:
def __init__(self):
- consumer_key = "WXfZoJi7i8TFmrGOK5Y7dVHon"
- consumer_secret = "EE46ezCkgKwy8GaKOFFCuMMoZbwDprnEXjhVMn7vI7cYaTbdcA"
- access_key = "867082422885785600-AJ0LdE8vc8uMs21VDv2... |
32951dda5a46487a485c949a07f457ae537f07f2 | src/encoded/upgrade/bismark_quality_metric.py | src/encoded/upgrade/bismark_quality_metric.py | from contentbase import (
ROOT,
upgrade_step,
)
@upgrade_step('bismark_quality_metric', '1', '2')
def bismark_quality_metric_1_2(value, system):
# http://redmine.encodedcc.org/issues/3114
root = system['registry'][ROOT]
step_run = root.get_by_uuid(value['step_run'])
value['quality_metric_of'] =... | from contentbase import (
CONNECTION,
upgrade_step,
)
@upgrade_step('bismark_quality_metric', '1', '2')
def bismark_quality_metric_1_2(value, system):
# http://redmine.encodedcc.org/issues/3114
conn = system['registry'][CONNECTION]
step_run = conn.get_by_uuid(value['step_run'])
output_files = ... | Change upgrade step to not use rev link. | Change upgrade step to not use rev link.
| Python | mit | 4dn-dcic/fourfront,hms-dbmi/fourfront,4dn-dcic/fourfront,T2DREAM/t2dream-portal,hms-dbmi/fourfront,ENCODE-DCC/encoded,T2DREAM/t2dream-portal,T2DREAM/t2dream-portal,ENCODE-DCC/encoded,ENCODE-DCC/snovault,ENCODE-DCC/snovault,ENCODE-DCC/encoded,hms-dbmi/fourfront,4dn-dcic/fourfront,4dn-dcic/fourfront,ENCODE-DCC/snovault,E... | ---
+++
@@ -1,14 +1,16 @@
from contentbase import (
- ROOT,
+ CONNECTION,
upgrade_step,
)
+
@upgrade_step('bismark_quality_metric', '1', '2')
def bismark_quality_metric_1_2(value, system):
# http://redmine.encodedcc.org/issues/3114
- root = system['registry'][ROOT]
- step_run = root.get_by... |
b6a66fa8ecdfbdd196c1d2a776c85ed9b3c1c06d | test/test_configuration.py | test/test_configuration.py | from __future__ import with_statement
import os.path
import tempfile
from nose.tools import *
from behave import configuration
# one entry of each kind handled
TEST_CONFIG='''[behave]
outfile=/tmp/spam
paths = /absolute/path
relative/path
tags = @foo,~@bar
@zap
format=pretty
tag-counter
stdout_c... | from __future__ import with_statement
import os.path
import tempfile
from nose.tools import *
from behave import configuration
# one entry of each kind handled
TEST_CONFIG='''[behave]
outfile=/tmp/spam
paths = /absolute/path
relative/path
tags = @foo,~@bar
@zap
format=pretty
tag-counter
stdout_c... | FIX test for Windows platform. | FIX test for Windows platform.
| Python | bsd-2-clause | hugeinc/behave-parallel | ---
+++
@@ -27,7 +27,7 @@
d = configuration.read_configuration(tn)
eq_(d['outfile'], '/tmp/spam')
eq_(d['paths'], [
- '/absolute/path',
+ os.path.normpath('/absolute/path'), # -- WINDOWS-REQUIRES: normpath
os.path.normpath(os.path.join(os.path.dirname(tn)... |
7127489fc85537722c6216ea6af0005604214bdc | txircd/modules/umode_i.py | txircd/modules/umode_i.py | from txircd.modbase import Mode
class InvisibleMode(Mode):
def namesListEntry(self, recipient, channel, user, representation):
if channel not in recipient.channels and "i" in user.mode:
return ""
return representation
class Spawner(object):
def __init__(self, ircd):
self.ircd = ircd
def spawn(self):
r... | from txircd.modbase import Mode
class InvisibleMode(Mode):
def namesListEntry(self, recipient, channel, user, representation):
if channel.name not in recipient.channels and "i" in user.mode:
return ""
return representation
class Spawner(object):
def __init__(self, ircd):
self.ircd = ircd
def spawn(self)... | Fix interpretation of parameters for names list modification | Fix interpretation of parameters for names list modification
| Python | bsd-3-clause | DesertBus/txircd,ElementalAlchemist/txircd,Heufneutje/txircd | ---
+++
@@ -2,7 +2,7 @@
class InvisibleMode(Mode):
def namesListEntry(self, recipient, channel, user, representation):
- if channel not in recipient.channels and "i" in user.mode:
+ if channel.name not in recipient.channels and "i" in user.mode:
return ""
return representation
|
b903bcfc893911e0abd313e3cd9ea5c7128024de | MS1/ddp-erlang-style/dna_lib.py | MS1/ddp-erlang-style/dna_lib.py | __author__ = 'mcsquaredjr'
import os
import socket
node_file = os.environ["NODES"]
cad_file = os.environ["CAD"]
procs_per_nod = os.environ["PROCS_PER_NODE"]
itemcount = os.environ["ITEMCOUNT"]
ddp = os.environment["DDP"]
def my_lines(i):
ip = socket.gethostbyname(socket.gethostname())
with open(cad_file, "... | __author__ = 'mcsquaredjr'
import os
import socket
node_file = os.environ["NODES"]
cad_file = os.environ["CAD"]
procs_per_nod = os.environ["PROCS_PER_NODE"]
itemcount = os.environ["ITEMCOUNT"]
ddp = os.environment["DDP"]
def my_lines():
ip = socket.gethostbyname(socket.gethostname())
with open(cad_file, "r... | Add more variables and bug fixes | Add more variables and bug fixes
| Python | apache-2.0 | SKA-ScienceDataProcessor/RC,SKA-ScienceDataProcessor/RC,SKA-ScienceDataProcessor/RC,SKA-ScienceDataProcessor/RC,SKA-ScienceDataProcessor/RC | ---
+++
@@ -11,7 +11,7 @@
-def my_lines(i):
+def my_lines():
ip = socket.gethostbyname(socket.gethostname())
with open(cad_file, "r") as cad:
lines = []
@@ -25,7 +25,7 @@
if i == 0 or i == 1:
return 0
else:
- return i -1
+ return i - 1
def chunk_count(i): |
78c3ad892260e9a89dab533a42f0c8f09f2401ca | src/armet/connectors/django/__init__.py | src/armet/connectors/django/__init__.py | # -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals, division
__all__ = [
]
def is_available(*capacities):
"""
Detects if the environment is available for use in
the (optionally) specified capacities.
"""
try:
# Attempted import.
import django
... | # -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals, division
__all__ = [
]
def is_available(*capacities):
"""
Detects if the environment is available for use in
the (optionally) specified capacities.
"""
try:
# Attempted import.
import django
exc... | Fix is_available method in django; proper exception handling for use checking. | Fix is_available method in django; proper exception handling for use checking.
| Python | mit | armet/python-armet | ---
+++
@@ -15,6 +15,14 @@
# Attempted import.
import django
+ except ImportError:
+ # Failed to import django
+ return False
+
+ # Import the exception we might get
+ from django.core.exceptions import ImproperlyConfigured
+
+ try:
# Now try and use it.
... |
9cea978862a5db98dc2b0a4aad0a19533357b9d2 | run_travis_lambdas.py | run_travis_lambdas.py | #!/usr/bin/env python
# -*- encoding: utf-8
"""
Usage: run_travis_lambdas.py (test|publish)
"""
import os
import subprocess
import sys
if __name__ == '__main__':
try:
verb = sys.argv[1]
assert verb in ('test', 'publish')
except (AssertionError, IndexError):
sys.exit(__doc__.strip())
... | #!/usr/bin/env python
# -*- encoding: utf-8
"""
Usage: run_travis_lambdas.py (test|publish)
"""
import os
import subprocess
import sys
if __name__ == '__main__':
try:
verb = sys.argv[1]
assert verb in ('test', 'publish')
except (AssertionError, IndexError):
sys.exit(__doc__.strip())
... | Make sure we use Python 3 here | Make sure we use Python 3 here
| Python | mit | wellcometrust/platform-api,wellcometrust/platform-api,wellcometrust/platform-api,wellcometrust/platform-api | ---
+++
@@ -31,7 +31,7 @@
env['TASK'] = '%s-%s' % (lambda_name, verb)
try:
- subprocess.check_call(['python', 'run_travis_task.py'], env=env)
+ subprocess.check_call(['python3', 'run_travis_task.py'], env=env)
except subprocess.CalledProcessError:
outcom... |
8c7de9c87412725c325f849f995df3010f36d5b2 | openmm/run_test.py | openmm/run_test.py | #!/usr/bin/env python
from simtk import openmm
# Check major version number
assert openmm.Platform.getOpenMMVersion() == '7.0', "openmm.Platform.getOpenMMVersion() = %s" % openmm.Platform.getOpenMMVersion()
# Check git hash
assert openmm.version.git_revision == '5e86c4f76cb8e40e026cc78cdc452cc378151705', "openmm.ver... | #!/usr/bin/env python
from simtk import openmm
# Check major version number
assert openmm.Platform.getOpenMMVersion() == '7.1', "openmm.Platform.getOpenMMVersion() = %s" % openmm.Platform.getOpenMMVersion()
# Check git hash
assert openmm.version.git_revision == '1e5b258c0df6ab8b4350fd2c3cbf6c6f7795847c', "openmm.ver... | Update openmm test script to check appropriate version numbers for beta | Update openmm test script to check appropriate version numbers for beta
| Python | mit | peastman/conda-recipes,swails/conda-recipes,cwehmeyer/conda-recipes,swails/conda-recipes,jchodera/conda-recipes,omnia-md/conda-recipes,peastman/conda-recipes,swails/conda-recipes,omnia-md/conda-recipes,cwehmeyer/conda-recipes,cwehmeyer/conda-recipes,omnia-md/conda-recipes,jchodera/conda-recipes,jchodera/conda-recipes,p... | ---
+++
@@ -3,7 +3,7 @@
from simtk import openmm
# Check major version number
-assert openmm.Platform.getOpenMMVersion() == '7.0', "openmm.Platform.getOpenMMVersion() = %s" % openmm.Platform.getOpenMMVersion()
+assert openmm.Platform.getOpenMMVersion() == '7.1', "openmm.Platform.getOpenMMVersion() = %s" % openmm.... |
b36da5a46137fc1d6fdad4a2ffbb62ad8a284046 | comics/comics/sequentialart.py | comics/comics/sequentialart.py | from comics.aggregator.crawler import CrawlerBase, CrawlerImage
from comics.core.comic_data import ComicDataBase
class ComicData(ComicDataBase):
name = "Sequential Art"
language = "en"
url = "http://www.collectedcurios.com/"
start_date = "2005-06-13"
rights = "Phillip M. Jackson"
class Crawler(C... | from comics.aggregator.crawler import CrawlerBase, CrawlerImage
from comics.core.comic_data import ComicDataBase
class ComicData(ComicDataBase):
name = "Sequential Art"
language = "en"
url = "http://www.collectedcurios.com/"
start_date = "2005-06-13"
rights = "Phillip M. Jackson"
class Crawler(C... | Update "Sequential Art" after site change | Update "Sequential Art" after site change
| Python | agpl-3.0 | datagutten/comics,jodal/comics,datagutten/comics,datagutten/comics,jodal/comics,jodal/comics,datagutten/comics,jodal/comics | ---
+++
@@ -18,5 +18,5 @@
page = self.parse_page(
"http://www.collectedcurios.com/sequentialart.php"
)
- url = page.src("img#strip")
+ url = page.src("img.w3-image")
return CrawlerImage(url) |
4026ee18f512d445a57413b65b7a29f965ededf4 | domino/utils/jupyter.py | domino/utils/jupyter.py | # Author: Álvaro Parafita (parafita.alvaro@gmail.com)
"""
Utilities for Jupyter Notebooks
"""
# Add parent folder to path and change dir to it
# so that we can access easily to all code and data in that folder
import sys
import os
import os.path
def notebook_init():
"""
Assuming a project is built ... | # Author: Álvaro Parafita (parafita.alvaro@gmail.com)
"""
Utilities for Jupyter Notebooks
"""
# Add parent folder to path and change dir to it
# so that we can access easily to all code and data in that folder
import sys
import os
import os.path
def notebook_init(path=os.path.pardir):
"""
Assuming ... | Add path parameter to notebook_init() | Add path parameter to notebook_init()
| Python | mit | aparafita/domino | ---
+++
@@ -12,7 +12,7 @@
import os.path
-def notebook_init():
+def notebook_init(path=os.path.pardir):
"""
Assuming a project is built in a root folder
with a notebooks subfolder where all .ipynb files are located,
@@ -24,5 +24,5 @@
"""
if os.path.split(os.path.abspath(os.pat... |
8a4897fc9cb0192ed91f4e63dbe2da37f4d3ec69 | xerox/__init__.py | xerox/__init__.py | from .core import *
import sys
def main():
""" Entry point for cli. """
if sys.argv[1:]: # called with input arguments
copy(' '.join(sys.argv[1:]))
elif not sys.stdin.isatty(): # piped in input
copy('\n'.join(sys.stdin.readlines()))
else: # paste output
print(paste())
| from .core import *
import sys
import os
def main():
""" Entry point for cli. """
if sys.argv[1:]: # called with input arguments
copy(' '.join(sys.argv[1:]))
elif not sys.stdin.isatty(): # piped in input
copy(''.join(sys.stdin.readlines()).rstrip(os.linesep))
else: # paste output
... | Join lines without newline and remove trailing newline | Join lines without newline and remove trailing newline
| Python | mit | kennethreitz/xerox | ---
+++
@@ -1,12 +1,13 @@
from .core import *
import sys
+import os
def main():
""" Entry point for cli. """
if sys.argv[1:]: # called with input arguments
copy(' '.join(sys.argv[1:]))
elif not sys.stdin.isatty(): # piped in input
- copy('\n'.join(sys.stdin.readlines()))
+ ... |
61f06da13bef77f576a0c2dea77febf0d2d4b6fb | subl.py | subl.py | from .dependencies import dependencies
dependencies.load()
import sublime, sublime_plugin
from sublime import Region
import subl_source_kitten
# Sublime Text will will call `on_query_completions` itself
class SublCompletions(sublime_plugin.EventListener):
def on_query_completions(self, view, prefix, locations):
... | from .dependencies import dependencies
dependencies.load()
import sublime, sublime_plugin
from sublime import Region
import subl_source_kitten
# Sublime Text will will call `on_query_completions` itself
class SublCompletions(sublime_plugin.EventListener):
def on_query_completions(self, view, prefix, locations):
... | Allow autocomplete on non-persisted swift files | Allow autocomplete on non-persisted swift files
| Python | mit | Dan2552/SourceKittenSubl,Dan2552/SourceKittenSubl,Dan2552/SourceKittenSubl | ---
+++
@@ -10,8 +10,10 @@
def on_query_completions(self, view, prefix, locations):
offset = locations[0]
file = view.file_name()
- if not file.endswith(".swift"):
+
+ if file != None and not file.endswith(".swift"):
return None
+
project_directory = view.win... |
8178bf161d39976405690d68d9ffe6c4dfd9d705 | web/view_athena/views.py | web/view_athena/views.py | from django.shortcuts import render
from elasticsearch import Elasticsearch
from django.http import HttpResponse
def search(request):
if request.method == 'GET':
term = request.GET.get('term_search')
if term == None:
term = ""
response = search_term(term)
pages = []
... | from django.shortcuts import render
from elasticsearch import Elasticsearch
from django.http import HttpResponse
def search(request):
if request.method == 'GET':
term = request.GET.get('term_search')
if term == None:
term = ""
response = search_term(term)
pages = []
... | Update 'search_term' functon. Add 'match_phrase' function. | Update 'search_term' functon. Add 'match_phrase' function.
| Python | mit | pattyvader/athena,pattyvader/athena,pattyvader/athena | ---
+++
@@ -21,8 +21,8 @@
def search_term(term):
es = Elasticsearch()
- res = es.search(index="athena", body={"query": {"bool": {"should": [ { "match": { "title": "\"" + str(term) + "\"" }},
- { "match": { "text": "\"" + str(term) + "\... |
82954f3df7e3b8f0a4cb921e40f351938451221d | cd/lambdas/pipeline-fail-notification/lambda_function.py | cd/lambdas/pipeline-fail-notification/lambda_function.py | # Invoked by: CloudWatch Events
# Returns: Error or status message
#
# Triggered periodically to check if the CD CodePipeline has failed, and
# publishes a notification
import boto3
import traceback
import json
import os
from datetime import datetime, timedelta
code_pipeline = boto3.client('codepipeline')
sns = boto3... | # Invoked by: CloudWatch Events
# Returns: Error or status message
#
# Triggered periodically to check if the CD CodePipeline has failed, and
# publishes a notification
import boto3
import traceback
import json
import os
from datetime import datetime, timedelta
code_pipeline = boto3.client('codepipeline')
sns = boto3... | Fix CD fail lambda python | Fix CD fail lambda python
| Python | mit | PRX/Infrastructure,PRX/Infrastructure,PRX/Infrastructure,PRX/Infrastructure,PRX/Infrastructure | ---
+++
@@ -23,19 +23,21 @@
try:
print('Checking pipeline state...')
- period_start = datetime.now() - timedelta(seconds=60)
-
pipeline_name = os.environ['PIPELINE_NAME']
pipeline_state = code_pipeline.get_pipeline_state(name=pipeline_name)
for stage_state in pipe... |
0fda3b2dc23c99bca856336504b961841faa1e51 | dashing/utils.py | dashing/utils.py | from django.conf.urls import url
from .views import Dashboard
class Router(object):
def __init__(self):
self.registry = []
def register(self, widget, basename, **parameters):
""" Register a widget, URL basename and any optional URL parameters.
Parameters are passed as keyword argumen... | from django.conf.urls import url
from .views import Dashboard
class Router(object):
def __init__(self):
self.registry = []
def register(self, widget, basename, **parameters):
""" Register a widget, URL basename and any optional URL parameters.
Parameters are passed as keyword argumen... | Fix typo in named group regex | Fix typo in named group regex
| Python | bsd-3-clause | talpor/django-dashing,swiftstack/django-dashing,talpor/django-dashing,quevedin/django-dashing,mverteuil/django-dashing,luto/django-dashing,quevedin/django-dashing,swiftstack/django-dashing,swiftstack/django-dashing,torstenfeld/django-dashing,torstenfeld/django-dashing,torstenfeld/django-dashing,mverteuil/django-dashing... | ---
+++
@@ -27,7 +27,7 @@
urlpatterns += [
url(r'/'.join((
r'^widgets/{}'.format(basename),
- r'/'.join((r'(P<{}>{})'.format(parameter, regex)
+ r'/'.join((r'(?P<{}>{})'.format(parameter, regex)
fo... |
daf580996210b562d78264db1e74a698d9937c40 | __init__.py | __init__.py | from __future__ import absolute_import, division, print_function
import logging
import sys
import warnings
if sys.version_info.major == 2:
warnings.warn(
"Python 2 is no longer fully supported. Please consider using the DIALS 2.2 release branch. "
"For more information on Python 2.7 support please... | from __future__ import absolute_import, division, print_function
import logging
import sys
import warnings
if sys.version_info.major == 2:
warnings.warn(
"Python 2 is no longer fully supported. Please consider using the DIALS 2.2 release branch. "
"For more information on Python 2.7 support please... | Make anyone importing DIALS aware of !2.7 support | Make anyone importing DIALS aware of !2.7 support
Warning is only shown on first import, and can be silenced in Python 2.7 with
import warnings
with warnings.catch_warnings():
warnings.simplefilter("ignore")
import dials
cf. #1175
| Python | bsd-3-clause | dials/dials,dials/dials,dials/dials,dials/dials,dials/dials | ---
+++
@@ -8,7 +8,7 @@
warnings.warn(
"Python 2 is no longer fully supported. Please consider using the DIALS 2.2 release branch. "
"For more information on Python 2.7 support please go to https://github.com/dials/dials/issues/1175.",
- DeprecationWarning,
+ UserWarning,
)
... |
3c603b177713e8266eb4881d5d325c148d3fb6c1 | __init__.py | __init__.py | # -*- coding: utf-8 -*-
__about__ = """
This project comes with the bare minimum set of applications and templates
to get you started. It includes no extra tabs, only the profile and notices
tabs are included by default. From here you can add any extra functionality
and applications that you would like.
"""
| # -*- coding: utf-8 -*-
__about__ = """
Django Packages is a directory of reusable apps, sites, tools, and more for your Django projects.
"""
| Update to be about Django, not 2010-era Pinax. | Update to be about Django, not 2010-era Pinax. | Python | mit | pydanny/djangopackages,pydanny/djangopackages,QLGu/djangopackages,nanuxbe/djangopackages,nanuxbe/djangopackages,QLGu/djangopackages,pydanny/djangopackages,QLGu/djangopackages,nanuxbe/djangopackages | ---
+++
@@ -1,8 +1,5 @@
# -*- coding: utf-8 -*-
__about__ = """
-This project comes with the bare minimum set of applications and templates
-to get you started. It includes no extra tabs, only the profile and notices
-tabs are included by default. From here you can add any extra functionality
-and applications th... |
59f878ed07dadf0ebc4a8f5fd23412ef21288b2a | __init__.py | __init__.py | import os
from flask import Flask, render_template, url_for
app = Flask(__name__)
@app.route('/')
def homepage():
viewer = 'clinician'
description = 'This is the clinician version.'
return render_template('index.html', viewer=viewer, description=description)
@app.route('/patient')
def patientpage():
viewer = 'p... | from __future__ import print_function
import os
from flask import Flask, render_template, url_for
app = Flask(__name__)
@app.route('/')
def homepage():
viewer = 'clinician'
description = 'This is the clinician version.'
return render_template('index.html', viewer=viewer, description=description)
@app.route('/pat... | Fix debugger start up issue + Add python3 print syntax | Fix debugger start up issue + Add python3 print syntax
| Python | mit | daviszhou/ascvd-webapp,daviszhou/ascvd-webapp,daviszhou/ascvd-webapp | ---
+++
@@ -1,5 +1,7 @@
+from __future__ import print_function
import os
from flask import Flask, render_template, url_for
+
app = Flask(__name__)
@app.route('/')
@@ -24,6 +26,5 @@
return render_template('about.html', viewer=viewer)
if __name__ == '__main__':
- port = int(os.environ.get('PORT', 5010))
- ap... |
db078d7332acf3032346b6642061c6f72c5dce1b | wooey/migrations/0028_add_script_subparser.py | wooey/migrations/0028_add_script_subparser.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2017-04-25 09:25
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import wooey.models.mixins
def createParsers(apps, schema_editor):
ScriptParameter = apps.get_model('wooey', 'ScriptParameter')... | # -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2017-04-25 09:25
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import wooey.models.mixins
class Migration(migrations.Migration):
dependencies = [
('wooey', '0027_parameter_order'),
... | Remove runpython to create subparers in 0028 | Remove runpython to create subparers in 0028
| Python | bsd-3-clause | wooey/Wooey,wooey/Wooey,wooey/Wooey,wooey/Wooey | ---
+++
@@ -5,17 +5,6 @@
from django.db import migrations, models
import django.db.models.deletion
import wooey.models.mixins
-
-
-def createParsers(apps, schema_editor):
- ScriptParameter = apps.get_model('wooey', 'ScriptParameter')
- ScriptParser = apps.get_model('wooey', 'ScriptParser')
-
- for param i... |
a9059f075bc1bb48422a3aba564a38071b1acf9f | selectable/forms/base.py | selectable/forms/base.py | from django import forms
from django.conf import settings
__all__ = ('BaseLookupForm', )
class BaseLookupForm(forms.Form):
term = forms.CharField(required=False)
limit = forms.IntegerField(required=False, min_value=1)
def clean_limit(self):
"Ensure given limit is less than default if defined"
... | from django import forms
from django.conf import settings
__all__ = ('BaseLookupForm', )
class BaseLookupForm(forms.Form):
term = forms.CharField(required=False)
limit = forms.IntegerField(required=False, min_value=1)
page = forms.IntegerField(required=False, min_value=1)
def clean_limit(self):
... | Move page cleaning logic to the form. | Move page cleaning logic to the form.
--HG--
branch : result-refactor
| Python | bsd-2-clause | mlavin/django-selectable,makinacorpus/django-selectable,affan2/django-selectable,affan2/django-selectable,mlavin/django-selectable,affan2/django-selectable,mlavin/django-selectable,makinacorpus/django-selectable | ---
+++
@@ -8,6 +8,7 @@
class BaseLookupForm(forms.Form):
term = forms.CharField(required=False)
limit = forms.IntegerField(required=False, min_value=1)
+ page = forms.IntegerField(required=False, min_value=1)
def clean_limit(self):
"Ensure given limit is less than default if defined"
@@... |
e4509d98e1aeb8a053bb4589eb6806d3e554af5e | topics/lemmatize_folder.py | topics/lemmatize_folder.py | import os
import sys
import re
import subprocess
def lemmatize( text ):
text = text.encode('utf8')
text = re.sub( '[\.,?!:;]' , '' , text )
out = subprocess.check_output( 'module load finnish-process; echo "' + text + '" | finnish-process', shell = True)
lemma = ''
for line in out.split('\n'):
... | import os
import sys
import re
import subprocess
def lemmatize( text ):
text = text.encode('utf8')
text = re.sub( '[\.,?!:;]' , '' , text )
out = subprocess.check_output( 'module load finnish-process; echo "' + text + '" | finnish-process', shell = True)
lemma = ''
for line in out.split('\n'):
... | Add possibility to lemmatize a folder or a file | Add possibility to lemmatize a folder or a file
| Python | mit | HIIT/digivaalit-2015,HIIT/digivaalit-2015,HIIT/digivaalit-2015 | ---
+++
@@ -20,11 +20,10 @@
return lemma
-## folder usecase
-path = sys.argv[1]
-for file in os.listdir( path ):
+## read a file and lemmatize it
+def file( path ):
- text = open( path + file )
+ text = open( path )
text = text.readlines()
text = map( lambda x: x.strip(), text )
text =... |
793dd2c1ec3d503b8d4325d44bd34b121273144c | jesusmtnez/python/koans/koans/triangle.py | jesusmtnez/python/koans/koans/triangle.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Triangle Project Code.
# Triangle analyzes the lengths of the sides of a triangle
# (represented by a, b and c) and returns the type of triangle.
#
# It returns:
# 'equilateral' if all sides are equal
# 'isosceles' if exactly 2 sides are equal
# 'scalene' ... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Triangle Project Code.
# Triangle analyzes the lengths of the sides of a triangle
# (represented by a, b and c) and returns the type of triangle.
#
# It returns:
# 'equilateral' if all sides are equal
# 'isosceles' if exactly 2 sides are equal
# 'scalene' ... | Complete 'About Triangle Project' koans | [Python] Complete 'About Triangle Project' koans
| Python | mit | JesusMtnez/devexperto-challenge,JesusMtnez/devexperto-challenge | ---
+++
@@ -18,7 +18,13 @@
#
def triangle(a, b, c):
# DELETE 'PASS' AND WRITE THIS CODE
- pass
+ # pass
+ if a == b == c:
+ return 'equilateral'
+ elif a == b or a == c or b == c:
+ return 'isosceles'
+ else:
+ return 'scalene'
# Error class used in part 2. No need to ch... |
31b70c6b08eedc1773d4993e9d9d420d84197b49 | corehq/apps/domain/__init__.py | corehq/apps/domain/__init__.py | from django.conf import settings
from corehq.preindex import ExtraPreindexPlugin
ExtraPreindexPlugin.register('domain', __file__, (
settings.NEW_DOMAINS_DB,
settings.NEW_USERS_GROUPS_DB,
settings.NEW_FIXTURES_DB,
'meta',
))
SHARED_DOMAIN = "<shared>"
UNKNOWN_DOMAIN = "<unknown>"
| SHARED_DOMAIN = "<shared>"
UNKNOWN_DOMAIN = "<unknown>"
| Remove domain design doc from irrelevant couch dbs | Remove domain design doc from irrelevant couch dbs
It used to contain views that were relevant to users, fixtures, and meta dbs,
but these have since been removed. Currently all views in the domain design doc
emit absolutely nothing in those domains
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq | ---
+++
@@ -1,13 +1,2 @@
-from django.conf import settings
-
-from corehq.preindex import ExtraPreindexPlugin
-
-ExtraPreindexPlugin.register('domain', __file__, (
- settings.NEW_DOMAINS_DB,
- settings.NEW_USERS_GROUPS_DB,
- settings.NEW_FIXTURES_DB,
- 'meta',
-))
-
SHARED_DOMAIN = "<shared>"
UNKNOWN_DO... |
818985feafcb0ce2b90dccaa41f6443c27bc1090 | django_enumfield/tests/test_validators.py | django_enumfield/tests/test_validators.py | import unittest
from django.db import models
from django_enumfield.exceptions import InvalidStatusOperationError
from django_enumfield.tests.models import BeerStyle, Person, PersonStatus
from django_enumfield.validators import validate_available_choice
class ValidatorTest(unittest.TestCase):
def test_validate_a... | import unittest
from django.db import models
from django_enumfield.exceptions import InvalidStatusOperationError
from django_enumfield.tests.models import BeerStyle, Person, PersonStatus
from django_enumfield.validators import validate_available_choice
class ValidatorTest(unittest.TestCase):
def test_validate_a... | Fix simple typo, convertable -> convertible | docs: Fix simple typo, convertable -> convertible
There is a small typo in django_enumfield/tests/test_validators.py.
Should read `convertible` rather than `convertable`.
| Python | mit | 5monkeys/django-enumfield | ---
+++
@@ -9,7 +9,7 @@
class ValidatorTest(unittest.TestCase):
def test_validate_available_choice_1(self):
- """Test passing a value non convertable to an int raises an
+ """Test passing a value non convertible to an int raises an
InvalidStatusOperationError
"""
self.... |
b8594bbe5375e20503d641dde8c4c0ef2cd85d3e | spec_cleaner/fileutils.py | spec_cleaner/fileutils.py | # vim: set ts=4 sw=4 et: coding=UTF-8
import os
from .rpmexception import RpmException
class FileUtils(object):
"""
Class working with file operations.
Read/write..
"""
# file variable
f = None
def open_datafile(self, name):
"""
Function to open data files.
Use... | # vim: set ts=4 sw=4 et: coding=UTF-8
import os
from .rpmexception import RpmException
class FileUtils(object):
"""
Class working with file operations.
Read/write..
"""
# file variable
f = None
def open_datafile(self, name):
"""
Function to open data files.
Use... | Check an extra possible data dir when installing in a venv | Check an extra possible data dir when installing in a venv
When installing spec-cleaner in a virtual env, the data files
(i.e. "excludes-bracketing.txt") are available in a different
directory. Also check this directory.
Fixes #128
| Python | bsd-3-clause | plusky/spec-cleaner,plusky/spec-cleaner,plusky/spec-cleaner,plusky/spec-cleaner,plusky/spec-cleaner | ---
+++
@@ -22,13 +22,19 @@
"""
try:
+ # the .. is appended as we are in spec_cleaner sub_folder
_file = open('{0}/../data/{1}'.format(os.path.dirname(os.path.realpath(__file__)), name), 'r')
except IOError:
- # the .. is appended as we are in spec_clean... |
7ab08a4524e7ed4dd0d465a7ad68e7802beebd2f | libs/globalvars.py | libs/globalvars.py | import os
import re
import sublime
from .logger import *
# get the directory path to this file;
LIBS_DIR = os.path.dirname(os.path.abspath(__file__))
PLUGIN_DIR = os.path.dirname(LIBS_DIR)
PACKAGES_DIR = os.path.dirname(PLUGIN_DIR)
PLUGIN_NAME = os.path.basename(PLUGIN_DIR)
# only Sublime Text 3 build after 3072 s... | import os
import re
import sublime
from .logger import *
# get the directory path to this file;
LIBS_DIR = os.path.dirname(os.path.abspath(__file__))
PLUGIN_DIR = os.path.dirname(LIBS_DIR)
PACKAGES_DIR = os.path.dirname(PLUGIN_DIR)
PLUGIN_NAME = os.path.basename(PLUGIN_DIR)
# only Sublime Text 3 build after 3072 s... | Change the console log level back to WARN | Change the console log level back to WARN
| Python | apache-2.0 | zhengbli/TypeScript-Sublime-Plugin,fongandrew/TypeScript-Sublime-JSX-Plugin,hoanhtien/TypeScript-Sublime-Plugin,Microsoft/TypeScript-Sublime-Plugin,hoanhtien/TypeScript-Sublime-Plugin,Microsoft/TypeScript-Sublime-Plugin,RyanCavanaugh/TypeScript-Sublime-Plugin,Microsoft/TypeScript-Sublime-Plugin,zhengbli/TypeScript-Subl... | ---
+++
@@ -22,7 +22,7 @@
# set logging levels
LOG_FILE_LEVEL = logging.WARN
-LOG_CONSOLE_LEVEL = logging.DEBUG
+LOG_CONSOLE_LEVEL = logging.WARN
NON_BLANK_LINE_PATTERN = re.compile("[\S]+")
VALID_COMPLETION_ID_PATTERN = re.compile("[a-zA-Z_$\.][\w$\.]*\Z") |
e0707619ca9192544a912b91993f0de5c507d7d7 | stutuz/__init__.py | stutuz/__init__.py | #-*- coding:utf-8 -*-
from __future__ import division
from __future__ import absolute_import
from __future__ import with_statement
from __future__ import print_function
from __future__ import unicode_literals
from logbook import Logger, NestedSetup
from flask import Flask
from flaskext.genshi import Genshi
from flask... | #-*- coding:utf-8 -*-
from __future__ import division
from __future__ import absolute_import
from __future__ import with_statement
from __future__ import print_function
from __future__ import unicode_literals
from logbook import Logger, NestedSetup
from flask import Flask
from flaskext.genshi import Genshi
from flask... | Make a default empty users list | Make a default empty users list
| Python | bsd-2-clause | dag/stutuz | ---
+++
@@ -11,6 +11,8 @@
from flaskext.genshi import Genshi
from flaskext.zodb import ZODB, PersistentMapping
+from stutuz.models import Users
+
logger = Logger(__name__)
genshi = Genshi()
@@ -22,6 +24,8 @@
if 'languages' not in root:
root['languages'] = PersistentMapping({'eng': 'English',
... |
295285a0a13207dac276da6e3b41e2057a7efee8 | test/tests/constant_damper_test/constant_damper_test.py | test/tests/constant_damper_test/constant_damper_test.py | import tools
def testdirichlet(dofs=0, np=0, n_threads=0):
tools.executeAppAndDiff(__file__,'constant_damper_test.i',['out.e'], dofs, np, n_threads)
| import tools
def testdamper(dofs=0, np=0, n_threads=0):
tools.executeAppAndDiff(__file__,'constant_damper_test.i',['out.e'], dofs, np, n_threads)
# Make sure the damping causes 8 NL steps
def testverifydamping(dofs=0, np=0, n_threads=0):
tools.executeAppExpectError(__file__,'constant_damper_test.i','NL step\s+8')... | Verify additional steps in damping problem | Verify additional steps in damping problem
r4199
| Python | lgpl-2.1 | jinmm1992/moose,stimpsonsg/moose,andrsd/moose,mellis13/moose,jinmm1992/moose,permcody/moose,liuwenf/moose,harterj/moose,jhbradley/moose,nuclear-wizard/moose,jhbradley/moose,adamLange/moose,roystgnr/moose,SudiptaBiswas/moose,katyhuff/moose,harterj/moose,roystgnr/moose,zzyfisherman/moose,roystgnr/moose,jasondhales/moose,... | ---
+++
@@ -1,4 +1,8 @@
import tools
-def testdirichlet(dofs=0, np=0, n_threads=0):
+def testdamper(dofs=0, np=0, n_threads=0):
tools.executeAppAndDiff(__file__,'constant_damper_test.i',['out.e'], dofs, np, n_threads)
+
+# Make sure the damping causes 8 NL steps
+def testverifydamping(dofs=0, np=0, n_threads=0)... |
d1ab1b7e7edf74f89274e48718fac0b6ac6d191d | dthm4kaiako/config/__init__.py | dthm4kaiako/config/__init__.py | """Configuration for Django system."""
__version__ = "0.14.0"
__version_info__ = tuple(
[
int(num) if num.isdigit() else num
for num in __version__.replace("-", ".", 1).split(".")
]
)
| """Configuration for Django system."""
__version__ = "0.14.1"
__version_info__ = tuple(
[
int(num) if num.isdigit() else num
for num in __version__.replace("-", ".", 1).split(".")
]
)
| Increment version number to 0.14.1 | Increment version number to 0.14.1
| Python | mit | uccser/cs4teachers,uccser/cs4teachers,uccser/cs4teachers,uccser/cs4teachers | ---
+++
@@ -1,6 +1,6 @@
"""Configuration for Django system."""
-__version__ = "0.14.0"
+__version__ = "0.14.1"
__version_info__ = tuple(
[
int(num) if num.isdigit() else num |
dab9d4e071bef5e0a771fa5a0eb7be81819bb68c | user_profile/urls.py | user_profile/urls.py | from django.conf.urls import include, url
from django.contrib import admin
from . import views
urlpatterns = [
url(r'^$', views.ViewView.as_view(), name='profile_own_view'),
url(r'^edit/', views.EditView.as_view(), name='profile_edit'),
url(r'^view/', views.ViewView.as_view(), name='profile_own_view'),
... | from django.conf.urls import include, url
from django.contrib import admin
from . import views
urlpatterns = [
url(r'^$', views.ViewView.as_view(), name='profile_own_view'),
url(r'^edit/', views.EditView.as_view(), name='profile_edit'),
url(r'^view/', views.ViewView.as_view(), name='profile_own_view'),
... | Fix user name url pattern | Fix user name url pattern
| Python | mit | DeWaster/Tviserrys,DeWaster/Tviserrys | ---
+++
@@ -7,6 +7,6 @@
url(r'^$', views.ViewView.as_view(), name='profile_own_view'),
url(r'^edit/', views.EditView.as_view(), name='profile_edit'),
url(r'^view/', views.ViewView.as_view(), name='profile_own_view'),
- url(r'^view/(?P<user_name>\d+)/$', views.ViewView.as_view(), name='profile_view')... |
bb2249998637c8c56cb8b7cd119c1d8d132e522e | viewer_examples/plugins/canny_simple.py | viewer_examples/plugins/canny_simple.py | from skimage import data
from skimage.filter import canny
from skimage.viewer import ImageViewer
from skimage.viewer.widgets import Slider
from skimage.viewer.plugins.overlayplugin import OverlayPlugin
image = data.camera()
# Note: ImageViewer must be called before Plugin b/c it starts the event loop.
viewer = Image... | from skimage import data
from skimage.filter import canny
from skimage.viewer import ImageViewer
from skimage.viewer.widgets import Slider
from skimage.viewer.widgets.history import SaveButtons
from skimage.viewer.plugins.overlayplugin import OverlayPlugin
image = data.camera()
# You can create a UI for a filter ju... | Add save buttons to viewer example. | Add save buttons to viewer example.
| Python | bsd-3-clause | jwiggins/scikit-image,WarrenWeckesser/scikits-image,rjeli/scikit-image,almarklein/scikit-image,michaelaye/scikit-image,newville/scikit-image,Britefury/scikit-image,blink1073/scikit-image,pratapvardhan/scikit-image,ClinicalGraphics/scikit-image,pratapvardhan/scikit-image,dpshelio/scikit-image,chintak/scikit-image,almark... | ---
+++
@@ -3,18 +3,22 @@
from skimage.viewer import ImageViewer
from skimage.viewer.widgets import Slider
+from skimage.viewer.widgets.history import SaveButtons
from skimage.viewer.plugins.overlayplugin import OverlayPlugin
image = data.camera()
-# Note: ImageViewer must be called before Plugin b/c it sta... |
7cf867e9ee7a3764b3168cd9671f6de0d0b1b090 | numpy/distutils/command/install_clib.py | numpy/distutils/command/install_clib.py | import os
from distutils.core import Command
from numpy.distutils.misc_util import get_cmd
class install_clib(Command):
description = "Command to install installable C libraries"
user_options = []
def initialize_options(self):
self.install_dir = None
self.outfiles = []
def finalize_o... | import os
from distutils.core import Command
from distutils.ccompiler import new_compiler
from numpy.distutils.misc_util import get_cmd
class install_clib(Command):
description = "Command to install installable C libraries"
user_options = []
def initialize_options(self):
self.install_dir = None
... | Move import at the top of module. | Move import at the top of module.
git-svn-id: 77a43f9646713b91fea7788fad5dfbf67e151ece@7278 94b884b6-d6fd-0310-90d3-974f1d3f35e1
| Python | bsd-3-clause | teoliphant/numpy-refactor,illume/numpy3k,Ademan/NumPy-GSoC,Ademan/NumPy-GSoC,teoliphant/numpy-refactor,chadnetzer/numpy-gaurdro,Ademan/NumPy-GSoC,jasonmccampbell/numpy-refactor-sprint,teoliphant/numpy-refactor,jasonmccampbell/numpy-refactor-sprint,illume/numpy3k,teoliphant/numpy-refactor,chadnetzer/numpy-gaurdro,illume... | ---
+++
@@ -1,5 +1,6 @@
import os
from distutils.core import Command
+from distutils.ccompiler import new_compiler
from numpy.distutils.misc_util import get_cmd
class install_clib(Command):
@@ -16,7 +17,6 @@
def run (self):
# We need the compiler to get the library name -> filename association
-... |
7ca3b7f294b954dcd95880c938709240b268766f | test_url_runner.py | test_url_runner.py | #!/usr/bin/env python
import unittest
# This line is important so flake8 must ignore this one
from app import views # flake8: noqa
from app import mulungwishi_app
class URLTest(unittest.TestCase):
def setUp(self):
self.client = mulungwishi_app.test_client()
self.client.testing = True
def te... | #!/usr/bin/env python
import unittest
# This line is important so flake8 must ignore this one
from app import views # flake8: noqa
from app import mulungwishi_app
class URLTest(unittest.TestCase):
def setUp(self):
self.client = mulungwishi_app.test_client()
self.client.testing = True
def te... | Add test for empty content string on query | Add test for empty content string on query
| Python | mit | engagespark/public-webhooks,engagespark/mulungwishi-webhook,engagespark/mulungwishi-webhook,admiral96/public-webhooks,engagespark/public-webhooks,admiral96/public-webhooks,admiral96/mulungwishi-webhook,admiral96/mulungwishi-webhook | ---
+++
@@ -24,6 +24,10 @@
result = self.client.get('/query?content')
self.assertEqual(result.status_code, 400)
+ def test_invalid_query_no_value_assigned(self):
+ result = self.client.get('/query?content=')
+ self.assertEqual(result.status_code, 400)
+
def test_invalid_query... |
fdc7f2c88e72af6e6493a70dad7673c9dbfcbde2 | opps/images/templatetags/images_tags.py | opps/images/templatetags/images_tags.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django import template
from ..generate import image_url as url
register = template.Library()
@register.simple_tag
def image_url(image_url, **kwargs):
return url(image_url=image_url, **kwargs)
@register.simple_tag
def image_obj(image, **kwargs):
new = {}
... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django import template
from ..generate import image_url as url
register = template.Library()
@register.simple_tag
def image_url(image_url, **kwargs):
return url(image_url=image_url, **kwargs)
@register.simple_tag
def image_obj(image, **kwargs):
new = {}
... | Remove halign and valign on image_obj | Remove halign and valign on image_obj
| Python | mit | opps/opps,YACOWS/opps,jeanmask/opps,YACOWS/opps,jeanmask/opps,opps/opps,YACOWS/opps,YACOWS/opps,williamroot/opps,opps/opps,williamroot/opps,jeanmask/opps,williamroot/opps,williamroot/opps,opps/opps,jeanmask/opps | ---
+++
@@ -17,10 +17,12 @@
new = {}
new['flip'] = image.flip
new['flop'] = image.flop
+ """
if image.halign != "":
new['halign'] = image.halign
if image.valign != "":
new['valign'] = image.valign
+ """
new['fit_in'] = image.fit_in
new['smart'] = image.smart
... |
7aca9e8cb526e721b88958ddfeac492e667041c3 | breakpad.py | breakpad.py | # Copyright (c) 2009 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.
"""Breakpad for Python.
Sends a notification when a process stops on an exception."""
import atexit
import getpass
import urllib
import traceback
impor... | # Copyright (c) 2009 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.
"""Breakpad for Python.
Sends a notification when a process stops on an exception."""
import atexit
import getpass
import urllib
import traceback
impor... | Add a check so non-google employee don't send crash dumps. | Add a check so non-google employee don't send crash dumps.
Add a warning message in case the check ever fail.
Review URL: http://codereview.chromium.org/460044
git-svn-id: fd409f4bdeea2bb50a5d34bb4d4bfc2046a5a3dd@33700 0039d316-1c4b-4281-b951-d872f2087c98
| Python | bsd-3-clause | smikes/depot_tools,kromain/chromium-tools,coreos/depot_tools,Neozaru/depot_tools,G-P-S/depot_tools,fracting/depot_tools,kaiix/depot_tools,liaorubei/depot_tools,withtone/depot_tools,smikes/depot_tools,npe9/depot_tools,Neozaru/depot_tools,Phonebooth/depot_tools,cybertk/depot_tools,smikes/depot_tools,duanwujie/depot_tools... | ---
+++
@@ -10,30 +10,35 @@
import getpass
import urllib
import traceback
+import socket
import sys
def SendStack(stack, url='http://chromium-status.appspot.com/breakpad'):
print 'Do you want to send a crash report [y/N]? ',
- if sys.stdin.read(1).lower() == 'y':
- try:
- params = {
- 'a... |
a37288cb47ea7b5d547c7ed6b7b5aa28a6d9b583 | workflowmax/api.py | workflowmax/api.py | from .endpoints import ENDPOINTS
from .managers import Manager
class WorkflowMax:
"""An ORM-like interface to the WorkflowMax API"""
def __init__(self, credentials):
self.credentials = credentials
for k, v in ENDPOINTS.items():
setattr(self, v['plural'], Manager(k, credentials))
... | from .credentials import Credentials
from .endpoints import ENDPOINTS
from .managers import Manager
class WorkflowMax:
"""An ORM-like interface to the WorkflowMax API"""
def __init__(self, credentials):
if not isinstance(credentials, Credentials):
raise TypeError(
'Expecte... | Check credentials; sort repr output | Check credentials; sort repr output
| Python | bsd-3-clause | ABASystems/pyworkflowmax | ---
+++
@@ -1,3 +1,4 @@
+from .credentials import Credentials
from .endpoints import ENDPOINTS
from .managers import Manager
@@ -6,6 +7,12 @@
"""An ORM-like interface to the WorkflowMax API"""
def __init__(self, credentials):
+ if not isinstance(credentials, Credentials):
+ raise Typ... |
190463fb4538654a62b440fc92041383f8b15957 | helusers/migrations/0001_add_ad_groups.py | helusers/migrations/0001_add_ad_groups.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2017-05-12 08:07
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0001_initial'),
]
oper... | # -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2017-05-12 08:07
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0001_initial'),
]
oper... | Fix migration for model verbose name changes | Fix migration for model verbose name changes
| Python | bsd-2-clause | City-of-Helsinki/django-helusers,City-of-Helsinki/django-helusers | ---
+++
@@ -31,7 +31,7 @@
('group', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='ad_groups', to='auth.Group')),
],
options={
- 'verbose_name': 'AD Group Mapping',
+ 'verbose_name': 'AD group mapping', 'verbose_nam... |
083a8d4f301da2ad665a3fefd13a4381417b1205 | imageutils/normalization/tests/test_ui.py | imageutils/normalization/tests/test_ui.py | import numpy as np
from numpy.testing import assert_allclose
from ..ui import scale_image
DATA = np.array([0, 1., 2.])
DATASCL = 0.5 * DATA
class TestImageScaling(object):
def test_linear(self):
"""Test linear scaling."""
img = scale_image(DATA, scale='linear')
assert_allclose(img, ... | import numpy as np
from numpy.testing import assert_allclose
from ..ui import scale_image
DATA = np.array([0, 1., 2.])
DATASCL = 0.5 * DATA
class TestImageScaling(object):
def test_linear(self):
"""Test linear scaling."""
img = scale_image(DATA, scale='linear')
assert_allclose(img, DATA... | Add test for asinh in scale_image | Add test for asinh in scale_image
| Python | bsd-3-clause | mhvk/astropy,saimn/astropy,aleksandr-bakanov/astropy,pllim/astropy,astropy/astropy,tbabej/astropy,AustereCuriosity/astropy,StuartLittlefair/astropy,stargaser/astropy,dhomeier/astropy,dhomeier/astropy,MSeifert04/astropy,kelle/astropy,saimn/astropy,lpsinger/astropy,DougBurke/astropy,DougBurke/astropy,kelle/astropy,mhvk/a... | ---
+++
@@ -8,7 +8,7 @@
class TestImageScaling(object):
-
+
def test_linear(self):
"""Test linear scaling."""
img = scale_image(DATA, scale='linear')
@@ -30,3 +30,10 @@
img = scale_image(DATA, scale='log')
ref = np.log10(1000 * DATASCL + 1.0) / np.log10(1001.0)
... |
e94ab19902cebff55c2aead9697423c9c94e478f | scripts/indices.py | scripts/indices.py | # Indices that need to be added manually:
#
# invoke shell --no-transaction
from pymongo import ASCENDING, DESCENDING
db['nodelog'].create_index([
('__backrefs.logged.node.logs', ASCENDING),
])
db['user'].create_index([
('emails', ASCENDING),
])
db['user'].create_index([
('emails', ASCENDING),
('us... | # Indices that need to be added manually:
#
# invoke shell --no-transaction
from pymongo import ASCENDING, DESCENDING
db['user'].create_index([
('emails', ASCENDING),
])
db['user'].create_index([
('emails', ASCENDING),
('username', ASCENDING),
])
db['node'].create_index([
('is_deleted', ASCENDING),... | Remove index on field that no longer exists | Remove index on field that no longer exists
[skip ci]
| Python | apache-2.0 | samchrisinger/osf.io,Johnetordoff/osf.io,hmoco/osf.io,crcresearch/osf.io,wearpants/osf.io,Nesiehr/osf.io,SSJohns/osf.io,amyshi188/osf.io,erinspace/osf.io,acshi/osf.io,amyshi188/osf.io,DanielSBrown/osf.io,kwierman/osf.io,HalcyonChimera/osf.io,pattisdr/osf.io,doublebits/osf.io,hmoco/osf.io,chrisseto/osf.io,SSJohns/osf.io... | ---
+++
@@ -4,10 +4,6 @@
from pymongo import ASCENDING, DESCENDING
-
-db['nodelog'].create_index([
- ('__backrefs.logged.node.logs', ASCENDING),
-])
db['user'].create_index([
('emails', ASCENDING), |
4e7fb558ba6411a33e0e1a2feeffad4d8647e17d | scipy/fftpack/__init__.py | scipy/fftpack/__init__.py | #
# fftpack - Discrete Fourier Transform algorithms.
#
# Created: Pearu Peterson, August,September 2002
from info import __all__,__doc__
from fftpack_version import fftpack_version as __version__
from basic import *
from pseudo_diffs import *
from helper import *
from numpy.dual import register_func
for k in ['fft'... | #
# fftpack - Discrete Fourier Transform algorithms.
#
# Created: Pearu Peterson, August,September 2002
from info import __all__,__doc__
from fftpack_version import fftpack_version as __version__
from basic import *
from pseudo_diffs import *
from helper import *
from numpy.dual import register_func
for k in ['fft'... | Add dct and idct in scipy.fftpack namespace. | Add dct and idct in scipy.fftpack namespace.
| Python | bsd-3-clause | felipebetancur/scipy,piyush0609/scipy,mgaitan/scipy,Eric89GXL/scipy,vanpact/scipy,pschella/scipy,piyush0609/scipy,arokem/scipy,njwilson23/scipy,vberaudi/scipy,grlee77/scipy,minhlongdo/scipy,ales-erjavec/scipy,argriffing/scipy,rgommers/scipy,maniteja123/scipy,ilayn/scipy,endolith/scipy,endolith/scipy,petebachant/scipy,z... | ---
+++
@@ -16,6 +16,8 @@
register_func(k, eval(k))
del k, register_func
+from realtransforms import *
+__all__.extend(['dct', 'idct'])
from numpy.testing import Tester
test = Tester().test |
ad934e49a43a8340af9d52bbac86bede45d0e84d | aero/adapters/brew.py | aero/adapters/brew.py | # -*- coding: utf-8 -*-
__author__ = 'nickl-'
from aero.__version__ import __version__
from .base import BaseAdapter
class Brew(BaseAdapter):
"""
Homebrew adapter.
"""
def search(self, query):
response = self.command(['search', query])[0]
if 'No formula found' not in response and 'Err... | # -*- coding: utf-8 -*-
__author__ = 'nickl-'
from aero.__version__ import __version__
from .base import BaseAdapter
class Brew(BaseAdapter):
"""
Homebrew adapter.
"""
def search(self, query):
response = self.command(['search', query])[0]
if 'No formula found' not in response and 'Err... | Use aero info instead for caching info | Use aero info instead for caching info
Brew requires brew info for additional information. If we instead call aero info we can at least cache the info calls for later.
| Python | bsd-3-clause | Aeronautics/aero | ---
+++
@@ -14,23 +14,16 @@
if 'No formula found' not in response and 'Error:' not in response:
return dict([(
self.package_name(line),
- '\n'.join(map(
- lambda k: k[0] if len(k) < 2 else k[0] + ': ' + k[1],
- self.search_inf... |
42d1ac59a1e35d8efd4785939696adbdbf39e1d2 | alg_insertion_sort.py | alg_insertion_sort.py | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def insertion_sort(a_list):
"""Insertion Sort algortihm.
Time complexity: O(n^2).
"""
gen = ((i, v) for i, v in enumerate(a_list) if i > 0)
for (i, v) in gen:
key = i
while... | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def insertion_sort(a_list):
"""Insertion Sort algortihm.
Time complexity: O(n^2).
Although its complexity is bigger than the ones with O(n*logn),
one advantage is the sorting happens in plac... | Revise docstring by adding advantage | Revise docstring by adding advantage
| Python | bsd-2-clause | bowen0701/algorithms_data_structures | ---
+++
@@ -7,6 +7,9 @@
"""Insertion Sort algortihm.
Time complexity: O(n^2).
+
+ Although its complexity is bigger than the ones with O(n*logn),
+ one advantage is the sorting happens in place.
"""
gen = ((i, v) for i, v in enumerate(a_list) if i > 0)
for (i, v) in gen: |
2fdb78366fd8e785ec1c613fa4d2f87064217101 | organizer/views.py | organizer/views.py | from django.http.response import HttpResponse
from django.template import Context, loader
from .models import Tag
def homepage(request):
tag_list = Tag.objects.all()
template = loader.get_template(
'organizer/tag_list.html')
context = Context({'tag_list': tag_list})
output = template.render(c... | from django.http.response import HttpResponse
from django.template import Context, loader
from .models import Tag
def homepage(request):
tag_list = Tag.objects.all()
template = loader.get_template(
'organizer/tag_list.html')
context = Context({'tag_list': tag_list})
output = template.render(c... | Tag Detail: load and render template. | Ch05: Tag Detail: load and render template.
| Python | bsd-2-clause | jambonrose/DjangoUnleashed-1.8,jambonrose/DjangoUnleashed-1.8 | ---
+++
@@ -16,4 +16,7 @@
def tag_detail(request):
# slug = ?
tag = Tag.objects.get(slug__iexact=slug)
- return HttpResponse()
+ template = loader.get_template(
+ 'organizer/tag_detail.html')
+ context = Context({'tag': tag})
+ return HttpResponse(template.render(context)) |
b1242e9f84afb331f4a3426abeba8e5d27a563c7 | wafer/talks/admin.py | wafer/talks/admin.py | from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from wafer.talks.models import TalkType, Talk, TalkUrl
class ScheduleListFilter(admin.SimpleListFilter):
title = _('in schedule')
parameter_name = 'schedule'
def lookups(self, request, model_admin):
return (
... | from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from wafer.talks.models import TalkType, Talk, TalkUrl
class ScheduleListFilter(admin.SimpleListFilter):
title = _('in schedule')
parameter_name = 'schedule'
def lookups(self, request, model_admin):
return (
... | Fix logic error in schedule filter | Fix logic error in schedule filter
| Python | isc | CarlFK/wafer,CTPUG/wafer,CarlFK/wafer,CarlFK/wafer,CTPUG/wafer,CTPUG/wafer,CarlFK/wafer,CTPUG/wafer | ---
+++
@@ -16,7 +16,9 @@
def queryset(self, request, queryset):
if self.value() == 'in':
return queryset.filter(scheduleitem__isnull=False)
- return queryset.filter(scheduleitem__isnull=True)
+ elif self.value() == 'out':
+ return queryset.filter(scheduleitem__isnu... |
40dc1250bf73b54dfcf04c7a82c452a731aa363c | tests/unit/blocks/test_two_column_layout_block.py | tests/unit/blocks/test_two_column_layout_block.py | import mock
from django.test import TestCase
from django.template import RequestContext
from fancypages.models import Container
from fancypages.models.blocks import TwoColumnLayoutBlock
from fancypages.test import factories
class TestTwoColumnLayoutBlock(TestCase):
def setUp(self):
super(TestTwoColumn... | import mock
from django.test import TestCase
from django.template import RequestContext
from fancypages.models import Container
from fancypages.models.blocks import TwoColumnLayoutBlock
from fancypages.test import factories
class TestTwoColumnLayoutBlock(TestCase):
def setUp(self):
super(TestTwoColumn... | Fix mock of request for block rendering | Fix mock of request for block rendering
| Python | bsd-3-clause | socradev/django-fancypages,socradev/django-fancypages,tangentlabs/django-fancypages,tangentlabs/django-fancypages,socradev/django-fancypages,tangentlabs/django-fancypages | ---
+++
@@ -14,8 +14,10 @@
def setUp(self):
super(TestTwoColumnLayoutBlock, self).setUp()
self.user = factories.UserFactory.build()
+ self.request = mock.Mock()
+ self.request.META = {}
- self.request_context = RequestContext(mock.MagicMock())
+ self.request_contex... |
42f5854b7a9c97b95418d02cb055fc1a751ad112 | apps/fund/serializers.py | apps/fund/serializers.py | from apps.projects.serializers import ProjectSmallSerializer
from rest_framework import serializers
from rest_framework import relations
from rest_framework import fields
from .models import Donation, Order, OrderItem
class DonationSerializer(serializers.ModelSerializer):
project = relations.PrimaryKeyRelatedFiel... | from rest_framework import serializers
from rest_framework import relations
from rest_framework import fields
from .models import Donation, Order, OrderItem
class DonationSerializer(serializers.ModelSerializer):
project = relations.PrimaryKeyRelatedField(source='project')
status = fields.Field()
class Me... | Fix bug in sund serializer | Fix bug in sund serializer
| Python | bsd-3-clause | onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site | ---
+++
@@ -1,4 +1,3 @@
-from apps.projects.serializers import ProjectSmallSerializer
from rest_framework import serializers
from rest_framework import relations
from rest_framework import fields |
c18bcd5af7e0b1506ca28cd33a3c939efee80d00 | openfisca_web_api/loader/entities.py | openfisca_web_api/loader/entities.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function, division, absolute_import
from openfisca_core.commons import to_unicode
def build_entities(tax_benefit_system):
entities = {
entity.key: build_entity(entity)
for entity in tax_benefit_system.entities
}
re... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function, division, absolute_import
from openfisca_core.commons import to_unicode
def build_entities(tax_benefit_system):
entities = {
entity.key: build_entity(entity)
for entity in tax_benefit_system.entities
}
re... | Make variable names more explicit | Make variable names more explicit
| Python | agpl-3.0 | openfisca/openfisca-core,openfisca/openfisca-core | ---
+++
@@ -14,29 +14,29 @@
def build_entity(entity):
- entity_formated = {
+ formatted_entity = {
'plural': entity.plural,
- 'description': to_unicode(entity.doc)
+ 'description': to_unicode(entity.label),
+ 'documentation': to_unicode(entity.doc)
}
if hasattr(e... |
2c3c52a2ecdb4271cea4e8ec31410ef48be3c728 | admin/manage.py | admin/manage.py | from mailu import manager, db
from mailu.admin import models
from passlib import hash
@manager.command
def flushdb():
""" Flush the database
"""
db.drop_all()
@manager.command
def initdb():
""" Initialize the database
"""
db.create_all()
@manager.command
def admin(localpart, domain_name, p... | from mailu import manager, db
from mailu.admin import models
from passlib import hash
@manager.command
def flushdb():
""" Flush the database
"""
db.drop_all()
@manager.command
def initdb():
""" Initialize the database
"""
db.create_all()
@manager.command
def admin(localpart, domain_name, p... | Add method to create a normal user | Add method to create a normal user
| Python | mit | kaiyou/freeposte.io,kaiyou/freeposte.io,kaiyou/freeposte.io,kaiyou/freeposte.io | ---
+++
@@ -34,6 +34,22 @@
db.session.add(user)
db.session.commit()
+@manager.command
+def user(localpart, domain_name, password):
+ """ Create an user
+ """
+ domain = models.Domain.query.get(domain_name)
+ if not domain:
+ domain = models.Domain(name=domain_name)
+ db.session.a... |
375c55a085dce451146a10b66b3c2d54a9919ed4 | pipelines/toast_example_dist.py | pipelines/toast_example_dist.py |
import toast
# Split COMM_WORLD into groups of 4 processes each
cm = toast.Comm(world=MPI.COMM_WORLD, groupsize=4)
# Create the distributed data object
dd = toast.Data(comm=cm)
# Each process group appends some observations.
# For this example, each observation is going to have the same
# number of samples, and the... |
import mpi4py.MPI as MPI
import toast
# Split COMM_WORLD into groups of 4 processes each
cm = toast.Comm(world=MPI.COMM_WORLD, groupsize=4)
# Create the distributed data object
dd = toast.Data(comm=cm)
# Each process group appends some observations.
# For this example, each observation is going to have the same
# ... | Fix typo, even though this example is not used for anything. | Fix typo, even though this example is not used for anything.
| Python | bsd-2-clause | tskisner/pytoast,tskisner/pytoast | ---
+++
@@ -1,3 +1,5 @@
+
+import mpi4py.MPI as MPI
import toast
|
f5d07cbefa185d88cdc1bddc4338d6e0ef1e2648 | porick/lib/auth.py | porick/lib/auth.py | import bcrypt
import hashlib
from pylons import response, request, url, config
from pylons import tmpl_context as c
from pylons.controllers.util import redirect
import porick.lib.helpers as h
from porick.model import db, User
def authenticate(username, password):
user = db.query(User).filter(User.username == us... | import bcrypt
import hashlib
from pylons import response, request, url, config
from pylons import tmpl_context as c
from pylons.controllers.util import redirect
import porick.lib.helpers as h
from porick.model import db, User
def authenticate(username, password):
user = db.query(User).filter(User.username == us... | Clear cookies if someone's got dodgy cookie info | Clear cookies if someone's got dodgy cookie info
| Python | apache-2.0 | kopf/porick,kopf/porick,kopf/porick | ---
+++
@@ -13,10 +13,12 @@
user = db.query(User).filter(User.username == username).first()
if not user:
return False
- if bcrypt.hashpw(password, config['PASSWORD_SALT']) == user.password:
+ elif bcrypt.hashpw(password, config['PASSWORD_SALT']) == user.password:
set_auth_cookie(user... |
8ab4b4be97ca026946b30cba7fce64bb30edd28d | fskintra.py | fskintra.py | #! /usr/bin/env python
#
#
#
import skoleintra.config
import skoleintra.pgContactLists
import skoleintra.pgDialogue
import skoleintra.pgDocuments
import skoleintra.pgFrontpage
import skoleintra.pgWeekplans
import skoleintra.schildren
SKOLEBESTYELSE_NAME = 'Skolebestyrelsen'
cnames = skoleintra.schildren.skoleGetChil... | #! /usr/bin/env python
#
#
#
import skoleintra.config
import skoleintra.pgContactLists
import skoleintra.pgDialogue
import skoleintra.pgDocuments
import skoleintra.pgFrontpage
import skoleintra.pgWeekplans
import skoleintra.schildren
SKOLEBESTYELSE_NAME = 'Skolebestyrelsen'
cnames = skoleintra.schildren.skoleGetChil... | Use config.log for print added in last commit | Use config.log for print added in last commit
| Python | bsd-2-clause | bennyslbs/fskintra | ---
+++
@@ -15,7 +15,7 @@
cnames = skoleintra.schildren.skoleGetChildren()
if cnames.count(SKOLEBESTYELSE_NAME):
- print 'Ignorerer ['+SKOLEBESTYELSE_NAME+']'
+ config.log(u'Ignorerer ['+SKOLEBESTYELSE_NAME+']')
cnames.remove(SKOLEBESTYELSE_NAME)
for cname in cnames: |
e21ca71d5bf19ec0feaab9dbf8caf25173152aec | projects/models.py | projects/models.py | # -*- encoding:utf-8 -*-
from django.db import models
class Project(models.Model):
STATUS = (
('unrevised', u'Неразгледан'),
('returned', u'Върнат за корекция'),
('pending', u'Предстои да бъде разгледан на СИС'),
('approved', u'Разгледан и одобрен на СИС'),
('rejected', u'Р... | # -*- encoding:utf-8 -*-
from django.db import models
class Project(models.Model):
STATUS = (
('unrevised', u'Неразгледан'),
('returned', u'Върнат за корекция'),
('pending', u'Предстои да бъде разгледан на СИС'),
('approved', u'Разгледан и одобрен на СИС'),
('rejected', u'Р... | Rename the date field related to the project status | Rename the date field related to the project status
| Python | mit | Hackfmi/Diaphanum,Hackfmi/Diaphanum | ---
+++
@@ -26,7 +26,7 @@
status = models.CharField(max_length=50,
choices=STATUS,
default='unrevised')
- date = models.DateField(blank=True, null=True)
+ discussed_at = models.DateField(blank=True, null=True)
def __unicode__(self):
... |
c9b97f6d1148378d1ba7189a1838ea03e240de40 | pycron/__init__.py | pycron/__init__.py | from datetime import datetime
def _parse_arg(value, target, maximum):
if value == '*':
return True
if '/' in value:
value, interval = value.split('/')
if value != '*':
raise ValueError
interval = int(interval)
if interval not in range(0, maximum + 1):
... | from datetime import datetime
def _parse_arg(value, target, maximum):
if value == '*':
return True
if ',' in value:
if '*' in value:
raise ValueError
values = filter(None, [int(x.strip()) for x in value.split(',')])
if target in values:
return True
... | Add parsing for list of numbers. | Add parsing for list of numbers.
| Python | mit | kipe/pycron | ---
+++
@@ -4,6 +4,15 @@
def _parse_arg(value, target, maximum):
if value == '*':
return True
+
+ if ',' in value:
+ if '*' in value:
+ raise ValueError
+
+ values = filter(None, [int(x.strip()) for x in value.split(',')])
+ if target in values:
+ return Tr... |
2c09716430f90f8bac00ff5a1490693578960495 | q_and_a/apps/questions/api/resources.py | q_and_a/apps/questions/api/resources.py | from tastypie.resources import ModelResource
from questions.models import Answer
class AnswerResource(ModelResource):
class Meta:
queryset = Answer.objects.all()
allowed_methods = ['get']
| import json
from tastypie.resources import ModelResource
from questions.models import Answer
from django.core.serializers.json import DjangoJSONEncoder
from tastypie.serializers import Serializer
# From the Tastypie Cookbook: Pretty-printed JSON Serialization
# http://django-tastypie.readthedocs.org/en/latest/cookbook... | Switch to pretty printing JSON for the API. | Switch to pretty printing JSON for the API.
| Python | bsd-3-clause | DemocracyClub/candidate_questions,DemocracyClub/candidate_questions,DemocracyClub/candidate_questions | ---
+++
@@ -1,7 +1,22 @@
+import json
from tastypie.resources import ModelResource
from questions.models import Answer
+from django.core.serializers.json import DjangoJSONEncoder
+from tastypie.serializers import Serializer
+
+# From the Tastypie Cookbook: Pretty-printed JSON Serialization
+# http://django-tastypie... |
02ab421105754e6ec258bc7c48b794bcb8ad95ec | HOME/.ipython/profile_default/ipython_config.py | HOME/.ipython/profile_default/ipython_config.py | c.TerminalIPythonApp.display_banner = False
c.TerminalInteractiveShell.confirm_exit = False
c.TerminalInteractiveShell.highlighting_style = "monokai"
c.TerminalInteractiveShell.term_title = False
| c.TerminalIPythonApp.display_banner = False
c.TerminalInteractiveShell.confirm_exit = False
c.TerminalInteractiveShell.highlighting_style = "monokai"
c.TerminalInteractiveShell.term_title = False
import logging
logging.getLogger('parso').level = logging.WARN
| Fix spammy logging during IPython tab complete | Fix spammy logging during IPython tab complete
https://github.com/ipython/ipython/issues/10946
| Python | mit | kbd/setup,kbd/setup,kbd/setup,kbd/setup,kbd/setup | ---
+++
@@ -2,3 +2,5 @@
c.TerminalInteractiveShell.confirm_exit = False
c.TerminalInteractiveShell.highlighting_style = "monokai"
c.TerminalInteractiveShell.term_title = False
+import logging
+logging.getLogger('parso').level = logging.WARN |
770f1a5d83a8450e9a16942d1260483f7b1401cd | sauce/model/news.py | sauce/model/news.py | # -*- coding: utf-8 -*-
'''News model module
@author: moschlar
'''
from datetime import datetime
from sqlalchemy import ForeignKey, Column
from sqlalchemy.types import Integer, Unicode, DateTime, Boolean
from sqlalchemy.orm import relationship, backref
from sqlalchemy.sql import desc
from sauce.model import Declara... | # -*- coding: utf-8 -*-
'''News model module
@author: moschlar
'''
from datetime import datetime
from sqlalchemy import ForeignKey, Column
from sqlalchemy.types import Integer, Unicode, DateTime, Boolean
from sqlalchemy.orm import relationship, backref
from sqlalchemy.sql import desc
from sauce.model import Declara... | Add unicode repr to NewsItem | Add unicode repr to NewsItem
| Python | agpl-3.0 | moschlar/SAUCE,moschlar/SAUCE,moschlar/SAUCE,moschlar/SAUCE | ---
+++
@@ -41,3 +41,6 @@
public = Column(Boolean, nullable=False, default=False)
__mapper_args__ = {'order_by': desc(date)}
+
+ def __unicode__(self):
+ return u'NewsItem %d "%s"' % (self.id or '', self.subject) |
5db2ee20fbe8ecdf1d432fd23c21702233f1bba7 | recharges/tasks.py | recharges/tasks.py | from celery.task import Task
from celery.utils.log import get_task_logger
import requests
logger = get_task_logger(__name__)
class Hotsocket_Login(Task):
"""
Task to get the username and password varified then produce a token
"""
name = "gopherairtime.recharges.tasks.hotsocket_login"
def run(s... | import requests
from django.conf import settings
from celery.task import Task
from celery.utils.log import get_task_logger
from .models import Account
logger = get_task_logger(__name__)
class Hotsocket_Login(Task):
"""
Task to get the username and password varified then produce a token
"""
name = ... | Refactor the task for getting token to store it in DB | Refactor the task for getting token to store it in DB
| Python | bsd-3-clause | westerncapelabs/gopherairtime,westerncapelabs/gopherairtime | ---
+++
@@ -1,7 +1,10 @@
+import requests
+
+from django.conf import settings
from celery.task import Task
from celery.utils.log import get_task_logger
-import requests
+from .models import Account
logger = get_task_logger(__name__)
@@ -21,8 +24,13 @@
l.info("Logging into hotsocket")
auth =... |
4d1455614beea6b751715fbd0a0547bbe3dea018 | wagtailstartproject/project_template/tests/middleware.py | wagtailstartproject/project_template/tests/middleware.py | try:
from django.utils.deprecation import MiddlewareMixin
except ImportError:
MiddlewareMixin = object
class PageStatusMiddleware(MiddlewareMixin):
"""Add the response status code as a meta tag in the head of all pages
Note: Only enable this middleware for (Selenium) tests
"""
def process_r... | try:
from django.utils.deprecation import MiddlewareMixin
except ImportError:
MiddlewareMixin = object
class PageStatusMiddleware(MiddlewareMixin):
"""Add the response status code as a meta tag in the head of all pages
Note: Only enable this middleware for (Selenium) tests
"""
def process_r... | Update PageStatusMiddleware for use with Python 3 | Update PageStatusMiddleware for use with Python 3
| Python | mit | leukeleu/wagtail-startproject,leukeleu/wagtail-startproject | ---
+++
@@ -16,8 +16,8 @@
# (expecting response['Content-Type'] to be ~ 'text/html; charset=utf-8')
if 'html' in response['Content-Type'].lower():
response.content = response.content.replace(
- '</head>',
- '<meta name="status_code" content="{status_code}" ... |
17cb875c0f7788d108e6f78cf12d8924d02bdccf | setup-user-theme.py | setup-user-theme.py | #!/usr/bin/python
# FIXME Need to handle the case when symlinks already exists
import os
theme_dir = os.path.expanduser('~/.themes/olpc/gtk-2.0')
engine_dir = os.path.expanduser('~/.gtk-2.0/engines')
src_dir = os.path.abspath(os.path.dirname(__file__))
if not os.path.exists(theme_dir):
try:
os.makedirs(theme_dir... | #!/usr/bin/python
# FIXME Need to handle the case when symlinks already exists
import os
theme_dir = os.path.expanduser('~/.themes/olpc/gtk-2.0')
gtkrc_dest = os.path.join(theme_dir, 'gtkrc')
engine_dir = os.path.expanduser('~/.gtk-2.0/engines')
engine_dest = os.path.join(engine_dir, 'libolpc.so')
src_dir = os.pat... | Deal with existing symlinks and add more error checking | Deal with existing symlinks and add more error checking
| Python | lgpl-2.1 | samdroid-apps/sugar-artwork,samdroid-apps/sugar-artwork,gusDuarte/sugar-artwork,i5o/sugar-artwork,gusDuarte/sugar-artwork,gusDuarte/sugar-artwork,godiard/sugar-artwork,sugarlabs/sugar-artwork,tchx84/debian-pkg-sugar-artwork,i5o/sugar-artwork,godiard/sugar-artwork,tchx84/debian-pkg-sugar-artwork,gusDuarte/sugar-artwork,... | ---
+++
@@ -5,7 +5,11 @@
import os
theme_dir = os.path.expanduser('~/.themes/olpc/gtk-2.0')
+gtkrc_dest = os.path.join(theme_dir, 'gtkrc')
+
engine_dir = os.path.expanduser('~/.gtk-2.0/engines')
+engine_dest = os.path.join(engine_dir, 'libolpc.so')
+
src_dir = os.path.abspath(os.path.dirname(__file__))
if no... |
db566a81186a600543ca1c04951c174ef24388f4 | slash_bot/config.py | slash_bot/config.py | # coding: utf-8
"""
Created on 2016-08-23
@author: naoey
"""
VERSION = "0.0.3"
BOT_PREFIX = ":"
PATHS = {
"logs_dir": "./../logs/",
"database": "./../slash_bot.db",
"discord_creds": "./../private/discord.json",
"rito_creds": "./../private/rito.json",
"assets": "./../assets/",
}
MODULES = {
... | # coding: utf-8
"""
Created on 2016-08-23
@author: naoey
"""
VERSION = "0.0.3"
BOT_PREFIX = ","
PATHS = {
"logs_dir": "./../logs/",
"database": "./../slash_bot.db",
"discord_creds": "./../private/discord.json",
"rito_creds": "./../private/rito.json",
"assets": "./../assets/",
}
MODULES = {
... | Fix stupid git app committing unwanted stuff~ | Fix stupid git app committing unwanted stuff~
| Python | mit | naoey/slash-bot,naoey/slash-bot | ---
+++
@@ -7,7 +7,7 @@
VERSION = "0.0.3"
-BOT_PREFIX = ":"
+BOT_PREFIX = ","
PATHS = {
"logs_dir": "./../logs/", |
50b9194b0f6c45abc0513b1172fbbaada180c38a | astropy/io/vo/__init__.py | astropy/io/vo/__init__.py | from __future__ import division, absolute_import
# If we're in the source directory, don't import anything, since that
# requires 2to3 to be run.
from astropy import setup_helpers
if setup_helpers.is_in_build_mode():
pass
else:
del setup_helpers
from .table import parse, parse_single_table
from .except... | from __future__ import division, absolute_import
# If we're in the source directory, don't import anything, since that
# requires 2to3 to be run.
from astropy import setup_helpers
if setup_helpers.is_in_build_mode():
pass
else:
del setup_helpers
from .table import parse, parse_single_table
from .except... | Use parentheses instead of \ for multi-line import. | Use parentheses instead of \ for multi-line import.
| Python | bsd-3-clause | AustereCuriosity/astropy,StuartLittlefair/astropy,MSeifert04/astropy,larrybradley/astropy,kelle/astropy,aleksandr-bakanov/astropy,lpsinger/astropy,tbabej/astropy,kelle/astropy,mhvk/astropy,kelle/astropy,mhvk/astropy,lpsinger/astropy,AustereCuriosity/astropy,bsipocz/astropy,DougBurke/astropy,larrybradley/astropy,Austere... | ---
+++
@@ -8,7 +8,7 @@
else:
del setup_helpers
from .table import parse, parse_single_table
- from .exceptions import VOWarning, VOTableChangeWarning, \
- VOTableSpecWarning, UnimplementedWarning, IOWarning, \
- VOTableSpecError
+ from .exceptions import (VOWarning, VOTableChangeWarn... |
32820375c4552a9648612ea0dddfbf524e672c0e | virtool/indexes/models.py | virtool/indexes/models.py | import enum
from sqlalchemy import Column, Integer, String, Enum
from virtool.pg.utils import Base, SQLEnum
class IndexType(str, SQLEnum):
"""
Enumerated type for index file types
"""
json = "json"
fasta = "fasta"
bowtie2 = "bowtie2"
class IndexFile(Base):
"""
SQL model to store n... | import enum
from sqlalchemy import Column, Integer, String, Enum
from virtool.pg.utils import Base, SQLEnum
class IndexType(str, SQLEnum):
"""
Enumerated type for index file types
"""
json = "json"
fasta = "fasta"
bowtie2 = "bowtie2"
class IndexFile(Base):
"""
SQL model to store n... | Update IndexFile model to have 'index' column instead of 'reference' | Update IndexFile model to have 'index' column instead of 'reference'
| Python | mit | virtool/virtool,igboyes/virtool,igboyes/virtool,virtool/virtool | ---
+++
@@ -24,10 +24,10 @@
id = Column(Integer, primary_key=True)
name = Column(String)
- reference = Column(String)
+ index = Column(String)
type = Column(Enum(IndexType))
size = Column(Integer)
def __repr__(self):
- return f"<IndexFile(id={self.id}, name={self.name}, refer... |
a68f7ea6a9335a54762bfecf7b8f0a186bab8ed8 | detectron2/projects/__init__.py | detectron2/projects/__init__.py | # Copyright (c) Facebook, Inc. and its affiliates.
import importlib
from pathlib import Path
_PROJECTS = {
"point_rend": "PointRend",
"deeplab": "DeepLab",
"panoptic_deeplab": "Panoptic-DeepLab",
}
_PROJECT_ROOT = Path(__file__).parent.parent.parent / "projects"
if _PROJECT_ROOT.is_dir():
# This is tr... | # Copyright (c) Facebook, Inc. and its affiliates.
import importlib
from pathlib import Path
_PROJECTS = {
"point_rend": "PointRend",
"deeplab": "DeepLab",
"panoptic_deeplab": "Panoptic-DeepLab",
}
_PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent / "projects"
if _PROJECT_ROOT.is_dir():
# ... | Resolve path in case it involves a symlink | Resolve path in case it involves a symlink
Reviewed By: ppwwyyxx
Differential Revision: D27823003
fbshipit-source-id: 67e6905f3c5c7bb1f593ee004160b195925f6d39
| Python | apache-2.0 | facebookresearch/detectron2,facebookresearch/detectron2,facebookresearch/detectron2 | ---
+++
@@ -7,7 +7,7 @@
"deeplab": "DeepLab",
"panoptic_deeplab": "Panoptic-DeepLab",
}
-_PROJECT_ROOT = Path(__file__).parent.parent.parent / "projects"
+_PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent / "projects"
if _PROJECT_ROOT.is_dir():
# This is true only for in-place installat... |
5fabf1513ff22b404e43de54c14b8f92e5f674e7 | senlin/tests/tempest/api/profiles/test_profile_delete.py | senlin/tests/tempest/api/profiles/test_profile_delete.py | # 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 t... | # 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 t... | Fix typos in tempest API tests for profile_delete | Fix typos in tempest API tests for profile_delete
This patch fixes typos in tempest API tests for profile_delete.
Change-Id: Ic6aa696f59621a5340d6cf67be76e830bbd30e67
| Python | apache-2.0 | stackforge/senlin,openstack/senlin,openstack/senlin,stackforge/senlin,openstack/senlin | ---
+++
@@ -25,8 +25,8 @@
cls.profile = cls.create_profile(constants.spec_nova_server)
@decorators.idempotent_id('ea3c1b9e-5ed7-4d63-84ce-2032c3bc6d27')
- def test_delete_policy(self):
- # Verify resp of policy delete API
+ def test_delete_profile(self):
+ # Verify resp of profile ... |
9d0c9c385e0a1a1f66fa1e0481048bd590e91b8e | airflow/contrib/example_dags/__init__.py | airflow/contrib/example_dags/__init__.py | # -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
#... | Add license to Contrib Example DAG Init file | [AIRFLOW-XXX] Add license to Contrib Example DAG Init file
| Python | apache-2.0 | owlabs/incubator-airflow,owlabs/incubator-airflow,owlabs/incubator-airflow,owlabs/incubator-airflow | ---
+++
@@ -0,0 +1,18 @@
+# -*- coding: utf-8 -*-
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the ... | |
f1eb55a147c4cc160decbfbcde190b7e8a2d3be6 | clot/torrent/backbone.py | clot/torrent/backbone.py | """This module implements the torrent's underlying storage."""
from .. import bencode
class Backbone: # pylint: disable=too-few-public-methods
"""Torrent file low-level contents."""
def __init__(self, raw_bytes, file_path=None):
"""Initialize self."""
self.raw_bytes = raw_bytes
... | """This module implements the torrent's underlying storage."""
from .. import bencode
class Backbone:
"""Torrent file low-level contents."""
def __init__(self, raw_bytes, file_path=None):
"""Initialize self."""
self.raw_bytes = raw_bytes
self.data = bencode.decode(raw_bytes, keytost... | Remove no longer needed pylint pragma | Remove no longer needed pylint pragma
| Python | mit | elliptical/bencode | ---
+++
@@ -4,7 +4,7 @@
from .. import bencode
-class Backbone: # pylint: disable=too-few-public-methods
+class Backbone:
"""Torrent file low-level contents."""
def __init__(self, raw_bytes, file_path=None): |
d5c59c018ba7558a9d21370d7eb58ab590779cf1 | plugins/autojoin/plugin_tests/autojoin_test.py | plugins/autojoin/plugin_tests/autojoin_test.py | from tests import base
def setUpModule():
base.enabledPlugins.append('autojoin')
base.startServer()
def tearDownModule():
base.stopServer()
class AutoJoinTest(base.TestCase):
def setUp(self):
base.TestCase.setUp(self)
| from girder.constants import AccessType
from tests import base
import json
def setUpModule():
base.enabledPlugins.append('autojoin')
base.startServer()
def tearDownModule():
base.stopServer()
class AutoJoinTest(base.TestCase):
def setUp(self):
base.TestCase.setUp(self)
self.users... | Add server tests for auto join plugin | Add server tests for auto join plugin
| Python | apache-2.0 | kotfic/girder,kotfic/girder,adsorensen/girder,jbeezley/girder,data-exp-lab/girder,girder/girder,sutartmelson/girder,Kitware/girder,girder/girder,sutartmelson/girder,jbeezley/girder,RafaelPalomar/girder,girder/girder,adsorensen/girder,RafaelPalomar/girder,manthey/girder,manthey/girder,data-exp-lab/girder,RafaelPalomar/g... | ---
+++
@@ -1,4 +1,6 @@
+from girder.constants import AccessType
from tests import base
+import json
def setUpModule():
@@ -14,3 +16,64 @@
def setUp(self):
base.TestCase.setUp(self)
+
+ self.users = [self.model('user').createUser(
+ 'usr%s' % num, 'passwd', 'tst', 'usr', 'u%s@u... |
6ba29917003ea2f4a91434de57751762898dddce | tests/test_main.py | tests/test_main.py | import unittest
import time
from Arduino import Arduino
"""
A collection of some basic tests for the Arduino library.
Extensive coverage is a bit difficult, since a positive test involves actually
connecting and issuing commands to a live Arduino, hosting any hardware
required to test a particular function. But a cor... | import unittest
import time
"""
A collection of some basic tests for the Arduino library.
Extensive coverage is a bit difficult, since a positive test involves actually
connecting and issuing commands to a live Arduino, hosting any hardware
required to test a particular function. But a core of basic communication tes... | Add another test to explicitly connect to a serial port. | Add another test to explicitly connect to a serial port.
| Python | mit | bopo/Python-Arduino-Command-API,thearn/Python-Arduino-Command-API,ianjosephwilson/Python-Arduino-Command-API | ---
+++
@@ -1,6 +1,5 @@
import unittest
import time
-from Arduino import Arduino
"""
A collection of some basic tests for the Arduino library.
@@ -13,14 +12,32 @@
class TestBasics(unittest.TestCase):
- _ = raw_input('Plug in Arduino board w/LED at pin 13, reset, then press enter')
- board = Arduino('... |
2eb07ae9b98c36dc94e143003a7c44c7fbfb54f7 | stronghold/middleware.py | stronghold/middleware.py | from django.contrib.auth.decorators import login_required
from stronghold import conf, utils
class LoginRequiredMiddleware(object):
"""
Force all views to use login required
View is deemed to be public if the @public decorator is applied to the view
View is also deemed to be Public if listed in in d... | from django.contrib.auth.decorators import login_required
from stronghold import conf, utils
class LoginRequiredMiddleware(object):
"""
Force all views to use login required
View is deemed to be public if the @public decorator is applied to the view
View is also deemed to be Public if listed in in d... | Refactor away unnecessary multiple return None | Refactor away unnecessary multiple return None
| Python | mit | SunilMohanAdapa/django-stronghold,SunilMohanAdapa/django-stronghold,mgrouchy/django-stronghold | ---
+++
@@ -18,16 +18,11 @@
self.public_view_urls = getattr(conf, 'STRONGHOLD_PUBLIC_URLS', ())
def process_view(self, request, view_func, view_args, view_kwargs):
- # if request is authenticated, dont process it
- if request.user.is_authenticated():
- return None
-
- #... |
33de32fe26085b4616d561fab5a9ce91ac56451e | arxiv_vanity/papers/migrations/0017_auto_20180619_1657.py | arxiv_vanity/papers/migrations/0017_auto_20180619_1657.py | # Generated by Django 2.0.6 on 2018-06-19 16:57
from django.db import migrations
def generate_arxiv_ids(apps, schema_editor):
SourceFile = apps.get_model('papers', 'SourceFile')
for sf in SourceFile.objects.all():
if not sf.arxiv_id:
sf.arxiv_id = sf.file.name.rsplit('.', 1)[0]
... | # Generated by Django 2.0.6 on 2018-06-19 16:57
from django.db import migrations
def generate_arxiv_ids(apps, schema_editor):
SourceFile = apps.get_model('papers', 'SourceFile')
for sf in SourceFile.objects.iterator():
if not sf.arxiv_id:
sf.arxiv_id = sf.file.name.rsplit('.', 1)[0]
... | Use iterator in migration to reduce memory | Use iterator in migration to reduce memory
| Python | apache-2.0 | arxiv-vanity/arxiv-vanity,arxiv-vanity/arxiv-vanity,arxiv-vanity/arxiv-vanity,arxiv-vanity/arxiv-vanity | ---
+++
@@ -5,7 +5,7 @@
def generate_arxiv_ids(apps, schema_editor):
SourceFile = apps.get_model('papers', 'SourceFile')
- for sf in SourceFile.objects.all():
+ for sf in SourceFile.objects.iterator():
if not sf.arxiv_id:
sf.arxiv_id = sf.file.name.rsplit('.', 1)[0]
sf... |
e81aeb401f7a9eacb31bed364594ffe3fb21dfcc | conftest.py | conftest.py | from django.conf import settings
import base64
import os
import os.path
def pytest_configure(config):
if not settings.configured:
os.environ['DJANGO_SETTINGS_MODULE'] = 'sentry.conf.server'
test_db = os.environ.get('DB', 'sqlite')
if test_db == 'mysql':
settings.DATABASES['default'].updat... | from django.conf import settings
import base64
import os
import os.path
def pytest_configure(config):
if not settings.configured:
os.environ['DJANGO_SETTINGS_MODULE'] = 'sentry.conf.server'
test_db = os.environ.get('DB', 'sqlite')
if test_db == 'mysql':
settings.DATABASES['default'].updat... | Improve test performance by using the md5 hasher for tests. | Improve test performance by using the md5 hasher for tests.
| Python | bsd-3-clause | gg7/sentry,mvaled/sentry,felixbuenemann/sentry,NickPresta/sentry,Kryz/sentry,imankulov/sentry,argonemyth/sentry,kevinastone/sentry,fuziontech/sentry,BuildingLink/sentry,Kryz/sentry,fotinakis/sentry,llonchj/sentry,korealerts1/sentry,camilonova/sentry,BuildingLink/sentry,zenefits/sentry,beni55/sentry,kevinlondon/sentry,p... | ---
+++
@@ -39,3 +39,7 @@
)
settings.SENTRY_KEY = base64.b64encode(os.urandom(40))
settings.SENTRY_PUBLIC = False
+ # This speeds up the tests considerably, pbkdf2 is by design, slow.
+ settings.PASSWORD_HASHERS = [
+ 'django.contrib.auth.hashers.MD5PasswordHasher',
+ ] |
fa4cc4cab3e76ba0211736da4862a85d50bdcccc | gameconf.py | gameconf.py | import os
from traceback import format_exc
from apps.config.models import ConfigValue
import functions_general
"""
Handle the setting/retrieving of server config directives.
"""
def host_os_is(osname):
"""
Check to see if the host OS matches the query.
"""
if os.name == osname:
return True
return... | import os
from traceback import format_exc
from apps.config.models import ConfigValue
import functions_general
"""
Handle the setting/retrieving of server config directives.
"""
def host_os_is(osname):
"""
Check to see if the host OS matches the query.
"""
if os.name == osname:
return True
return... | Make config values not case-sensitive. | Make config values not case-sensitive.
| Python | bsd-3-clause | mrkulk/text-world,titeuf87/evennia,mrkulk/text-world,shollen/evennia,feend78/evennia,TheTypoMaster/evennia,feend78/evennia,ypwalter/evennia,ergodicbreak/evennia,mrkulk/text-world,emergebtc/evennia,ypwalter/evennia,titeuf87/evennia,emergebtc/evennia,titeuf87/evennia,emergebtc/evennia,ypwalter/evennia,jamesbeebop/evennia... | ---
+++
@@ -20,7 +20,7 @@
Retrieve a configuration value.
"""
try:
- return ConfigValue.objects.get(conf_key=configname).conf_value
+ return ConfigValue.objects.get(conf_key__iexact=configname).conf_value
except:
functions_general.log_errmsg("Unable to get config value for %s:\n%s" % ... |
aaaab6f87fef26feb29ddf8188e6410e7be55376 | falcom/test/test_logtree.py | falcom/test/test_logtree.py | # Copyright (c) 2017 The Regents of the University of Michigan.
# All Rights Reserved. Licensed according to the terms of the Revised
# BSD License. See LICENSE.txt for details.
from hamcrest import *
import unittest
from .hamcrest import evaluates_to_false
from ..logtree import Tree
class TreeTest (unittest.TestCase... | # Copyright (c) 2017 The Regents of the University of Michigan.
# All Rights Reserved. Licensed according to the terms of the Revised
# BSD License. See LICENSE.txt for details.
from hamcrest import *
import unittest
from .hamcrest import evaluates_to_false
from ..logtree import Tree
class GivenEmptyTree (unittest.Te... | Refactor tests to use setup | Refactor tests to use setup
| Python | bsd-3-clause | mlibrary/image-conversion-and-validation,mlibrary/image-conversion-and-validation | ---
+++
@@ -7,12 +7,13 @@
from .hamcrest import evaluates_to_false
from ..logtree import Tree
-class TreeTest (unittest.TestCase):
+class GivenEmptyTree (unittest.TestCase):
- def test_tree_is_a_class (self):
- t = Tree()
- assert_that(repr(t), starts_with("<Tree"))
+ def setUp (self):
+ ... |
245d0b91a778d6c0015e04bf369bc59304588cb9 | block_disposable_email.py | block_disposable_email.py | #!/usr/bin/env python
import re
import sys
def chunk(l,n):
return (l[i:i+n] for i in xrange(0, len(l), n))
def is_disposable_email(email):
emails = [line.strip() for line in open('domain-list.txt')]
"""
Chunk it!
Regex parser doesn't deal with hundreds of groups
"""
for email_group ... | from django.conf import settings
import re
import sys
class DisposableEmailChecker():
"""
Check if an email is from a disposable
email service
"""
def __init__(self):
self.emails = [line.strip() for line in open(settings.DISPOSABLE_EMAIL_DOMAINS)]
def chunk(l,n):
retu... | Convert for use with Django | Convert for use with Django
| Python | bsd-3-clause | aaronbassett/DisposableEmailChecker | ---
+++
@@ -1,31 +1,24 @@
-#!/usr/bin/env python
+from django.conf import settings
import re
import sys
-def chunk(l,n):
- return (l[i:i+n] for i in xrange(0, len(l), n))
-
-
-def is_disposable_email(email):
- emails = [line.strip() for line in open('domain-list.txt')]
+class DisposableEmailChecker():
+ ... |
22800562830d11cf8287656f098e163d7cedf2d3 | test/test_scraping.py | test/test_scraping.py | from datetime import datetime
import sys
import unittest
import btceapi
class TestScraping(unittest.TestCase):
def test_scrape_main_page(self):
mainPage = btceapi.scrapeMainPage()
for message in mainPage.messages:
msgId, user, time, text = message
assert type(time) is date... | from datetime import datetime
import sys
import unittest
import btceapi
class TestScraping(unittest.TestCase):
def test_scrape_main_page(self):
mainPage = btceapi.scrapeMainPage()
for message in mainPage.messages:
msgId, user, time, text = message
self.assertIs(type(time),... | Fix for assertIn method not being present in Python 2.6. Undo prior erroneous commit (assertIn is missing, not assertIs). | Fix for assertIn method not being present in Python 2.6.
Undo prior erroneous commit (assertIn is missing, not assertIs).
| Python | mit | alanmcintyre/btce-api,CodeReclaimers/btce-api,lromanov/tidex-api | ---
+++
@@ -10,12 +10,12 @@
mainPage = btceapi.scrapeMainPage()
for message in mainPage.messages:
msgId, user, time, text = message
- assert type(time) is datetime
+ self.assertIs(type(time), datetime)
if sys.version_info[0] == 2:
# py... |
8a39404dc2b6e3acc0324d9c11619640e44f6bd5 | tests/test_threads.py | tests/test_threads.py | from guv.green import threading, time
def f1():
"""A simple function
"""
print('Hello, world!')
def f2():
"""A simple function that sleeps for a short period of time
"""
time.sleep(0.1)
class TestThread:
def test_thread_create(self):
t = threading.Thread(target=f1)
asse... | from guv.green import threading, time
def f1():
"""A simple function
"""
print('Hello, world!')
def f2():
"""A simple function that sleeps for a short period of time
"""
time.sleep(0.1)
class TestThread:
def test_thread_create(self):
t = threading.Thread(target=f1)
asse... | Check to ensure that we're dealing with "green" threads | Check to ensure that we're dealing with "green" threads
| Python | mit | veegee/guv,veegee/guv | ---
+++
@@ -16,22 +16,23 @@
class TestThread:
def test_thread_create(self):
t = threading.Thread(target=f1)
- assert t
+ assert 'green' in repr(t)
def test_thread_start(self):
t = threading.Thread(target=f1)
+ assert 'green' in repr(t)
t.start()
- as... |
d565fdab9cefc080ff3127f036c19e95cba73f6e | tests/test_udacity.py | tests/test_udacity.py | import unittest
from mooc_aggregator_restful_api import udacity
class UdacityTestCase(unittest.TestCase):
'''
Unit Tests for module udacity
'''
def setUp(self):
self.udacity_test_object = udacity.UdacityAPI()
def test_udacity_api_response(self):
self.assertEqual(self.udacity_te... | import unittest
from mooc_aggregator_restful_api import udacity
class UdacityTestCase(unittest.TestCase):
'''
Unit Tests for module udacity
'''
def setUp(self):
self.udacity_test_object = udacity.UdacityAPI()
def test_udacity_api_response(self):
self.assertEqual(self.udacity_te... | Add unit test for mongofy_courses of udacity module | Add unit test for mongofy_courses of udacity module
| Python | mit | ueg1990/mooc_aggregator_restful_api | ---
+++
@@ -15,6 +15,10 @@
def test_udacity_api_response(self):
self.assertEqual(self.udacity_test_object.status_code(), 200)
+ def test_udacity_api_mongofy_courses(self):
+ course = self.udacity_test_object.mongofy_courses()[0]
+ self.assertEqual(course['title'], 'Intro to Computer S... |
badbe38249297372c14cde1c58501854ccda413a | uncertainty/lib/nlp/__init__.py | uncertainty/lib/nlp/__init__.py | import os
VERBS_PATH = os.path.join(
os.path.dirname(os.path.abspath(__file__)), 'verbs.txt'
)
| from pkg_resources import resource_filename
VERBS_PATH = resource_filename('uncertainty.lib.nlp', 'verbs.txt')
| Use pkg_resources to resolve file paths | Use pkg_resources to resolve file paths
| Python | mit | meyersbs/uncertainty | ---
+++
@@ -1,5 +1,3 @@
-import os
+from pkg_resources import resource_filename
-VERBS_PATH = os.path.join(
- os.path.dirname(os.path.abspath(__file__)), 'verbs.txt'
- )
+VERBS_PATH = resource_filename('uncertainty.lib.nlp', 'verbs.txt') |
0cf45ad47d8b5e6e6df329990e76c4e5702f8e6c | django_lightweight_queue/app_settings.py | django_lightweight_queue/app_settings.py | from django.conf import settings
def setting(suffix, default):
return getattr(settings, 'LIGHTWEIGHT_QUEUE_%s' % suffix, default)
BACKEND = setting('BACKED', 'django_lightweight_queue.backends.synchronous.SynchronousBackend')
MIDDLEWARE = setting('MIDDLEWARE', (
'django_lightweight_queue.middleware.logging.Lo... | from django.conf import settings
def setting(suffix, default):
return getattr(settings, 'LIGHTWEIGHT_QUEUE_%s' % suffix, default)
BACKEND = setting('BACKEND', 'django_lightweight_queue.backends.synchronous.SynchronousBackend')
MIDDLEWARE = setting('MIDDLEWARE', (
'django_lightweight_queue.middleware.logging.L... | Correct typo in getting BACKEND. | Correct typo in getting BACKEND.
Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@thread.com>
| Python | bsd-3-clause | prophile/django-lightweight-queue,thread/django-lightweight-queue,lamby/django-lightweight-queue,thread/django-lightweight-queue,prophile/django-lightweight-queue | ---
+++
@@ -3,7 +3,7 @@
def setting(suffix, default):
return getattr(settings, 'LIGHTWEIGHT_QUEUE_%s' % suffix, default)
-BACKEND = setting('BACKED', 'django_lightweight_queue.backends.synchronous.SynchronousBackend')
+BACKEND = setting('BACKEND', 'django_lightweight_queue.backends.synchronous.SynchronousBack... |
42f9c3ae74073fd55702e3ffccd5b4b820d86c22 | bpython/test/test_keys.py | bpython/test/test_keys.py | #!/usr/bin/env python
import unittest
import bpython.keys as keys
class TestKeys(unittest.TestCase):
def test_keymap_map(self):
"""Verify KeyMap.map being a dictionary with the correct length."""
self.assertEqual(len(keys.key_dispatch.map), 43)
def test_keymap_setitem(self):
"""Verify ... | #!/usr/bin/env python
import unittest
import bpython.keys as keys
class TestKeys(unittest.TestCase):
def test_keymap_getitem(self):
"""Verify keys.KeyMap correctly looking up items."""
self.assertEqual(keys.key_dispatch['C-['], (chr(27), '^['))
self.assertEqual(keys.key_dispatch['F11'], ('K... | Add __delitem__, and dict length checking to tests for keys | Add __delitem__, and dict length checking to tests for keys
| Python | mit | 5monkeys/bpython | ---
+++
@@ -3,22 +3,6 @@
import bpython.keys as keys
class TestKeys(unittest.TestCase):
- def test_keymap_map(self):
- """Verify KeyMap.map being a dictionary with the correct length."""
- self.assertEqual(len(keys.key_dispatch.map), 43)
-
- def test_keymap_setitem(self):
- """Verify ke... |
91951e85caf1b928224dba1ecc33a59957187dff | tkp/tests/__init__.py | tkp/tests/__init__.py | import unittest
testfiles = [
'tkp.tests.accessors',
'tkp.tests.classification',
'tkp.tests.config',
'tkp.tests.coordinates',
'tkp.tests.database',
'tkp.tests.dataset',
'tkp.tests.FDR',
'tkp.tests.feature_extraction',
'tkp.tests.gaussian',
'tkp.tests.L15_12h_const',
'tkp.tes... | import unittest
testfiles = [
'tkp.tests.accessors',
'tkp.tests.classification',
'tkp.tests.config',
'tkp.tests.coordinates',
'tkp.tests.database',
'tkp.tests.dataset',
'tkp.tests.FDR',
'tkp.tests.feature_extraction',
'tkp.tests.gaussian',
'tkp.tests.L15_12h_const',
'tkp.tes... | Remove special-casing of aipsppimage test | Remove special-casing of aipsppimage test
We have other dependencies on pyrap too...
git-svn-id: 71bcaaf8fac6301ed959c5094abb905057e55e2d@2123 2b73c8c1-3922-0410-90dd-bc0a5c6f2ac6
| Python | bsd-2-clause | bartscheers/tkp,mkuiack/tkp,transientskp/tkp,transientskp/tkp,mkuiack/tkp,bartscheers/tkp | ---
+++
@@ -14,13 +14,5 @@
'tkp.tests.sigmaclip',
'tkp.tests.source_measurements',
'tkp.tests.wcs',
+ 'tkp.tests.aipsppimage'
]
-
-# Pyrap is required for AIPS++ image support, but
-# not necessary for the rest of the library.
-try:
- import pyrap
-except:
- pass
-else:
- testfiles.append(... |
60f696c07b64909ccaee8d90eff54ac6301b7a71 | buildbox/app.py | buildbox/app.py | from sqlalchemy import create_engine
from tornado.web import Application, url
from buildbox.config import settings
from buildbox.db.backend import Backend
from buildbox.web.frontend.build_list import BuildListHandler
from buildbox.web.frontend.build_details import BuildDetailsHandler
application = Application(
[... | from sqlalchemy import create_engine
from tornado.web import Application, url
from buildbox.config import settings
from buildbox.db.backend import Backend
from buildbox.web.frontend.build_list import BuildListHandler
from buildbox.web.frontend.build_details import BuildDetailsHandler
application = Application(
[... | Disable debug output of sqla | Disable debug output of sqla
| Python | apache-2.0 | bowlofstew/changes,wfxiang08/changes,dropbox/changes,wfxiang08/changes,wfxiang08/changes,bowlofstew/changes,dropbox/changes,dropbox/changes,wfxiang08/changes,bowlofstew/changes,bowlofstew/changes,dropbox/changes | ---
+++
@@ -21,8 +21,8 @@
settings['database'],
# pool_size=options.mysql_poolsize,
# pool_recycle=3600,
- echo=settings['debug'],
- echo_pool=settings['debug'],
+ # echo=settings['debug'],
+ # echo_pool=settings['debug'],
),
)
|
68b2536c53426d9b624527f7ef0eb5b22c68986e | helusers/models.py | helusers/models.py | import uuid
import logging
from django.db import models
from django.contrib.auth.models import AbstractUser as DjangoAbstractUser
logger = logging.getLogger(__name__)
class AbstractUser(DjangoAbstractUser):
uuid = models.UUIDField(primary_key=True)
department_name = models.CharField(max_length=50, null=True,... | import uuid
import logging
from django.db import models
from django.contrib.auth.models import AbstractUser as DjangoAbstractUser
logger = logging.getLogger(__name__)
class AbstractUser(DjangoAbstractUser):
uuid = models.UUIDField()
department_name = models.CharField(max_length=50, null=True, blank=True)
... | Make UUID a non-pk to work around problems in 3rd party apps | Make UUID a non-pk to work around problems in 3rd party apps
| Python | bsd-2-clause | City-of-Helsinki/django-helusers,City-of-Helsinki/django-helusers | ---
+++
@@ -7,7 +7,7 @@
class AbstractUser(DjangoAbstractUser):
- uuid = models.UUIDField(primary_key=True)
+ uuid = models.UUIDField()
department_name = models.CharField(max_length=50, null=True, blank=True)
def save(self, *args, **kwargs): |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.