commit stringlengths 40 40 | old_file stringlengths 4 118 | new_file stringlengths 4 118 | old_contents stringlengths 10 2.94k | new_contents stringlengths 21 3.18k | subject stringlengths 16 444 | message stringlengths 17 2.63k | lang stringclasses 1
value | license stringclasses 13
values | repos stringlengths 5 43k | ndiff stringlengths 51 3.32k | instruction stringlengths 16 444 | content stringlengths 133 4.32k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
a8818e2058fdfaec7f283a5115619d42d23b7dde | anchorhub/builtin/github/writer.py | anchorhub/builtin/github/writer.py |
from anchorhub.writer import Writer
from anchorhub.builtin.github.wstrategies import MarkdownATXWriterStrategy, \
MarkdownSetextWriterStrategy, MarkdownInlineLinkWriterStrategy
import anchorhub.builtin.github.switches as ghswitches
def make_github_markdown_writer(opts):
"""
Creates a Writer object used f... |
from anchorhub.writer import Writer
from anchorhub.builtin.github.wstrategies import MarkdownATXWriterStrategy, \
MarkdownSetextWriterStrategy, MarkdownInlineLinkWriterStrategy
import anchorhub.builtin.github.switches as ghswitches
def make_github_markdown_writer(opts):
"""
Creates a Writer object used f... | Use Setext strategy in GitHub built in Writer | Use Setext strategy in GitHub built in Writer
| Python | apache-2.0 | samjabrahams/anchorhub |
from anchorhub.writer import Writer
from anchorhub.builtin.github.wstrategies import MarkdownATXWriterStrategy, \
MarkdownSetextWriterStrategy, MarkdownInlineLinkWriterStrategy
import anchorhub.builtin.github.switches as ghswitches
def make_github_markdown_writer(opts):
"""
Creates a ... | Use Setext strategy in GitHub built in Writer | ## Code Before:
from anchorhub.writer import Writer
from anchorhub.builtin.github.wstrategies import MarkdownATXWriterStrategy, \
MarkdownSetextWriterStrategy, MarkdownInlineLinkWriterStrategy
import anchorhub.builtin.github.switches as ghswitches
def make_github_markdown_writer(opts):
"""
Creates a Writ... |
c154d79ba13d95f3240efd9eb4725cf9fc16060f | forms.py | forms.py | from flask_wtf import Form
from wtforms import StringField, PasswordField
from wtforms.validators import DataRequired, Email
class Login(Form):
username = StringField('Username', validators=[DataRequired()])
password = PasswordField('Password', validators=[DataRequired()])
| from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField
from wtforms.validators import DataRequired, Email
class Login(FlaskForm):
username = StringField('Username', validators=[DataRequired()])
password = PasswordField('Password', validators=[DataRequired()])
| Change deprecated flask_wtf.Form with flask_wtf.FlaskForm | Change deprecated flask_wtf.Form with flask_wtf.FlaskForm
| Python | mit | openedoo/module_employee,openedoo/module_employee,openedoo/module_employee | - from flask_wtf import Form
+ from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField
from wtforms.validators import DataRequired, Email
- class Login(Form):
+ class Login(FlaskForm):
username = StringField('Username', validators=[DataRequired()])
password = PasswordField('... | Change deprecated flask_wtf.Form with flask_wtf.FlaskForm | ## Code Before:
from flask_wtf import Form
from wtforms import StringField, PasswordField
from wtforms.validators import DataRequired, Email
class Login(Form):
username = StringField('Username', validators=[DataRequired()])
password = PasswordField('Password', validators=[DataRequired()])
## Instruction:
Cha... |
ce95e50b7cb3ef9bbabddb033352aacb96b9237a | pywikibot/families/wikivoyage_family.py | pywikibot/families/wikivoyage_family.py | """Family module for Wikivoyage."""
#
# (C) Pywikibot team, 2012-2016
#
# Distributed under the terms of the MIT license.
#
from __future__ import absolute_import, unicode_literals
__version__ = '$Id$'
# The new wikivoyage family that is hosted at wikimedia
from pywikibot import family
class Family(family.Subdomai... | """Family module for Wikivoyage."""
#
# (C) Pywikibot team, 2012-2016
#
# Distributed under the terms of the MIT license.
#
# The new wikivoyage family that is hosted at wikimedia
from __future__ import absolute_import, unicode_literals
from pywikibot import family
__version__ = '$Id$'
class Family(family.Subdomain... | Add fi:wikivoyage and sort by current article count | Add fi:wikivoyage and sort by current article count
Fix also pycodestyle (former PEP8) E402 problem
Bug: T153470
Change-Id: Id9bc980c7a9cfb21063597a3d5eae11c31d8040c
| Python | mit | Darkdadaah/pywikibot-core,magul/pywikibot-core,jayvdb/pywikibot-core,hasteur/g13bot_tools_new,happy5214/pywikibot-core,magul/pywikibot-core,happy5214/pywikibot-core,Darkdadaah/pywikibot-core,npdoty/pywikibot,wikimedia/pywikibot-core,PersianWikipedia/pywikibot-core,hasteur/g13bot_tools_new,jayvdb/pywikibot-core,hasteur/... | """Family module for Wikivoyage."""
#
# (C) Pywikibot team, 2012-2016
#
# Distributed under the terms of the MIT license.
#
+ # The new wikivoyage family that is hosted at wikimedia
from __future__ import absolute_import, unicode_literals
+ from pywikibot import family
+
__version__ = '$Id$'
-
- # ... | Add fi:wikivoyage and sort by current article count | ## Code Before:
"""Family module for Wikivoyage."""
#
# (C) Pywikibot team, 2012-2016
#
# Distributed under the terms of the MIT license.
#
from __future__ import absolute_import, unicode_literals
__version__ = '$Id$'
# The new wikivoyage family that is hosted at wikimedia
from pywikibot import family
class Family... |
38216f9d1b875c31b97c80bb9217557e67c92ff3 | spicedham/backend.py | spicedham/backend.py | class BaseBackend(object):
"""
A base class for backend plugins.
"""
def __init__(self, config):
pass
def reset(self):
"""
Resets the training data to a blank slate.
"""
raise NotImplementedError()
def get_key(self, classifier, key, default=None):
... | class BaseBackend(object):
"""
A base class for backend plugins.
"""
def __init__(self, config):
pass
def reset(self):
"""
Resets the training data to a blank slate.
"""
raise NotImplementedError()
def get_key(self, classification_type, classifier, key... | Add classifier type to the base class | Add classifier type to the base class
| Python | mpl-2.0 | mozilla/spicedham,mozilla/spicedham | class BaseBackend(object):
"""
A base class for backend plugins.
"""
def __init__(self, config):
pass
def reset(self):
"""
Resets the training data to a blank slate.
"""
raise NotImplementedError()
+
- def get_key(self, clas... | Add classifier type to the base class | ## Code Before:
class BaseBackend(object):
"""
A base class for backend plugins.
"""
def __init__(self, config):
pass
def reset(self):
"""
Resets the training data to a blank slate.
"""
raise NotImplementedError()
def get_key(self, classifier, key, defa... |
ba2f2d7e53f0ffc58c882d78f1b8bc9a468eb164 | predicates.py | predicates.py | class OneOf:
def __init__(self, members):
self.members = members
def __call__(self, candidate):
if candidate in self.members:
return True
return "%s not in %s" % (candidate, self.members)
def __repr__(self):
return "one of %s" % ', '.join(self.members)
def oneof(*members):
return OneOf(members)
class... | class OneOf:
def __init__(self, members):
self.members = members
def __call__(self, candidate):
if candidate in self.members:
return True
return "%s not in %s" % (candidate, self.members)
def __repr__(self):
return "one of %s" % ', '.join(map(repr, self.members))
def oneof(*members):
return OneOf(memb... | Fix problem rendering oneof() predicate when the members aren't strings | Fix problem rendering oneof() predicate when the members aren't strings
| Python | mit | mrozekma/pytypecheck | class OneOf:
def __init__(self, members):
self.members = members
def __call__(self, candidate):
if candidate in self.members:
return True
return "%s not in %s" % (candidate, self.members)
def __repr__(self):
- return "one of %s" % ', '.join(self.members)
+ return "one of %s" % ', '... | Fix problem rendering oneof() predicate when the members aren't strings | ## Code Before:
class OneOf:
def __init__(self, members):
self.members = members
def __call__(self, candidate):
if candidate in self.members:
return True
return "%s not in %s" % (candidate, self.members)
def __repr__(self):
return "one of %s" % ', '.join(self.members)
def oneof(*members):
return OneOf... |
7955e777d6ba3bbbd104bd3916f131ab7fa8f8b5 | asyncmongo/__init__.py | asyncmongo/__init__.py | try:
import bson
except ImportError:
raise ImportError("bson library not installed. Install pymongo >= 1.9 https://github.com/mongodb/mongo-python-driver")
# also update in setup.py
version = "1.3"
version_info = (1, 3)
ASCENDING = 1
"""Ascending sort order."""
DESCENDING = -1
"""Descending sort order."""
GEO... | try:
import bson
except ImportError:
raise ImportError("bson library not installed. Install pymongo >= 1.9 https://github.com/mongodb/mongo-python-driver")
# also update in setup.py
version = "1.3"
version_info = (1, 3)
ASCENDING = 1
"""Ascending sort order."""
DESCENDING = -1
"""Descending sort order."""
GEO... | Support Sort Order For TEXT Index | Support Sort Order For TEXT Index
| Python | apache-2.0 | RealGeeks/asyncmongo | try:
import bson
except ImportError:
raise ImportError("bson library not installed. Install pymongo >= 1.9 https://github.com/mongodb/mongo-python-driver")
# also update in setup.py
version = "1.3"
version_info = (1, 3)
ASCENDING = 1
"""Ascending sort order."""
DESCENDING = -1
"""Des... | Support Sort Order For TEXT Index | ## Code Before:
try:
import bson
except ImportError:
raise ImportError("bson library not installed. Install pymongo >= 1.9 https://github.com/mongodb/mongo-python-driver")
# also update in setup.py
version = "1.3"
version_info = (1, 3)
ASCENDING = 1
"""Ascending sort order."""
DESCENDING = -1
"""Descending so... |
26efd98c88a627f76ebd0865053353eb7a30e3bb | .glerbl/repo_conf.py | .glerbl/repo_conf.py | checks = {
'pre-commit': [
# BEFORE_COMMIT in the root of the working tree can be used as
# reminder to do something before the next commit.
"no_before_commit",
# We only allow ASCII filenames.
"no_non_ascii_filenames",
# We don't allow trailing whitespaces.
... | import sys
import os
dirname = os.path.dirname(__file__)
python_path = os.path.join(os.path.dirname(dirname), "selenium_test", "lib")
if "PYTHONPATH" not in os.environ:
os.environ["PYTHONPATH"] = python_path
else:
os.environ["PYTHONPATH"] = python_path + ":" + os.environ["PYTHONPATH"]
checks = {
'pre-com... | Modify PYTHONPATH so that pylint is able to find wedutil. | Modify PYTHONPATH so that pylint is able to find wedutil.
| Python | mpl-2.0 | mangalam-research/wed,slattery/wed,lddubeau/wed,slattery/wed,mangalam-research/wed,slattery/wed,mangalam-research/wed,lddubeau/wed,mangalam-research/wed,lddubeau/wed,lddubeau/wed | + import sys
+ import os
+
+ dirname = os.path.dirname(__file__)
+
+ python_path = os.path.join(os.path.dirname(dirname), "selenium_test", "lib")
+ if "PYTHONPATH" not in os.environ:
+ os.environ["PYTHONPATH"] = python_path
+ else:
+ os.environ["PYTHONPATH"] = python_path + ":" + os.environ["PYTHONPATH"]
+
... | Modify PYTHONPATH so that pylint is able to find wedutil. | ## Code Before:
checks = {
'pre-commit': [
# BEFORE_COMMIT in the root of the working tree can be used as
# reminder to do something before the next commit.
"no_before_commit",
# We only allow ASCII filenames.
"no_non_ascii_filenames",
# We don't allow trailing whit... |
7608d0e89781f70fcb49e7dc3ee5cd57a094f18c | rx/__init__.py | rx/__init__.py | from .observable import Observable
from .anonymousobservable import AnonymousObservable
from .observer import Observer
from . import checkedobserver
from . import linq
from . import backpressure
try:
from asyncio import Future
except ImportError:
Future = None
# Rx configuration dictionary
config = {
"Fut... | from threading import Lock
from .observable import Observable
from .anonymousobservable import AnonymousObservable
from .observer import Observer
from . import checkedobserver
from . import linq
from . import backpressure
try:
from asyncio import Future
except ImportError:
Future = None
# Rx configuration di... | Make it possible to set custom Lock | Make it possible to set custom Lock
| Python | mit | ReactiveX/RxPY,ReactiveX/RxPY,dbrattli/RxPY | + from threading import Lock
+
from .observable import Observable
from .anonymousobservable import AnonymousObservable
from .observer import Observer
from . import checkedobserver
from . import linq
from . import backpressure
try:
from asyncio import Future
except ImportError:
Future = N... | Make it possible to set custom Lock | ## Code Before:
from .observable import Observable
from .anonymousobservable import AnonymousObservable
from .observer import Observer
from . import checkedobserver
from . import linq
from . import backpressure
try:
from asyncio import Future
except ImportError:
Future = None
# Rx configuration dictionary
con... |
0aa61fb32df9ae3ef9c465f4b246edf04897cd14 | staticfiles/views.py | staticfiles/views.py | from django.views.static import serve as django_serve
from staticfiles.resolvers import resolve
def serve(request, path, show_indexes=False):
"""
Serve static files from locations inferred from INSTALLED_APPS and
STATICFILES_DIRS.
To use, put a URL pattern such as::
(r'^(?P<path>.*)$', 'stat... | from django import http
from django.views.static import serve as django_serve
from staticfiles.resolvers import resolve
def serve(request, path, show_indexes=False):
"""
Serve static files from locations inferred from INSTALLED_APPS and
STATICFILES_DIRS.
To use, put a URL pattern such as::
(... | Make the staticfiles serve view raise a 404 for paths which could not be resolved. | Make the staticfiles serve view raise a 404 for paths which could not be resolved.
| Python | bsd-3-clause | tusbar/django-staticfiles,jezdez-archive/django-staticfiles,tusbar/django-staticfiles | + from django import http
from django.views.static import serve as django_serve
from staticfiles.resolvers import resolve
def serve(request, path, show_indexes=False):
"""
Serve static files from locations inferred from INSTALLED_APPS and
STATICFILES_DIRS.
To use, put a URL patter... | Make the staticfiles serve view raise a 404 for paths which could not be resolved. | ## Code Before:
from django.views.static import serve as django_serve
from staticfiles.resolvers import resolve
def serve(request, path, show_indexes=False):
"""
Serve static files from locations inferred from INSTALLED_APPS and
STATICFILES_DIRS.
To use, put a URL pattern such as::
(r'^(?P<p... |
979c56f882178ce49194850bd9e78c9dea4692dd | chardet/__init__.py | chardet/__init__.py |
from .compat import PY2, PY3
from .universaldetector import UniversalDetector
from .version import __version__, VERSION
def detect(byte_str):
"""
Detect the encoding of the given byte string.
:param byte_str: The byte sequence to examine.
:type byte_str: ``bytes`` or ``bytearray``
"""
... |
from .compat import PY2, PY3
from .universaldetector import UniversalDetector
from .version import __version__, VERSION
def detect(byte_str):
"""
Detect the encoding of the given byte string.
:param byte_str: The byte sequence to examine.
:type byte_str: ``bytes`` or ``bytearray``
"""
... | Remove unnecessary line from detect | Remove unnecessary line from detect
| Python | lgpl-2.1 | ddboline/chardet,chardet/chardet,chardet/chardet,ddboline/chardet |
from .compat import PY2, PY3
from .universaldetector import UniversalDetector
from .version import __version__, VERSION
def detect(byte_str):
"""
Detect the encoding of the given byte string.
:param byte_str: The byte sequence to examine.
:type byte_str: ``bytes``... | Remove unnecessary line from detect | ## Code Before:
from .compat import PY2, PY3
from .universaldetector import UniversalDetector
from .version import __version__, VERSION
def detect(byte_str):
"""
Detect the encoding of the given byte string.
:param byte_str: The byte sequence to examine.
:type byte_str: ``bytes`` or ``byte... |
9ddc63eb0e1e3612ac4a1ea5b95e405ca0915b52 | setup.py | setup.py |
from distutils.core import setup
setup(name="sysops-api",
version="1.0",
description="LinkedIn Redis / Cfengine API",
author = "Mike Svoboda",
author_email = "msvoboda@linkedin.com",
py_modules=['CacheExtractor', 'RedisFinder'],
data_files=[('/usr/local/bin', ['./scripts/extract_sys... |
from distutils.core import setup
setup(name="sysops-api",
version="1.0",
description="LinkedIn Redis / Cfengine API",
author="Mike Svoboda",
author_email="msvoboda@linkedin.com",
py_modules=['CacheExtractor', 'RedisFinder'],
scripts=['scripts/extract_sysops_cache.py',
... | Install scripts properly rather than as datafiles | Install scripts properly rather than as datafiles
- also fix whitespace
| Python | apache-2.0 | linkedin/sysops-api,linkedin/sysops-api,slietz/sysops-api,slietz/sysops-api |
from distutils.core import setup
setup(name="sysops-api",
version="1.0",
description="LinkedIn Redis / Cfengine API",
- author = "Mike Svoboda",
+ author="Mike Svoboda",
- author_email = "msvoboda@linkedin.com",
+ author_email="msvoboda@linkedin.com",
py_modules=['... | Install scripts properly rather than as datafiles | ## Code Before:
from distutils.core import setup
setup(name="sysops-api",
version="1.0",
description="LinkedIn Redis / Cfengine API",
author = "Mike Svoboda",
author_email = "msvoboda@linkedin.com",
py_modules=['CacheExtractor', 'RedisFinder'],
data_files=[('/usr/local/bin', ['./scr... |
2727fccdb3672e1c7b28e4ba94ec743b53298f26 | src/main.py | src/main.py | '''
Created on Aug 12, 2017
@author: Aditya
This is the main file and will import other modules/codes written for python tkinter demonstration
'''
import program1 as p1
import program2 as p2
import program3 as p3
import program4 as p4
import program5 as p5
import program6 as p6
import program7 as p7
i... | '''
Created on Aug 12, 2017
@author: Aditya
This is the main file and will import other modules/codes written for python tkinter demonstration
'''
import program1 as p1
import program2 as p2
import program3 as p3
import program4 as p4
import program5 as p5
import program6 as p6
import program7 as p7
i... | Include Text App in Main | Include Text App in Main | Python | mit | deshadi/python-gui-demos | '''
Created on Aug 12, 2017
@author: Aditya
This is the main file and will import other modules/codes written for python tkinter demonstration
'''
import program1 as p1
import program2 as p2
import program3 as p3
import program4 as p4
import program5 as p5
import program6 as ... | Include Text App in Main | ## Code Before:
'''
Created on Aug 12, 2017
@author: Aditya
This is the main file and will import other modules/codes written for python tkinter demonstration
'''
import program1 as p1
import program2 as p2
import program3 as p3
import program4 as p4
import program5 as p5
import program6 as p6
import program7 as p7
... |
1e327401d9c020bb7941b20ff51890ad1729973d | tests.py | tests.py | import pytest
from django.contrib.auth import get_user_model
from seleniumlogin import force_login
pytestmark = [pytest.mark.django_db(transaction=True)]
def test_non_authenticated_user_cannot_access_test_page(selenium, live_server):
selenium.get('{}/test/login_required/'.format(live_server.url))
assert 'fa... | import pytest
from django.contrib.auth import get_user_model
from seleniumlogin import force_login
pytestmark = [pytest.mark.django_db(transaction=True)]
def test_non_authenticated_user_cannot_access_test_page(selenium, live_server):
selenium.get('{}/test/login_required/'.format(live_server.url))
assert 'fa... | Rename test. The test tries to access a test page, not a blank page | Rename test. The test tries to access a test page, not a blank page
| Python | mit | feffe/django-selenium-login,feffe/django-selenium-login | import pytest
from django.contrib.auth import get_user_model
from seleniumlogin import force_login
pytestmark = [pytest.mark.django_db(transaction=True)]
def test_non_authenticated_user_cannot_access_test_page(selenium, live_server):
selenium.get('{}/test/login_required/'.format(live_server.... | Rename test. The test tries to access a test page, not a blank page | ## Code Before:
import pytest
from django.contrib.auth import get_user_model
from seleniumlogin import force_login
pytestmark = [pytest.mark.django_db(transaction=True)]
def test_non_authenticated_user_cannot_access_test_page(selenium, live_server):
selenium.get('{}/test/login_required/'.format(live_server.url)... |
741545dcf58fdfaf882d797d3ce4f7607ca0dad4 | kobo/client/commands/cmd_resubmit_tasks.py | kobo/client/commands/cmd_resubmit_tasks.py |
from __future__ import print_function
import sys
from kobo.client.task_watcher import TaskWatcher
from kobo.client import ClientCommand
class Resubmit_Tasks(ClientCommand):
"""resubmit failed tasks"""
enabled = True
def options(self):
self.parser.usage = "%%prog %s task_id [task_id...]" % sel... |
from __future__ import print_function
import sys
from kobo.client.task_watcher import TaskWatcher
from kobo.client import ClientCommand
class Resubmit_Tasks(ClientCommand):
"""resubmit failed tasks"""
enabled = True
def options(self):
self.parser.usage = "%%prog %s task_id [task_id...]" % sel... | Add --nowait option to resubmit-tasks cmd | Add --nowait option to resubmit-tasks cmd
In some use cases, waiting till the tasks finish is undesirable. Nowait
option should be provided.
| Python | lgpl-2.1 | release-engineering/kobo,release-engineering/kobo,release-engineering/kobo,release-engineering/kobo |
from __future__ import print_function
import sys
from kobo.client.task_watcher import TaskWatcher
from kobo.client import ClientCommand
class Resubmit_Tasks(ClientCommand):
"""resubmit failed tasks"""
enabled = True
def options(self):
self.parser.usage = "%%pro... | Add --nowait option to resubmit-tasks cmd | ## Code Before:
from __future__ import print_function
import sys
from kobo.client.task_watcher import TaskWatcher
from kobo.client import ClientCommand
class Resubmit_Tasks(ClientCommand):
"""resubmit failed tasks"""
enabled = True
def options(self):
self.parser.usage = "%%prog %s task_id [ta... |
8e7a92bce03ca472bc78bb9df5e2c9cf063c29b7 | temba/campaigns/tasks.py | temba/campaigns/tasks.py | from __future__ import unicode_literals
from datetime import datetime
from django.utils import timezone
from djcelery_transactions import task
from redis_cache import get_redis_connection
from .models import Campaign, EventFire
from django.conf import settings
import redis
from temba.msgs.models import HANDLER_QUEUE, ... | from __future__ import unicode_literals
from datetime import datetime
from django.utils import timezone
from djcelery_transactions import task
from redis_cache import get_redis_connection
from .models import Campaign, EventFire
from django.conf import settings
import redis
from temba.msgs.models import HANDLER_QUEUE, ... | Use correct field to get org from | Use correct field to get org from
| Python | agpl-3.0 | harrissoerja/rapidpro,pulilab/rapidpro,pulilab/rapidpro,reyrodrigues/EU-SMS,tsotetsi/textily-web,harrissoerja/rapidpro,tsotetsi/textily-web,pulilab/rapidpro,tsotetsi/textily-web,Thapelo-Tsotetsi/rapidpro,Thapelo-Tsotetsi/rapidpro,ewheeler/rapidpro,praekelt/rapidpro,harrissoerja/rapidpro,praekelt/rapidpro,reyrodrigues/E... | from __future__ import unicode_literals
from datetime import datetime
from django.utils import timezone
from djcelery_transactions import task
from redis_cache import get_redis_connection
from .models import Campaign, EventFire
from django.conf import settings
import redis
from temba.msgs.models im... | Use correct field to get org from | ## Code Before:
from __future__ import unicode_literals
from datetime import datetime
from django.utils import timezone
from djcelery_transactions import task
from redis_cache import get_redis_connection
from .models import Campaign, EventFire
from django.conf import settings
import redis
from temba.msgs.models import... |
1e2086b868861034d89138349c4da909f380f19e | feedback/views.py | feedback/views.py | from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from rest_framework import serializers, status
from rest_framework.response import Response
from rest_framework.views import APIView
from .models import Feedback
class FeedbackSerializer(serializers.ModelSeriali... | from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from rest_framework import serializers, status
from rest_framework.response import Response
from rest_framework.views import APIView
from .models import Feedback
class FeedbackSerializer(serializers.ModelSeriali... | Make feedback compatible with DRF >3.3.0 | Make feedback compatible with DRF >3.3.0
| Python | mit | City-of-Helsinki/digihel,City-of-Helsinki/digihel,City-of-Helsinki/digihel,City-of-Helsinki/digihel | from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from rest_framework import serializers, status
from rest_framework.response import Response
from rest_framework.views import APIView
from .models import Feedback
class FeedbackSerializer(seri... | Make feedback compatible with DRF >3.3.0 | ## Code Before:
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from rest_framework import serializers, status
from rest_framework.response import Response
from rest_framework.views import APIView
from .models import Feedback
class FeedbackSerializer(serializ... |
90bdcad66a6f29c9e3d731b5b09b0a2ba477ae2f | tviit/urls.py | tviit/urls.py | from django.conf.urls import include, url
from django.contrib import admin
from . import views
urlpatterns = [
url(r'^', views.IndexView.as_view(), name='tviit_index'),
]
| from django.conf.urls import include, url
from django.contrib import admin
from . import views
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='tviit_index'),
url(r'create/$', views.create_tviit, name="create_tviit"),
]
| Create url-patterns for tviit creation | Create url-patterns for tviit creation
| Python | mit | DeWaster/Tviserrys,DeWaster/Tviserrys | from django.conf.urls import include, url
from django.contrib import admin
from . import views
urlpatterns = [
- url(r'^', views.IndexView.as_view(), name='tviit_index'),
+ url(r'^$', views.IndexView.as_view(), name='tviit_index'),
+ url(r'create/$', views.create_tviit, name="create_tviit"),
... | Create url-patterns for tviit creation | ## Code Before:
from django.conf.urls import include, url
from django.contrib import admin
from . import views
urlpatterns = [
url(r'^', views.IndexView.as_view(), name='tviit_index'),
]
## Instruction:
Create url-patterns for tviit creation
## Code After:
from django.conf.urls import include, url
from django.co... |
881222a49c6b3e8792adf5754c61992bd12c7b28 | tests/test_conduction.py | tests/test_conduction.py |
"""Test Mongo Conduction."""
import logging
import pymongo
from mockupdb import go
from pymongo.errors import OperationFailure
from conduction.server import get_mockup, main_loop
from tests import unittest # unittest2 on Python 2.6.
class ConductionTest(unittest.TestCase):
def setUp(self):
self.mocku... |
"""Test Mongo Conduction."""
import logging
import pymongo
from mockupdb import go
from pymongo.errors import OperationFailure
from conduction.server import get_mockup, main_loop
from tests import unittest # unittest2 on Python 2.6.
class ConductionTest(unittest.TestCase):
def setUp(self):
self.mocku... | Test root URI and 404s. | Test root URI and 404s.
| Python | apache-2.0 | ajdavis/mongo-conduction |
"""Test Mongo Conduction."""
import logging
import pymongo
from mockupdb import go
from pymongo.errors import OperationFailure
from conduction.server import get_mockup, main_loop
from tests import unittest # unittest2 on Python 2.6.
class ConductionTest(unittest.TestCase):
def s... | Test root URI and 404s. | ## Code Before:
"""Test Mongo Conduction."""
import logging
import pymongo
from mockupdb import go
from pymongo.errors import OperationFailure
from conduction.server import get_mockup, main_loop
from tests import unittest # unittest2 on Python 2.6.
class ConductionTest(unittest.TestCase):
def setUp(self):
... |
b8350e91d7bd1e3a775ed230820c96a180a2ad02 | tests/test_solver.py | tests/test_solver.py | from tinyik import Link, Joint, FKSolver
from .utils import x, y, z, theta, approx_eq
def test_forward_kinematics():
fk = FKSolver([
Joint('z'), Link([1., 0., 0.]), Joint('y'), Link([1., 0., 0.])
])
assert all(fk.solve([0., 0.]) == [2., 0., 0.])
assert approx_eq(fk.solve([theta, theta]), [x,... | from tinyik import Link, Joint, FKSolver, CCDFKSolver, CCDIKSolver
from .utils import x, y, z, theta, approx_eq
components = [Joint('z'), Link([1., 0., 0.]), Joint('y'), Link([1., 0., 0.])]
predicted = [2., 0., 0.]
def test_fk():
fk = FKSolver(components)
assert all(fk.solve([0., 0.]) == predicted)
as... | Add tests for CCD IK solver | Add tests for CCD IK solver
| Python | mit | lanius/tinyik | - from tinyik import Link, Joint, FKSolver
+ from tinyik import Link, Joint, FKSolver, CCDFKSolver, CCDIKSolver
from .utils import x, y, z, theta, approx_eq
- def test_forward_kinematics():
- fk = FKSolver([
- Joint('z'), Link([1., 0., 0.]), Joint('y'), Link([1., 0., 0.])
+ components = [Joint('z... | Add tests for CCD IK solver | ## Code Before:
from tinyik import Link, Joint, FKSolver
from .utils import x, y, z, theta, approx_eq
def test_forward_kinematics():
fk = FKSolver([
Joint('z'), Link([1., 0., 0.]), Joint('y'), Link([1., 0., 0.])
])
assert all(fk.solve([0., 0.]) == [2., 0., 0.])
assert approx_eq(fk.solve([the... |
35594a4f8c549d507c7d7030141ae511aed57c09 | workflowmax/__init__.py | workflowmax/__init__.py | from .api import WorkflowMax # noqa
__version__ = "0.1.0"
| from .api import WorkflowMax # noqa
from .credentials import Credentials # noqa
__version__ = "0.1.0"
| Add Credentials to root namespace | Add Credentials to root namespace
| Python | bsd-3-clause | ABASystems/pyworkflowmax | from .api import WorkflowMax # noqa
+ from .credentials import Credentials # noqa
__version__ = "0.1.0"
| Add Credentials to root namespace | ## Code Before:
from .api import WorkflowMax # noqa
__version__ = "0.1.0"
## Instruction:
Add Credentials to root namespace
## Code After:
from .api import WorkflowMax # noqa
from .credentials import Credentials # noqa
__version__ = "0.1.0"
|
ab5aac0c9b0e075901c4cd8dd5d134e79f0e0110 | brasileirao/spiders/results_spider.py | brasileirao/spiders/results_spider.py | import scrapy
import scrapy.selector
from brasileirao.items import BrasileiraoItem
import hashlib
class ResultsSpider(scrapy.Spider):
name = "results"
start_urls = [
'https://esporte.uol.com.br/futebol/campeonatos/brasileirao/jogos/',
]
def parse(self, response):
actual_round = 0
... |
import scrapy
import scrapy.selector
from brasileirao.items import BrasileiraoItem
import hashlib
class ResultsSpider(scrapy.Spider):
name = "results"
start_urls = [
'https://esporte.uol.com.br/futebol/campeonatos/brasileirao/jogos/',
]
def parse(self, response):
actual_round = 0
... | Set utf-8 as default encoding. | Set utf-8 as default encoding.
| Python | mit | pghilardi/live-football-client | +
import scrapy
import scrapy.selector
from brasileirao.items import BrasileiraoItem
import hashlib
class ResultsSpider(scrapy.Spider):
name = "results"
start_urls = [
'https://esporte.uol.com.br/futebol/campeonatos/brasileirao/jogos/',
]
def parse(self, response... | Set utf-8 as default encoding. | ## Code Before:
import scrapy
import scrapy.selector
from brasileirao.items import BrasileiraoItem
import hashlib
class ResultsSpider(scrapy.Spider):
name = "results"
start_urls = [
'https://esporte.uol.com.br/futebol/campeonatos/brasileirao/jogos/',
]
def parse(self, response):
actu... |
a3c1822dd2942de4b6bf5cac14039e6789babf85 | wafer/pages/admin.py | wafer/pages/admin.py | from django.contrib import admin
from wafer.pages.models import File, Page
class PageAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("name",)}
list_display = ('name', 'slug', 'get_people_display_names', 'get_in_schedule')
admin.site.register(Page, PageAdmin)
admin.site.register(File)
| from django.contrib import admin
from wafer.pages.models import File, Page
from reversion.admin import VersionAdmin
class PageAdmin(VersionAdmin, admin.ModelAdmin):
prepopulated_fields = {"slug": ("name",)}
list_display = ('name', 'slug', 'get_people_display_names', 'get_in_schedule')
admin.site.register(... | Add reversion support to Pages | Add reversion support to Pages
| Python | isc | CTPUG/wafer,CTPUG/wafer,CTPUG/wafer,CTPUG/wafer | from django.contrib import admin
from wafer.pages.models import File, Page
+ from reversion.admin import VersionAdmin
+
- class PageAdmin(admin.ModelAdmin):
+ class PageAdmin(VersionAdmin, admin.ModelAdmin):
prepopulated_fields = {"slug": ("name",)}
list_display = ('name', 'slug', 'get_people_... | Add reversion support to Pages | ## Code Before:
from django.contrib import admin
from wafer.pages.models import File, Page
class PageAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("name",)}
list_display = ('name', 'slug', 'get_people_display_names', 'get_in_schedule')
admin.site.register(Page, PageAdmin)
admin.site.register(Fil... |
4076fb322814848d802d1f925d163e90b3d629a9 | selenium_testcase/testcases/forms.py | selenium_testcase/testcases/forms.py |
from __future__ import absolute_import
from selenium.webdriver.common.by import By
from .utils import wait_for
class FormTestMixin:
# default search element
form_search_list = (
(By.ID, '{}',),
(By.NAME, '{}',),
(By.XPATH, '//form[@action="{}"]',),
(By.XPATH, '//form[@name=... |
from __future__ import absolute_import
from selenium.webdriver.common.by import By
from .utils import wait_for
class FormTestMixin:
# default search element
form_search_list = (
(By.ID, '{}',),
(By.NAME, '{}',),
(By.XPATH, '//form[@action="{}"]',),
(By.XPATH, '//form[@name=... | Split get_input from set_input in FormTestMixin. | Split get_input from set_input in FormTestMixin.
In order to reduce side-effects, this commit moves the @wait_for to
a get_input method and set_input operates immediately.
| Python | bsd-3-clause | nimbis/django-selenium-testcase,nimbis/django-selenium-testcase |
from __future__ import absolute_import
from selenium.webdriver.common.by import By
from .utils import wait_for
class FormTestMixin:
# default search element
form_search_list = (
(By.ID, '{}',),
(By.NAME, '{}',),
(By.XPATH, '//form[@action="{}"]',),
... | Split get_input from set_input in FormTestMixin. | ## Code Before:
from __future__ import absolute_import
from selenium.webdriver.common.by import By
from .utils import wait_for
class FormTestMixin:
# default search element
form_search_list = (
(By.ID, '{}',),
(By.NAME, '{}',),
(By.XPATH, '//form[@action="{}"]',),
(By.XPATH... |
149a8091333766068cac445db770ea73055d8647 | simuvex/procedures/stubs/UserHook.py | simuvex/procedures/stubs/UserHook.py | import simuvex
class UserHook(simuvex.SimProcedure):
NO_RET = True
# pylint: disable=arguments-differ
def run(self, user_func=None, user_kwargs=None, default_return_addr=None):
result = user_func(self.state, **user_kwargs)
if result is None:
self.add_successor(self.state, defau... | import simuvex
class UserHook(simuvex.SimProcedure):
NO_RET = True
# pylint: disable=arguments-differ
def run(self, user_func=None, user_kwargs=None, default_return_addr=None, length=None):
result = user_func(self.state, **user_kwargs)
if result is None:
self.add_successor(self... | Make the userhook take the length arg b/c why not | Make the userhook take the length arg b/c why not
| Python | bsd-2-clause | axt/angr,schieb/angr,tyb0807/angr,chubbymaggie/angr,chubbymaggie/simuvex,chubbymaggie/angr,chubbymaggie/simuvex,f-prettyland/angr,axt/angr,angr/angr,f-prettyland/angr,tyb0807/angr,schieb/angr,axt/angr,chubbymaggie/angr,f-prettyland/angr,iamahuman/angr,tyb0807/angr,iamahuman/angr,angr/angr,iamahuman/angr,angr/angr,schie... | import simuvex
class UserHook(simuvex.SimProcedure):
NO_RET = True
# pylint: disable=arguments-differ
- def run(self, user_func=None, user_kwargs=None, default_return_addr=None):
+ def run(self, user_func=None, user_kwargs=None, default_return_addr=None, length=None):
result = us... | Make the userhook take the length arg b/c why not | ## Code Before:
import simuvex
class UserHook(simuvex.SimProcedure):
NO_RET = True
# pylint: disable=arguments-differ
def run(self, user_func=None, user_kwargs=None, default_return_addr=None):
result = user_func(self.state, **user_kwargs)
if result is None:
self.add_successor(s... |
8528beef5d10355af07f641b4987df3cd64a7b0f | sprockets/mixins/metrics/__init__.py | sprockets/mixins/metrics/__init__.py | from .influxdb import InfluxDBMixin
from .statsd import StatsdMixin
version_info = (1, 0, 0)
__version__ = '.'.join(str(v) for v in version_info)
__all__ = ['InfluxDBMixin', 'StatsdMixin']
| try:
from .influxdb import InfluxDBMixin
from .statsd import StatsdMixin
except ImportError as error:
def InfluxDBMixin(*args, **kwargs):
raise error
def StatsdMixin(*args, **kwargs):
raise error
version_info = (1, 0, 0)
__version__ = '.'.join(str(v) for v in version_info)
__all__ = ['... | Make it safe to import __version__. | Make it safe to import __version__.
| Python | bsd-3-clause | sprockets/sprockets.mixins.metrics | + try:
- from .influxdb import InfluxDBMixin
+ from .influxdb import InfluxDBMixin
- from .statsd import StatsdMixin
+ from .statsd import StatsdMixin
+ except ImportError as error:
+ def InfluxDBMixin(*args, **kwargs):
+ raise error
+
+ def StatsdMixin(*args, **kwargs):
+ raise error
... | Make it safe to import __version__. | ## Code Before:
from .influxdb import InfluxDBMixin
from .statsd import StatsdMixin
version_info = (1, 0, 0)
__version__ = '.'.join(str(v) for v in version_info)
__all__ = ['InfluxDBMixin', 'StatsdMixin']
## Instruction:
Make it safe to import __version__.
## Code After:
try:
from .influxdb import InfluxDBMixin
... |
7b1d520278b8fe33b68103d26f9aa7bb945f6791 | cryptography/hazmat/backends/__init__.py | cryptography/hazmat/backends/__init__.py |
from cryptography.hazmat.backends import openssl
from cryptography.hazmat.bindings.commoncrypto.binding import (
Binding as CommonCryptoBinding
)
_ALL_BACKENDS = [openssl.backend]
if CommonCryptoBinding.is_available():
from cryptography.hazmat.backends import commoncrypto
_ALL_BACKENDS.append(commoncrypt... |
from cryptography.hazmat.backends import openssl
from cryptography.hazmat.backends.multibackend import MultiBackend
from cryptography.hazmat.bindings.commoncrypto.binding import (
Binding as CommonCryptoBinding
)
_ALL_BACKENDS = [openssl.backend]
if CommonCryptoBinding.is_available():
from cryptography.hazma... | Make the default backend be a multi-backend | Make the default backend be a multi-backend
| Python | bsd-3-clause | bwhmather/cryptography,Ayrx/cryptography,bwhmather/cryptography,Lukasa/cryptography,Ayrx/cryptography,bwhmather/cryptography,kimvais/cryptography,skeuomorf/cryptography,dstufft/cryptography,kimvais/cryptography,Lukasa/cryptography,dstufft/cryptography,Ayrx/cryptography,skeuomorf/cryptography,Lukasa/cryptography,sholsap... |
from cryptography.hazmat.backends import openssl
+ from cryptography.hazmat.backends.multibackend import MultiBackend
from cryptography.hazmat.bindings.commoncrypto.binding import (
Binding as CommonCryptoBinding
)
_ALL_BACKENDS = [openssl.backend]
if CommonCryptoBinding.is_available():
f... | Make the default backend be a multi-backend | ## Code Before:
from cryptography.hazmat.backends import openssl
from cryptography.hazmat.bindings.commoncrypto.binding import (
Binding as CommonCryptoBinding
)
_ALL_BACKENDS = [openssl.backend]
if CommonCryptoBinding.is_available():
from cryptography.hazmat.backends import commoncrypto
_ALL_BACKENDS.ap... |
5957999c52f939691cbe6b8dd5aa929980a24501 | tests/unit/test_start.py | tests/unit/test_start.py | import pytest
from iwant_bot import start
def test_add():
assert start.add_numbers(0, 0) == 0
assert start.add_numbers(1, 1) == 2
| from iwant_bot import start
def test_add():
assert start.add_numbers(0, 0) == 0
assert start.add_numbers(1, 1) == 2
| Remove the unused pytest import | Remove the unused pytest import
| Python | mit | kiwicom/iwant-bot | - import pytest
-
-
from iwant_bot import start
def test_add():
assert start.add_numbers(0, 0) == 0
assert start.add_numbers(1, 1) == 2
| Remove the unused pytest import | ## Code Before:
import pytest
from iwant_bot import start
def test_add():
assert start.add_numbers(0, 0) == 0
assert start.add_numbers(1, 1) == 2
## Instruction:
Remove the unused pytest import
## Code After:
from iwant_bot import start
def test_add():
assert start.add_numbers(0, 0) == 0
assert s... |
f5d4da9fa71dbb59a9459e376fde8840037bf39a | account_banking_sepa_credit_transfer/__init__.py | account_banking_sepa_credit_transfer/__init__.py |
from . import wizard
from . import models
|
from . import wizard
| Remove import models from init in sepa_credit_transfer | Remove import models from init in sepa_credit_transfer
| Python | agpl-3.0 | open-synergy/bank-payment,sergio-incaser/bank-payment,hbrunn/bank-payment,sergio-teruel/bank-payment,ndtran/bank-payment,David-Amaro/bank-payment,rlizana/bank-payment,sergiocorato/bank-payment,damdam-s/bank-payment,CompassionCH/bank-payment,CompassionCH/bank-payment,incaser/bank-payment,Antiun/bank-payment,sergio-terue... |
from . import wizard
- from . import models
| Remove import models from init in sepa_credit_transfer | ## Code Before:
from . import wizard
from . import models
## Instruction:
Remove import models from init in sepa_credit_transfer
## Code After:
from . import wizard
|
39dbbac659e9ae9c1bbad8a979cc99ef6eafaeff | models.py | models.py | import os
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL')
db = SQLAlchemy(app)
class FoodMenu(db.Model):
id = db.Column(db.Integer, primary_key=True)
result = db.Column(db.Text)
def __init__(self, resu... | import os
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL')
db = SQLAlchemy(app)
class FoodMenu(db.Model):
id = db.Column(db.Integer, primary_key=True)
result = db.Column(db.Text)
def __init__(self, resu... | Include class name in model representations | Include class name in model representations
| Python | mit | alykhank/FoodMenu,alykhank/FoodMenu,alykhank/FoodMenu | import os
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL')
db = SQLAlchemy(app)
class FoodMenu(db.Model):
id = db.Column(db.Integer, primary_key=True)
result = db.Column(db.Text)
... | Include class name in model representations | ## Code Before:
import os
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL')
db = SQLAlchemy(app)
class FoodMenu(db.Model):
id = db.Column(db.Integer, primary_key=True)
result = db.Column(db.Text)
def __i... |
e16c65ec8c774cc27f9f7aa43e88521c3854b6b7 | ella/imports/management/commands/fetchimports.py | ella/imports/management/commands/fetchimports.py | from django.core.management.base import BaseCommand
from optparse import make_option
class Command(BaseCommand):
help = 'Fetch all registered imports'
def handle(self, *test_labels, **options):
from ella.imports.models import fetch_all
fetch_all()
| from django.core.management.base import NoArgsCommand
from optparse import make_option
import sys
class Command(NoArgsCommand):
help = 'Fetch all registered imports'
def handle(self, *test_labels, **options):
from ella.imports.models import fetch_all
errors = fetch_all()
if errors:
... | Return exit code (count of errors) | Return exit code (count of errors)
git-svn-id: 6ce22b13eace8fe533dbb322c2bb0986ea4cd3e6@520 2d143e24-0a30-0410-89d7-a2e95868dc81
| Python | bsd-3-clause | MichalMaM/ella,MichalMaM/ella,WhiskeyMedia/ella,whalerock/ella,ella/ella,whalerock/ella,WhiskeyMedia/ella,petrlosa/ella,petrlosa/ella,whalerock/ella | - from django.core.management.base import BaseCommand
+ from django.core.management.base import NoArgsCommand
from optparse import make_option
+ import sys
- class Command(BaseCommand):
+ class Command(NoArgsCommand):
help = 'Fetch all registered imports'
def handle(self, *test_labels, **options):
... | Return exit code (count of errors) | ## Code Before:
from django.core.management.base import BaseCommand
from optparse import make_option
class Command(BaseCommand):
help = 'Fetch all registered imports'
def handle(self, *test_labels, **options):
from ella.imports.models import fetch_all
fetch_all()
## Instruction:
Return exit co... |
45c400e02fbeb5b455e27fef81e47e45f274eaec | core/forms.py | core/forms.py |
from django import forms
class GameForm(forms.Form):
amount = forms.IntegerField()
def __init__(self, *args, **kwargs):
super(GameForm, self).__init__(*args, **kwargs)
for name, field in self.fields.items():
if isinstance(field, forms.IntegerField):
self.fields[n... |
from django import forms
class GameForm(forms.Form):
amount = forms.IntegerField(initial=100)
def __init__(self, *args, **kwargs):
super(GameForm, self).__init__(*args, **kwargs)
for name, field in self.fields.items():
if isinstance(field, forms.IntegerField):
se... | Add a default bet amount. | Add a default bet amount.
| Python | bsd-2-clause | stephenmcd/gamblor,stephenmcd/gamblor |
from django import forms
class GameForm(forms.Form):
- amount = forms.IntegerField()
+ amount = forms.IntegerField(initial=100)
def __init__(self, *args, **kwargs):
super(GameForm, self).__init__(*args, **kwargs)
for name, field in self.fields.items():
... | Add a default bet amount. | ## Code Before:
from django import forms
class GameForm(forms.Form):
amount = forms.IntegerField()
def __init__(self, *args, **kwargs):
super(GameForm, self).__init__(*args, **kwargs)
for name, field in self.fields.items():
if isinstance(field, forms.IntegerField):
... |
fcc571d2f4c35ac8f0e94e51e6ac94a0c051062d | src/rinoh/__init__.py | src/rinoh/__init__.py |
import os
import sys
from importlib import import_module
from .version import __version__, __release_date__
if sys.version_info < (3, 3):
print('rinohtype requires Python 3.3 or higher')
sys.exit(1)
CORE_MODULES = ['annotation', 'color', 'dimension', 'document', 'draw', 'float',
'flowable... |
import os
import sys
from importlib import import_module
from .version import __version__, __release_date__
if sys.version_info < (3, 3):
print('rinohtype requires Python 3.3 or higher')
sys.exit(1)
CORE_MODULES = ['annotation', 'attribute', 'color', 'dimension', 'document',
'draw', 'elem... | Update the top-level rinoh package | Update the top-level rinoh package
Make all symbols and modules relevant to users available directly
from the rinoh package.
| Python | agpl-3.0 | brechtm/rinohtype,brechtm/rinohtype,brechtm/rinohtype |
import os
import sys
from importlib import import_module
from .version import __version__, __release_date__
if sys.version_info < (3, 3):
print('rinohtype requires Python 3.3 or higher')
sys.exit(1)
- CORE_MODULES = ['annotation', 'color', 'dimension', 'document', 'draw', 'flo... | Update the top-level rinoh package | ## Code Before:
import os
import sys
from importlib import import_module
from .version import __version__, __release_date__
if sys.version_info < (3, 3):
print('rinohtype requires Python 3.3 or higher')
sys.exit(1)
CORE_MODULES = ['annotation', 'color', 'dimension', 'document', 'draw', 'float',
... |
f9293d838a21f495ea9b56cbe0f6f75533360aed | pyinfra/api/config.py | pyinfra/api/config.py | import six
from pyinfra import logger
class Config(object):
'''
The default/base configuration options for a pyinfra deploy.
'''
state = None
# % of hosts which have to fail for all operations to stop
FAIL_PERCENT = None
# Seconds to timeout SSH connections
CONNECT_TIMEOUT = 10
... | import six
class Config(object):
'''
The default/base configuration options for a pyinfra deploy.
'''
state = None
# % of hosts which have to fail for all operations to stop
FAIL_PERCENT = None
# Seconds to timeout SSH connections
CONNECT_TIMEOUT = 10
# Temporary directory (on ... | Remove support for deprecated `Config.TIMEOUT`. | Remove support for deprecated `Config.TIMEOUT`.
| Python | mit | Fizzadar/pyinfra,Fizzadar/pyinfra | import six
-
- from pyinfra import logger
class Config(object):
'''
The default/base configuration options for a pyinfra deploy.
'''
state = None
# % of hosts which have to fail for all operations to stop
FAIL_PERCENT = None
# Seconds to timeout SSH connecti... | Remove support for deprecated `Config.TIMEOUT`. | ## Code Before:
import six
from pyinfra import logger
class Config(object):
'''
The default/base configuration options for a pyinfra deploy.
'''
state = None
# % of hosts which have to fail for all operations to stop
FAIL_PERCENT = None
# Seconds to timeout SSH connections
CONNECT_... |
22f3d6d6fdc3e5f07ead782828b406c9a27d0199 | UDPSender.py | UDPSender.py | from can import Listener
import socket
class UDPSender(Listener):
dataConvert = {"0x600": {"String":"RPM:",
"Slot":0,
"Conversion":1},
"0x601": {"String":"OIL:",
"Slot":2,
"Convers... | from can import Listener
from socket import socket
class UDPSender(Listener):
dataConvert = {"0x600": {"String":"RPM:",
"Slot":0,
"Conversion":1},
"0x601": {"String":"OIL:",
"Slot":2,
... | Change of import of libraries. | Change of import of libraries.
Tried to fix issue displayed below.
[root@alarm BeagleDash]# python3.3 CANtoUDP.py
Traceback (most recent call last):
File "CANtoUDP.py", line 10, in <module>
listeners = [csv, UDPSender()]
TypeError: 'module' object is not callable
Exception AttributeError: "'super' object has no attri... | Python | mit | TAURacing/BeagleDash | from can import Listener
- import socket
+ from socket import socket
class UDPSender(Listener):
dataConvert = {"0x600": {"String":"RPM:",
"Slot":0,
"Conversion":1},
"0x601": {"String":"OIL:",
"... | Change of import of libraries. | ## Code Before:
from can import Listener
import socket
class UDPSender(Listener):
dataConvert = {"0x600": {"String":"RPM:",
"Slot":0,
"Conversion":1},
"0x601": {"String":"OIL:",
"Slot":2,
... |
1da2c0e00d43c4fb9a7039e98401d333d387a057 | saleor/search/views.py | saleor/search/views.py | from __future__ import unicode_literals
from django.core.paginator import Paginator, InvalidPage
from django.conf import settings
from django.http import Http404
from django.shortcuts import render
from .forms import SearchForm
from ..product.utils import products_with_details
def paginate_results(results, get_data,... | from __future__ import unicode_literals
from django.core.paginator import Paginator, InvalidPage
from django.conf import settings
from django.http import Http404
from django.shortcuts import render
from .forms import SearchForm
from ..product.utils import products_with_details
def paginate_results(results, get_data,... | Fix empty search results logic | Fix empty search results logic
| Python | bsd-3-clause | mociepka/saleor,jreigel/saleor,itbabu/saleor,maferelo/saleor,KenMutemi/saleor,HyperManTT/ECommerceSaleor,HyperManTT/ECommerceSaleor,HyperManTT/ECommerceSaleor,KenMutemi/saleor,tfroehlich82/saleor,jreigel/saleor,KenMutemi/saleor,itbabu/saleor,car3oon/saleor,maferelo/saleor,car3oon/saleor,UITools/saleor,maferelo/saleor,i... | from __future__ import unicode_literals
from django.core.paginator import Paginator, InvalidPage
from django.conf import settings
from django.http import Http404
from django.shortcuts import render
from .forms import SearchForm
from ..product.utils import products_with_details
def paginate_resu... | Fix empty search results logic | ## Code Before:
from __future__ import unicode_literals
from django.core.paginator import Paginator, InvalidPage
from django.conf import settings
from django.http import Http404
from django.shortcuts import render
from .forms import SearchForm
from ..product.utils import products_with_details
def paginate_results(re... |
6c9b0b0c7e78524ea889f8a89c2eba8acb57f782 | gaphor/ui/iconname.py | gaphor/ui/iconname.py |
from gaphor import UML
import re
from functools import singledispatch
TO_KEBAB = re.compile(r"([a-z])([A-Z]+)")
def to_kebab_case(s):
return TO_KEBAB.sub("\\1-\\2", s).lower()
@singledispatch
def get_icon_name(element):
"""
Get an icon name for a UML model element.
"""
return "gaphor-" + to_k... |
from gaphor import UML
import re
from functools import singledispatch
TO_KEBAB = re.compile(r"([a-z])([A-Z]+)")
def to_kebab_case(s):
return TO_KEBAB.sub("\\1-\\2", s).lower()
@singledispatch
def get_icon_name(element):
"""
Get an icon name for a UML model element.
"""
return "gaphor-" + to_k... | Fix stereotype icon in namespace view | Fix stereotype icon in namespace view
| Python | lgpl-2.1 | amolenaar/gaphor,amolenaar/gaphor |
from gaphor import UML
import re
from functools import singledispatch
TO_KEBAB = re.compile(r"([a-z])([A-Z]+)")
def to_kebab_case(s):
return TO_KEBAB.sub("\\1-\\2", s).lower()
@singledispatch
def get_icon_name(element):
"""
Get an icon name for a UML model element.
... | Fix stereotype icon in namespace view | ## Code Before:
from gaphor import UML
import re
from functools import singledispatch
TO_KEBAB = re.compile(r"([a-z])([A-Z]+)")
def to_kebab_case(s):
return TO_KEBAB.sub("\\1-\\2", s).lower()
@singledispatch
def get_icon_name(element):
"""
Get an icon name for a UML model element.
"""
return ... |
bb34b21ebd2378f944498708ac4f13d16aa61aa1 | src/mist/io/tests/api/features/steps/backends.py | src/mist/io/tests/api/features/steps/backends.py | from behave import *
@given(u'"{text}" backend added')
def given_backend(context, text):
backends = context.client.list_backends()
for backend in backends:
if text in backend['title']:
return
@when(u'I list backends')
def list_backends(context):
context.backends = context.client.lis... | from behave import *
@given(u'"{text}" backend added through api')
def given_backend(context, text):
backends = context.client.list_backends()
for backend in backends:
if text in backend['title']:
return
@when(u'I list backends')
def list_backends(context):
context.backends = contex... | Rename Behave steps for api tests | Rename Behave steps for api tests
| Python | agpl-3.0 | johnnyWalnut/mist.io,DimensionDataCBUSydney/mist.io,zBMNForks/mist.io,afivos/mist.io,Lao-liu/mist.io,Lao-liu/mist.io,munkiat/mist.io,kelonye/mist.io,kelonye/mist.io,afivos/mist.io,Lao-liu/mist.io,Lao-liu/mist.io,DimensionDataCBUSydney/mist.io,johnnyWalnut/mist.io,zBMNForks/mist.io,DimensionDataCBUSydney/mist.io,Dimensi... | from behave import *
- @given(u'"{text}" backend added')
+ @given(u'"{text}" backend added through api')
def given_backend(context, text):
backends = context.client.list_backends()
for backend in backends:
if text in backend['title']:
return
@when(u'I list backen... | Rename Behave steps for api tests | ## Code Before:
from behave import *
@given(u'"{text}" backend added')
def given_backend(context, text):
backends = context.client.list_backends()
for backend in backends:
if text in backend['title']:
return
@when(u'I list backends')
def list_backends(context):
context.backends = co... |
6f42f03f950e4c3967eb1efd7feb9364c9fbaf1f | google.py | google.py | import os
from werkzeug.contrib.fixers import ProxyFix
from flask import Flask, redirect, url_for
from flask_dance.contrib.google import make_google_blueprint, google
from raven.contrib.flask import Sentry
app = Flask(__name__)
app.wsgi_app = ProxyFix(app.wsgi_app)
sentry = Sentry(app)
app.secret_key = os.environ.get(... | import os
from werkzeug.contrib.fixers import ProxyFix
from flask import Flask, redirect, url_for
from flask_dance.contrib.google import make_google_blueprint, google
from raven.contrib.flask import Sentry
app = Flask(__name__)
app.wsgi_app = ProxyFix(app.wsgi_app)
sentry = Sentry(app)
app.secret_key = os.environ.get(... | Use userinfo URI for user profile info | Use userinfo URI for user profile info
| Python | mit | singingwolfboy/flask-dance-google | import os
from werkzeug.contrib.fixers import ProxyFix
from flask import Flask, redirect, url_for
from flask_dance.contrib.google import make_google_blueprint, google
from raven.contrib.flask import Sentry
app = Flask(__name__)
app.wsgi_app = ProxyFix(app.wsgi_app)
sentry = Sentry(app)
app.secret_k... | Use userinfo URI for user profile info | ## Code Before:
import os
from werkzeug.contrib.fixers import ProxyFix
from flask import Flask, redirect, url_for
from flask_dance.contrib.google import make_google_blueprint, google
from raven.contrib.flask import Sentry
app = Flask(__name__)
app.wsgi_app = ProxyFix(app.wsgi_app)
sentry = Sentry(app)
app.secret_key =... |
ad73789f74106a2d6014a2f737578494d2d21fbf | virtool/api/processes.py | virtool/api/processes.py | import virtool.http.routes
import virtool.utils
from virtool.api.utils import json_response
routes = virtool.http.routes.Routes()
@routes.get("/api/processes")
async def find(req):
db = req.app["db"]
documents = [virtool.utils.base_processor(d) async for d in db.processes.find()]
return json_response(d... | import virtool.http.routes
import virtool.utils
from virtool.api.utils import json_response
routes = virtool.http.routes.Routes()
@routes.get("/api/processes")
async def find(req):
db = req.app["db"]
documents = [virtool.utils.base_processor(d) async for d in db.processes.find()]
return json_response(d... | Remove specific process API GET endpoints | Remove specific process API GET endpoints | Python | mit | virtool/virtool,igboyes/virtool,virtool/virtool,igboyes/virtool | import virtool.http.routes
import virtool.utils
from virtool.api.utils import json_response
routes = virtool.http.routes.Routes()
@routes.get("/api/processes")
async def find(req):
db = req.app["db"]
documents = [virtool.utils.base_processor(d) async for d in db.processes.find()]
... | Remove specific process API GET endpoints | ## Code Before:
import virtool.http.routes
import virtool.utils
from virtool.api.utils import json_response
routes = virtool.http.routes.Routes()
@routes.get("/api/processes")
async def find(req):
db = req.app["db"]
documents = [virtool.utils.base_processor(d) async for d in db.processes.find()]
return... |
d7f3ea41bc3d252d786a339fc34337f01e1cc3eb | django_dbq/migrations/0001_initial.py | django_dbq/migrations/0001_initial.py | from __future__ import unicode_literals
from django.db import models, migrations
import jsonfield.fields
import uuid
try:
from django.db.models import UUIDField
except ImportError:
from django_dbq.fields import UUIDField
class Migration(migrations.Migration):
dependencies = [
]
operations = [
... | from __future__ import unicode_literals
from django.db import models, migrations
import jsonfield.fields
import uuid
from django.db.models import UUIDField
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Job',
field... | Remove reference to old UUIDfield in django migration | Remove reference to old UUIDfield in django migration
| Python | bsd-2-clause | dabapps/django-db-queue | from __future__ import unicode_literals
from django.db import models, migrations
import jsonfield.fields
import uuid
- try:
- from django.db.models import UUIDField
+ from django.db.models import UUIDField
- except ImportError:
- from django_dbq.fields import UUIDField
class Migration(migr... | Remove reference to old UUIDfield in django migration | ## Code Before:
from __future__ import unicode_literals
from django.db import models, migrations
import jsonfield.fields
import uuid
try:
from django.db.models import UUIDField
except ImportError:
from django_dbq.fields import UUIDField
class Migration(migrations.Migration):
dependencies = [
]
... |
a5130e32bffa1dbc4d83f349fc3653b690154d71 | vumi/workers/vas2nets/workers.py | vumi/workers/vas2nets/workers.py |
from twisted.python import log
from twisted.internet.defer import inlineCallbacks, Deferred
from vumi.message import Message
from vumi.service import Worker
class EchoWorker(Worker):
@inlineCallbacks
def startWorker(self):
"""called by the Worker class when the AMQP connections been established"""
... |
from twisted.python import log
from twisted.internet.defer import inlineCallbacks, Deferred
from vumi.message import Message
from vumi.service import Worker
class EchoWorker(Worker):
@inlineCallbacks
def startWorker(self):
"""called by the Worker class when the AMQP connections been established"""
... | Add keyword to echo worker. | Add keyword to echo worker.
| Python | bsd-3-clause | TouK/vumi,vishwaprakashmishra/xmatrix,harrissoerja/vumi,TouK/vumi,vishwaprakashmishra/xmatrix,harrissoerja/vumi,vishwaprakashmishra/xmatrix,harrissoerja/vumi,TouK/vumi |
from twisted.python import log
from twisted.internet.defer import inlineCallbacks, Deferred
from vumi.message import Message
from vumi.service import Worker
class EchoWorker(Worker):
@inlineCallbacks
def startWorker(self):
"""called by the Worker class when the AMQP connec... | Add keyword to echo worker. | ## Code Before:
from twisted.python import log
from twisted.internet.defer import inlineCallbacks, Deferred
from vumi.message import Message
from vumi.service import Worker
class EchoWorker(Worker):
@inlineCallbacks
def startWorker(self):
"""called by the Worker class when the AMQP connections been... |
bbf22dc68202d81a8c7e94fbb8e61d819d808115 | wisely_project/pledges/models.py | wisely_project/pledges/models.py | from django.utils import timezone
from django.db import models
from users.models import Course, BaseModel, User
class Pledge(BaseModel):
user = models.ForeignKey(User)
course = models.ForeignKey(Course)
money = models.DecimalField(max_digits=8, decimal_places=2)
pledge_date = models.DateTimeField('da... | from django.utils import timezone
from django.db import models
from users.models import Course, BaseModel, UserProfile
class Pledge(BaseModel):
user = models.ForeignKey(UserProfile)
course = models.ForeignKey(Course)
money = models.DecimalField(max_digits=8, decimal_places=2)
pledge_date = models.Dat... | Make pledge foreignkey to userprofile | Make pledge foreignkey to userprofile
| Python | mit | TejasM/wisely,TejasM/wisely,TejasM/wisely | from django.utils import timezone
from django.db import models
- from users.models import Course, BaseModel, User
+ from users.models import Course, BaseModel, UserProfile
class Pledge(BaseModel):
- user = models.ForeignKey(User)
+ user = models.ForeignKey(UserProfile)
course = models.Forei... | Make pledge foreignkey to userprofile | ## Code Before:
from django.utils import timezone
from django.db import models
from users.models import Course, BaseModel, User
class Pledge(BaseModel):
user = models.ForeignKey(User)
course = models.ForeignKey(Course)
money = models.DecimalField(max_digits=8, decimal_places=2)
pledge_date = models.D... |
8eca7b30865e4d02fd440f55ad3215dee6fab8a1 | gee_asset_manager/batch_remover.py | gee_asset_manager/batch_remover.py | import fnmatch
import logging
import sys
import ee
def delete(asset_path):
root = asset_path[:asset_path.rfind('/')]
all_assets_names = [e['id'] for e in ee.data.getList({'id': root})]
filtered_names = fnmatch.filter(all_assets_names, asset_path)
if not filtered_names:
logging.warning('Nothin... | import fnmatch
import logging
import sys
import ee
def delete(asset_path):
root_idx = asset_path.rfind('/')
if root_idx == -1:
logging.warning('Asset not found. Make sure you pass full asset name, e.g. users/pinkiepie/rainbow')
sys.exit(1)
root = asset_path[:root_idx]
all_assets_names... | Add warning when removing an asset without full path | Add warning when removing an asset without full path
| Python | apache-2.0 | tracek/gee_asset_manager | import fnmatch
import logging
import sys
import ee
def delete(asset_path):
- root = asset_path[:asset_path.rfind('/')]
+ root_idx = asset_path.rfind('/')
+ if root_idx == -1:
+ logging.warning('Asset not found. Make sure you pass full asset name, e.g. users/pinkiepie/rainbow')
+ ... | Add warning when removing an asset without full path | ## Code Before:
import fnmatch
import logging
import sys
import ee
def delete(asset_path):
root = asset_path[:asset_path.rfind('/')]
all_assets_names = [e['id'] for e in ee.data.getList({'id': root})]
filtered_names = fnmatch.filter(all_assets_names, asset_path)
if not filtered_names:
logging... |
18a874f312a57b4b9b7a5ce5cf9857585f0f0fef | truffe2/app/utils.py | truffe2/app/utils.py |
def add_current_unit(request):
"""Template context processor to add current unit"""
return {'CURRENT_UNIT': get_current_unit(request)}
def get_current_unit(request):
"""Return the current unit"""
from units.models import Unit
current_unit_pk = request.session.get('current_unit_pk', 1)
try... | from django.conf import settings
def add_current_unit(request):
"""Template context processor to add current unit"""
return {'CURRENT_UNIT': get_current_unit(request)}
def get_current_unit(request):
"""Return the current unit"""
from units.models import Unit
current_unit_pk = request.session.g... | Fix error if no units | Fix error if no units
| Python | bsd-2-clause | agepoly/truffe2,ArcaniteSolutions/truffe2,ArcaniteSolutions/truffe2,agepoly/truffe2,agepoly/truffe2,ArcaniteSolutions/truffe2,agepoly/truffe2,ArcaniteSolutions/truffe2 | + from django.conf import settings
def add_current_unit(request):
"""Template context processor to add current unit"""
return {'CURRENT_UNIT': get_current_unit(request)}
def get_current_unit(request):
"""Return the current unit"""
from units.models import Unit
current... | Fix error if no units | ## Code Before:
def add_current_unit(request):
"""Template context processor to add current unit"""
return {'CURRENT_UNIT': get_current_unit(request)}
def get_current_unit(request):
"""Return the current unit"""
from units.models import Unit
current_unit_pk = request.session.get('current_unit_... |
4c1bf1757baa5beec50377724961c528f5985864 | ptest/screencapturer.py | ptest/screencapturer.py | import threading
import traceback
import plogger
__author__ = 'karl.gong'
def take_screen_shot():
current_thread = threading.currentThread()
active_browser = current_thread.get_property("browser")
if active_browser is not None:
while True:
try:
active_browser.switch... | import threading
import traceback
import StringIO
import plogger
try:
from PIL import ImageGrab
except ImportError:
PIL_installed = False
else:
PIL_installed = True
try:
import wx
except ImportError:
wxpython_installed = False
else:
wxpython_installed = True
__author__ = 'karl.gong'
def t... | Support capture screenshot for no-selenium test | Support capture screenshot for no-selenium test
| Python | apache-2.0 | KarlGong/ptest,KarlGong/ptest | import threading
import traceback
+ import StringIO
import plogger
+
+ try:
+ from PIL import ImageGrab
+ except ImportError:
+ PIL_installed = False
+ else:
+ PIL_installed = True
+
+ try:
+ import wx
+ except ImportError:
+ wxpython_installed = False
+ else:
+ wxpython_installed ... | Support capture screenshot for no-selenium test | ## Code Before:
import threading
import traceback
import plogger
__author__ = 'karl.gong'
def take_screen_shot():
current_thread = threading.currentThread()
active_browser = current_thread.get_property("browser")
if active_browser is not None:
while True:
try:
activ... |
c82f0f10ea8b96377ebed8a6859ff3cd8ed4cd3f | python/turbodbc/exceptions.py | python/turbodbc/exceptions.py | from __future__ import absolute_import
from functools import wraps
from exceptions import StandardError
from turbodbc_intern import Error as InternError
class Error(StandardError):
pass
class InterfaceError(Error):
pass
class DatabaseError(Error):
pass
def translate_exceptions(f):
@wraps(f)
... | from __future__ import absolute_import
from functools import wraps
from turbodbc_intern import Error as InternError
# Python 2/3 compatibility
try:
from exceptions import StandardError as _BaseError
except ImportError:
_BaseError = Exception
class Error(_BaseError):
pass
class InterfaceError(Error):... | Fix Python 2/3 exception base class compatibility | Fix Python 2/3 exception base class compatibility
| Python | mit | blue-yonder/turbodbc,blue-yonder/turbodbc,blue-yonder/turbodbc,blue-yonder/turbodbc | from __future__ import absolute_import
from functools import wraps
- from exceptions import StandardError
from turbodbc_intern import Error as InternError
+ # Python 2/3 compatibility
+ try:
+ from exceptions import StandardError as _BaseError
+ except ImportError:
+ _BaseError = Exception
+
... | Fix Python 2/3 exception base class compatibility | ## Code Before:
from __future__ import absolute_import
from functools import wraps
from exceptions import StandardError
from turbodbc_intern import Error as InternError
class Error(StandardError):
pass
class InterfaceError(Error):
pass
class DatabaseError(Error):
pass
def translate_exceptions(f):... |
8abdce9c60c9d2ead839e0065d35128ec16a82a1 | chatterbot/__main__.py | chatterbot/__main__.py | import sys
if __name__ == '__main__':
import chatterbot
if '--version' in sys.argv:
print(chatterbot.__version__)
if 'list_nltk_data' in sys.argv:
import nltk.data
print('\n'.join(nltk.data.path))
| import sys
if __name__ == '__main__':
import chatterbot
if '--version' in sys.argv:
print(chatterbot.__version__)
if 'list_nltk_data' in sys.argv:
import os
import nltk.data
data_directories = []
# Find each data directory in the NLTK path that has content
... | Add commad line utility to find NLTK data | Add commad line utility to find NLTK data
| Python | bsd-3-clause | gunthercox/ChatterBot,vkosuri/ChatterBot | import sys
if __name__ == '__main__':
import chatterbot
if '--version' in sys.argv:
print(chatterbot.__version__)
if 'list_nltk_data' in sys.argv:
+ import os
import nltk.data
- print('\n'.join(nltk.data.path))
+ data_directories = []
+... | Add commad line utility to find NLTK data | ## Code Before:
import sys
if __name__ == '__main__':
import chatterbot
if '--version' in sys.argv:
print(chatterbot.__version__)
if 'list_nltk_data' in sys.argv:
import nltk.data
print('\n'.join(nltk.data.path))
## Instruction:
Add commad line utility to find NLTK data
## Code... |
210c7b7fb421a7c083b9d292370b15c0ece17fa7 | source/bark/__init__.py | source/bark/__init__.py |
from .handler.distribute import Distribute
#: Top level handler responsible for relaying all logs to other handlers.
handle = Distribute()
|
from .handler.distribute import Distribute
#: Top level handler responsible for relaying all logs to other handlers.
handler = Distribute()
handlers = handler.handlers
handle = handler.handle
| Correct handler reference variable name and add convenient accessors. | Correct handler reference variable name and add convenient accessors.
| Python | apache-2.0 | 4degrees/mill,4degrees/sawmill |
from .handler.distribute import Distribute
#: Top level handler responsible for relaying all logs to other handlers.
- handle = Distribute()
+ handler = Distribute()
+ handlers = handler.handlers
+ handle = handler.handle
+ | Correct handler reference variable name and add convenient accessors. | ## Code Before:
from .handler.distribute import Distribute
#: Top level handler responsible for relaying all logs to other handlers.
handle = Distribute()
## Instruction:
Correct handler reference variable name and add convenient accessors.
## Code After:
from .handler.distribute import Distribute
#: Top level ha... |
1c78dfa0e0d1905910476b4052e42de287a70b74 | runtests.py | runtests.py |
import os
import sys
import string
def main():
"""
Executes the tests. Requires the CherryPy live server to be installed.
"""
command = "python manage.py test"
options = "--exe --with-selenium --with-selenium-fixtures --with-cherrypyliveserver"
apps = []
if len(sys.argv) > 1:
apps = sys.argv[1:]
... |
import os
import sys
import string
def main():
"""
Executes the tests. Requires the CherryPy live server to be installed.
"""
command = "python manage.py test"
options = "--exe --with-selenium --with-selenium-fixtures --with-cherrypyliveserver --noinput"
apps = []
if len(sys.argv) > 1:
apps = sys.a... | Update to the run tests script to force database deletion if the test database exists. | Update to the run tests script to force database deletion if the test database exists.
| Python | mit | jtakayama/makahiki-draft,jtakayama/ics691-setupbooster,csdl/makahiki,yongwen/makahiki,yongwen/makahiki,jtakayama/makahiki-draft,yongwen/makahiki,justinslee/Wai-Not-Makahiki,csdl/makahiki,jtakayama/makahiki-draft,yongwen/makahiki,csdl/makahiki,csdl/makahiki,jtakayama/makahiki-draft,jtakayama/ics691-setupbooster,jtakayam... |
import os
import sys
import string
def main():
"""
Executes the tests. Requires the CherryPy live server to be installed.
"""
command = "python manage.py test"
- options = "--exe --with-selenium --with-selenium-fixtures --with-cherrypyliveserver"
+ options = "--exe --with-selenium --w... | Update to the run tests script to force database deletion if the test database exists. | ## Code Before:
import os
import sys
import string
def main():
"""
Executes the tests. Requires the CherryPy live server to be installed.
"""
command = "python manage.py test"
options = "--exe --with-selenium --with-selenium-fixtures --with-cherrypyliveserver"
apps = []
if len(sys.argv) > 1:
apps =... |
78b2978c3e0e56c4c75a3a6b532e02c995ca69ed | openedx/core/djangoapps/user_api/permissions/views.py | openedx/core/djangoapps/user_api/permissions/views.py | from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework import permissions
from django.db import transaction
from django.utils.translation import ugettext as _
from openedx.core.lib.api.authentication import (
SessionAuthenticatio... | from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from openedx.core.lib.api.authentication import (
SessionAuthenticationAllowInactiveUser,
OAuth2AuthenticationAllowInactiveUser,
)
from openedx.core.lib.api.parsers import MergePatchParser
fr... | Remove unused import and redundant comment | Remove unused import and redundant comment
| Python | agpl-3.0 | mbareta/edx-platform-ft,mbareta/edx-platform-ft,mbareta/edx-platform-ft,mbareta/edx-platform-ft | from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
- from rest_framework import permissions
-
- from django.db import transaction
- from django.utils.translation import ugettext as _
from openedx.core.lib.api.authentication import (
... | Remove unused import and redundant comment | ## Code Before:
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework import permissions
from django.db import transaction
from django.utils.translation import ugettext as _
from openedx.core.lib.api.authentication import (
Sess... |
cadee051a462de765bab59ac42d6b372fa49c033 | examples/logfile.py | examples/logfile.py | from __future__ import unicode_literals, print_function
from twisted.internet.task import react
from eliot.logwriter import ThreadedFileWriter
from eliot import Message, Logger, addDestination
_logger = Logger()
def main(reactor):
print("Logging to example-eliot.log...")
logWriter = ThreadedFileWriter(op... | from __future__ import unicode_literals, print_function
from twisted.internet.task import react
from eliot.logwriter import ThreadedFileWriter
from eliot import Message, Logger
_logger = Logger()
def main(reactor):
print("Logging to example-eliot.log...")
logWriter = ThreadedFileWriter(open("example-elio... | Fix bug where the service was added as a destination one time too many. | Fix bug where the service was added as a destination one time too many.
| Python | apache-2.0 | iffy/eliot,ClusterHQ/eliot,ScatterHQ/eliot,ScatterHQ/eliot,ScatterHQ/eliot | from __future__ import unicode_literals, print_function
from twisted.internet.task import react
from eliot.logwriter import ThreadedFileWriter
- from eliot import Message, Logger, addDestination
+ from eliot import Message, Logger
_logger = Logger()
def main(reactor):
print("Logging... | Fix bug where the service was added as a destination one time too many. | ## Code Before:
from __future__ import unicode_literals, print_function
from twisted.internet.task import react
from eliot.logwriter import ThreadedFileWriter
from eliot import Message, Logger, addDestination
_logger = Logger()
def main(reactor):
print("Logging to example-eliot.log...")
logWriter = Threa... |
9f10dbdabe61ed841c0def319f021a4735f39217 | src/sct/templates/__init__.py | src/sct/templates/__init__.py | '''
Copyright 2014 Universitatea de Vest din Timișoara
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 i... |
from sct.templates.hadoop import HadoopServer, HadoopWorker
TEMPLATES = {
'hadoop-server': {
'max-node-count': 1,
'cloudinit': HadoopServer
},
'hadoop-worker': {
'max-node-count': None,
'cloudinit': HadoopWorker
}
}
def get_available_templates():
return TEMPLATES... | Add provisional (needs to be replaced with pkg_resources entry point discovery) template registry | Add provisional (needs to be replaced with pkg_resources entry point discovery) template registry
| Python | apache-2.0 | mneagul/scape-cloud-toolkit,mneagul/scape-cloud-toolkit,mneagul/scape-cloud-toolkit | - '''
- Copyright 2014 Universitatea de Vest din Timișoara
-
- 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 applicabl... | Add provisional (needs to be replaced with pkg_resources entry point discovery) template registry | ## Code Before:
'''
Copyright 2014 Universitatea de Vest din Timișoara
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 la... |
e9e4c622ff667e475986e1544ec78b0604b8a511 | girder_worker/tasks.py | girder_worker/tasks.py | import core
from girder_worker.utils import JobStatus
from .app import app
def _cleanup(*args, **kwargs):
core.events.trigger('cleanup')
@app.task(name='girder_worker.run', bind=True, after_return=_cleanup)
def run(tasks, *pargs, **kwargs):
jobInfo = kwargs.pop('jobInfo', {})
retval = 0
kwargs['_jo... | import core
from girder_worker.utils import JobStatus
from .app import app
def _cleanup(*args, **kwargs):
core.events.trigger('cleanup')
@app.task(name='girder_worker.run', bind=True, after_return=_cleanup)
def run(task, *pargs, **kwargs):
kwargs['_job_manager'] = task.job_manager \
if hasattr(task,... | Fix typo from bad conflict resolution during merge | Fix typo from bad conflict resolution during merge
| Python | apache-2.0 | girder/girder_worker,girder/girder_worker,girder/girder_worker | import core
from girder_worker.utils import JobStatus
from .app import app
def _cleanup(*args, **kwargs):
core.events.trigger('cleanup')
@app.task(name='girder_worker.run', bind=True, after_return=_cleanup)
- def run(tasks, *pargs, **kwargs):
+ def run(task, *pargs, **kwargs):
- jobInfo ... | Fix typo from bad conflict resolution during merge | ## Code Before:
import core
from girder_worker.utils import JobStatus
from .app import app
def _cleanup(*args, **kwargs):
core.events.trigger('cleanup')
@app.task(name='girder_worker.run', bind=True, after_return=_cleanup)
def run(tasks, *pargs, **kwargs):
jobInfo = kwargs.pop('jobInfo', {})
retval = 0
... |
fd48211548c8c2d5daec0994155ddb7e8d226882 | tests/test_anki_sync.py | tests/test_anki_sync.py | import pytest
import os
import rememberberry
from rememberscript import RememberMachine, FileStorage
from rememberberry.testing import tmp_data_path, assert_replies, get_isolated_story
@pytest.mark.asyncio
@tmp_data_path('/tmp/data/', delete=True)
async def test_anki_account():
storage = FileStorage()
m, stora... | import pytest
import os
import rememberberry
from rememberscript import RememberMachine, FileStorage
from rememberberry.testing import tmp_data_path, assert_replies, get_isolated_story
@pytest.mark.asyncio
@tmp_data_path('/tmp/data/', delete=True)
async def test_anki_account():
storage = FileStorage()
storage[... | Fix missing username in test | Fix missing username in test
| Python | agpl-3.0 | rememberberry/rememberberry-server,rememberberry/rememberberry-server | import pytest
import os
import rememberberry
from rememberscript import RememberMachine, FileStorage
from rememberberry.testing import tmp_data_path, assert_replies, get_isolated_story
@pytest.mark.asyncio
@tmp_data_path('/tmp/data/', delete=True)
async def test_anki_account():
storage = FileSt... | Fix missing username in test | ## Code Before:
import pytest
import os
import rememberberry
from rememberscript import RememberMachine, FileStorage
from rememberberry.testing import tmp_data_path, assert_replies, get_isolated_story
@pytest.mark.asyncio
@tmp_data_path('/tmp/data/', delete=True)
async def test_anki_account():
storage = FileStorag... |
2c38fea1434f8591957c2707359412151c4b6c43 | tests/test_timezones.py | tests/test_timezones.py | import unittest
import datetime
from garage.timezones import TimeZone
class TimeZoneTest(unittest.TestCase):
def test_time_zone(self):
utc = datetime.datetime(2000, 1, 2, 3, 4, 0, 0, TimeZone.UTC)
cst = utc.astimezone(TimeZone.CST)
print('xxx', utc, cst)
self.assertEqual(2000, c... | import unittest
import datetime
from garage.timezones import TimeZone
class TimeZoneTest(unittest.TestCase):
def test_time_zone(self):
utc = datetime.datetime(2000, 1, 2, 3, 4, 0, 0, TimeZone.UTC)
cst = utc.astimezone(TimeZone.CST)
self.assertEqual(2000, cst.year)
self.assertEqu... | Remove print in unit test | Remove print in unit test
| Python | mit | clchiou/garage,clchiou/garage,clchiou/garage,clchiou/garage | import unittest
import datetime
from garage.timezones import TimeZone
class TimeZoneTest(unittest.TestCase):
def test_time_zone(self):
utc = datetime.datetime(2000, 1, 2, 3, 4, 0, 0, TimeZone.UTC)
cst = utc.astimezone(TimeZone.CST)
- print('xxx', utc, cst)
... | Remove print in unit test | ## Code Before:
import unittest
import datetime
from garage.timezones import TimeZone
class TimeZoneTest(unittest.TestCase):
def test_time_zone(self):
utc = datetime.datetime(2000, 1, 2, 3, 4, 0, 0, TimeZone.UTC)
cst = utc.astimezone(TimeZone.CST)
print('xxx', utc, cst)
self.ass... |
b1d3a0c79a52ca1987ea08a546213e1135539927 | tools/bots/ddc_tests.py | tools/bots/ddc_tests.py |
import os
import os.path
import shutil
import sys
import subprocess
import bot
import bot_utils
utils = bot_utils.GetUtils()
BUILD_OS = utils.GuessOS()
(bot_name, _) = bot.GetBotName()
CHANNEL = bot_utils.GetChannelFromName(bot_name)
if __name__ == '__main__':
with utils.ChangedWorkingDirectory('pkg/dev_compile... |
import os
import os.path
import shutil
import sys
import subprocess
import bot
import bot_utils
utils = bot_utils.GetUtils()
BUILD_OS = utils.GuessOS()
(bot_name, _) = bot.GetBotName()
CHANNEL = bot_utils.GetChannelFromName(bot_name)
if __name__ == '__main__':
with utils.ChangedWorkingDirectory('pkg/dev_compile... | Set CHROME_BIN on DDC bot | Set CHROME_BIN on DDC bot
Noticed the Linux bot is failing on this:
https://build.chromium.org/p/client.dart.fyi/builders/ddc-linux-release-be/builds/1724/steps/ddc%20tests/logs/stdio
R=whesse@google.com
Review-Url: https://codereview.chromium.org/2640093002 .
| Python | bsd-3-clause | dartino/dart-sdk,dart-archive/dart-sdk,dart-lang/sdk,dartino/dart-sdk,dartino/dart-sdk,dartino/dart-sdk,dartino/dart-sdk,dart-archive/dart-sdk,dart-archive/dart-sdk,dartino/dart-sdk,dartino/dart-sdk,dart-archive/dart-sdk,dartino/dart-sdk,dart-archive/dart-sdk,dart-lang/sdk,dart-archive/dart-sdk,dart-lang/sdk,dart-lang/... |
import os
import os.path
import shutil
import sys
import subprocess
import bot
import bot_utils
utils = bot_utils.GetUtils()
BUILD_OS = utils.GuessOS()
(bot_name, _) = bot.GetBotName()
CHANNEL = bot_utils.GetChannelFromName(bot_name)
if __name__ == '__main__':
with utils.Ch... | Set CHROME_BIN on DDC bot | ## Code Before:
import os
import os.path
import shutil
import sys
import subprocess
import bot
import bot_utils
utils = bot_utils.GetUtils()
BUILD_OS = utils.GuessOS()
(bot_name, _) = bot.GetBotName()
CHANNEL = bot_utils.GetChannelFromName(bot_name)
if __name__ == '__main__':
with utils.ChangedWorkingDirectory(... |
c143bc14be8d486d313056c0d1313e03ac438284 | examples/ex_aps_parser.py | examples/ex_aps_parser.py | from __future__ import print_function
import os
import glob
import pyingest.parsers.aps as aps
import pyingest.parsers.arxiv as arxiv
import pyingest.serializers.classic
import traceback
import json
import xmltodict
from datetime import datetime
input_list = 'bibc.2.out'
testfile=[]
xmldir = '/proj/ads/fulltext/source... | from __future__ import print_function
import os
import glob
import pyingest.parsers.aps as aps
import pyingest.parsers.arxiv as arxiv
import pyingest.serializers.classic
import traceback
import json
import xmltodict
from datetime import datetime
import sys
input_list = 'bibc.2.out'
testfile=[]
xmldir = '/proj/ads/full... | Use open mode syntax on example file | Use open mode syntax on example file
| Python | mit | adsabs/adsabs-pyingest,adsabs/adsabs-pyingest,adsabs/adsabs-pyingest | from __future__ import print_function
import os
import glob
import pyingest.parsers.aps as aps
import pyingest.parsers.arxiv as arxiv
import pyingest.serializers.classic
import traceback
import json
import xmltodict
from datetime import datetime
+ import sys
input_list = 'bibc.2.out'
testfile... | Use open mode syntax on example file | ## Code Before:
from __future__ import print_function
import os
import glob
import pyingest.parsers.aps as aps
import pyingest.parsers.arxiv as arxiv
import pyingest.serializers.classic
import traceback
import json
import xmltodict
from datetime import datetime
input_list = 'bibc.2.out'
testfile=[]
xmldir = '/proj/ads... |
bc593f1716a8e36e65cf75a58e524e77d38d5d9c | notation/statistics.py | notation/statistics.py |
def mean(values):
return float(sum(values)) / len(values)
def median(values):
middle = (len(values) - 1) // 2
if len(values) % 2:
return values[middle]
else:
return mean(values[middle:middle + 2])
|
def mean(values):
return float(sum(values)) / len(values)
def quantile(p):
def bound_quantile(values):
ix = int(len(values) * p)
if len(values) % 2:
return values[ix]
elif ix < 1:
return values[0]
else:
return mean(values[ix - 1:ix + 1])
... | Add a rudimentary quantile factory function. | Add a rudimentary quantile factory function.
| Python | isc | debrouwere/python-ballpark | +
def mean(values):
return float(sum(values)) / len(values)
- def median(values):
- middle = (len(values) - 1) // 2
+ def quantile(p):
+ def bound_quantile(values):
+ ix = int(len(values) * p)
- if len(values) % 2:
+ if len(values) % 2:
- return values[middle]
+ ... | Add a rudimentary quantile factory function. | ## Code Before:
def mean(values):
return float(sum(values)) / len(values)
def median(values):
middle = (len(values) - 1) // 2
if len(values) % 2:
return values[middle]
else:
return mean(values[middle:middle + 2])
## Instruction:
Add a rudimentary quantile factory function.
## Code Af... |
ec235e290b4428dec2db03a19d678eba52f02fb5 | keyring/getpassbackend.py | keyring/getpassbackend.py | """Specific support for getpass."""
import os
import getpass
from keyring.core import get_password as original_get_password
def get_password(prompt='Password: ', stream=None,
service_name='Python',
username=None):
if username is None:
username = getpass.getuser()
retu... | """Specific support for getpass."""
import os
import getpass
import keyring.core
def get_password(prompt='Password: ', stream=None,
service_name='Python',
username=None):
if username is None:
username = getpass.getuser()
return keyring.core.get_password(service_name, ... | Use module namespaces to distinguish names instead of 'original_' prefix | Use module namespaces to distinguish names instead of 'original_' prefix
| Python | mit | jaraco/keyring | """Specific support for getpass."""
import os
import getpass
- from keyring.core import get_password as original_get_password
+ import keyring.core
def get_password(prompt='Password: ', stream=None,
service_name='Python',
username=None):
if username is None:
... | Use module namespaces to distinguish names instead of 'original_' prefix | ## Code Before:
"""Specific support for getpass."""
import os
import getpass
from keyring.core import get_password as original_get_password
def get_password(prompt='Password: ', stream=None,
service_name='Python',
username=None):
if username is None:
username = getpass.ge... |
4a711a2709ec5d8a8e04bb0f735fcfaa319cffdf | designate/objects/validation_error.py | designate/objects/validation_error.py | import six
from designate.objects import base
class ValidationError(base.DesignateObject):
FIELDS = {
'path': {},
'message': {},
'validator': {},
'validator_value': {},
'raw': {},
}
@classmethod
def from_js_error(cls, js_error):
"""Convert a JSON Schem... | from designate.objects import base
class ValidationError(base.DesignateObject):
FIELDS = {
'path': {},
'message': {},
'validator': {},
'validator_value': {},
'raw': {},
}
@classmethod
def from_js_error(cls, js_error):
"""Convert a JSON Schema Validation... | Fix the displayed error message in V2 API | Fix the displayed error message in V2 API
Change-Id: I07c3f1ed79fa507dbe9b76eb8f5964475516754c
| Python | apache-2.0 | tonyli71/designate,openstack/designate,ionrock/designate,ionrock/designate,ramsateesh/designate,grahamhayes/designate,cneill/designate-testing,muraliselva10/designate,muraliselva10/designate,cneill/designate-testing,openstack/designate,tonyli71/designate,muraliselva10/designate,grahamhayes/designate,ionrock/designate,t... | - import six
-
from designate.objects import base
class ValidationError(base.DesignateObject):
FIELDS = {
'path': {},
'message': {},
'validator': {},
'validator_value': {},
'raw': {},
}
@classmethod
def from_js_error(cls, js_error):... | Fix the displayed error message in V2 API | ## Code Before:
import six
from designate.objects import base
class ValidationError(base.DesignateObject):
FIELDS = {
'path': {},
'message': {},
'validator': {},
'validator_value': {},
'raw': {},
}
@classmethod
def from_js_error(cls, js_error):
"""Conv... |
6fc2e75426eb34755bf6dbedbd21a4345d9c5738 | plugins/websites.py | plugins/websites.py | import re
from smartbot import utils
class Plugin:
def on_message(self, bot, msg, reply):
match = re.findall(r"(https?://[^\s]+)", msg["message"], re.IGNORECASE)
for i, url in enumerate(match):
title = utils.web.get_title(url)
if title:
reply("[{0}]: {1}".f... | import io
import re
import unittest
from smartbot import utils
class Plugin:
def on_message(self, bot, msg, reply):
match = re.findall(r"(https?://[^\s]+)", msg["message"], re.IGNORECASE)
for i, url in enumerate(match):
title = utils.web.get_title(url)
if title:
... | Add tests for website plugin | Add tests for website plugin
| Python | mit | Muzer/smartbot,Cyanogenoid/smartbot,thomasleese/smartbot-old,tomleese/smartbot | + import io
import re
+ import unittest
from smartbot import utils
class Plugin:
def on_message(self, bot, msg, reply):
match = re.findall(r"(https?://[^\s]+)", msg["message"], re.IGNORECASE)
for i, url in enumerate(match):
title = utils.web.get_title(url)
... | Add tests for website plugin | ## Code Before:
import re
from smartbot import utils
class Plugin:
def on_message(self, bot, msg, reply):
match = re.findall(r"(https?://[^\s]+)", msg["message"], re.IGNORECASE)
for i, url in enumerate(match):
title = utils.web.get_title(url)
if title:
repl... |
5f2ab0dcaec5a7826ff0652e7c052971083a8398 | openid/test/datadriven.py | openid/test/datadriven.py | import unittest
class DataDrivenTestCase(unittest.TestCase):
cases = []
@classmethod
def generateCases(cls):
return cls.cases
@classmethod
def loadTests(cls):
tests = []
for case in cls.generateCases():
if isinstance(case, tuple):
test = cls(*c... | import unittest
class DataDrivenTestCase(unittest.TestCase):
cases = []
@classmethod
def generateCases(cls):
return cls.cases
@classmethod
def loadTests(cls):
tests = []
for case in cls.generateCases():
if isinstance(case, tuple):
test = cls(*c... | Replace ad-hoc pain with builtin methods | Replace ad-hoc pain with builtin methods
| Python | apache-2.0 | moreati/python3-openid,isagalaev/sm-openid,moreati/python3-openid,moreati/python3-openid,necaris/python3-openid,misli/python3-openid,necaris/python3-openid,misli/python3-openid,misli/python3-openid | import unittest
class DataDrivenTestCase(unittest.TestCase):
cases = []
@classmethod
def generateCases(cls):
return cls.cases
@classmethod
def loadTests(cls):
tests = []
for case in cls.generateCases():
if isinstance(case, tuple):... | Replace ad-hoc pain with builtin methods | ## Code Before:
import unittest
class DataDrivenTestCase(unittest.TestCase):
cases = []
@classmethod
def generateCases(cls):
return cls.cases
@classmethod
def loadTests(cls):
tests = []
for case in cls.generateCases():
if isinstance(case, tuple):
... |
89d8ee0b91c9fd579dcf965e9e07f18954625c72 | xero/api.py | xero/api.py | from .manager import Manager
class Xero(object):
"""An ORM-like interface to the Xero API"""
OBJECT_LIST = (u'Contacts', u'Accounts', u'CreditNotes',
u'Currencies', u'Invoices', u'Items', u'Organisation',
u'Payments', u'TaxRates', u'TrackingCategories')
def __init__... | from .manager import Manager
class Xero(object):
"""An ORM-like interface to the Xero API"""
OBJECT_LIST = (u'Contacts', u'Accounts', u'CreditNotes',
u'Currencies', u'Invoices', u'Items', u'Organisation',
u'Payments', u'TaxRates', u'TrackingCategories', u'ManualJournals'... | Add support for manual journals | Add support for manual journals
| Python | bsd-3-clause | wegotpop/pyxero,jarekwg/pyxero,jaymcconnell/pyxero,opendesk/pyxero,thisismyrobot/pyxero,freakboy3742/pyxero,MJMortimer/pyxero,unomena/pyxero,schinckel/pyxero,unomena/pyxeropos,jacobg/pyxero,direvus/pyxero | from .manager import Manager
class Xero(object):
"""An ORM-like interface to the Xero API"""
OBJECT_LIST = (u'Contacts', u'Accounts', u'CreditNotes',
u'Currencies', u'Invoices', u'Items', u'Organisation',
- u'Payments', u'TaxRates', u'TrackingCategories')... | Add support for manual journals | ## Code Before:
from .manager import Manager
class Xero(object):
"""An ORM-like interface to the Xero API"""
OBJECT_LIST = (u'Contacts', u'Accounts', u'CreditNotes',
u'Currencies', u'Invoices', u'Items', u'Organisation',
u'Payments', u'TaxRates', u'TrackingCategories')
... |
fb9591c4a2801bfe5f5380c3e33aa44a25db3591 | customforms/models.py | customforms/models.py |
from django.utils.translation import ugettext as _
from django.db import models
class Form(models.Model):
title = models.CharField(_("Title"), max_length=255)
def __unicode__(self):
return u'%s' % self.title
class Meta:
ordering = ('title', )
class Question(models.Model):
form = m... |
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _
from django.db import models
class Form(models.Model):
title = models.CharField(_("Title"), max_length=255)
def __unicode__(self):
return u'%s' % self.title
class Meta:
ordering = ('title', )... | Add absolute URLs to form and question admin | Add absolute URLs to form and question admin
| Python | apache-2.0 | cschwede/django-customforms |
+ from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _
from django.db import models
class Form(models.Model):
title = models.CharField(_("Title"), max_length=255)
def __unicode__(self):
return u'%s' % self.title
class Meta:
... | Add absolute URLs to form and question admin | ## Code Before:
from django.utils.translation import ugettext as _
from django.db import models
class Form(models.Model):
title = models.CharField(_("Title"), max_length=255)
def __unicode__(self):
return u'%s' % self.title
class Meta:
ordering = ('title', )
class Question(models.Mode... |
d6ff777c7fb3f645c021da1319bb5d78d13aa9db | meshnet/interface.py | meshnet/interface.py | import serial
import struct
from siphashc import siphash
def _hash(key: str, sender: int, receiver: int, msg_type: int, data: bytes):
packed_data = struct.pack(">h>hBs", sender, receiver, msg_type, data)
return struct.pack("Q", siphash(key, packed_data))
class SerialMessage(object):
def __init__(self):
... | import serial
import struct
from siphashc import siphash
def _hash(key: bytes, sender: int, receiver: int, msg_type: int, data: bytes):
packed_data = struct.pack(">hhB", sender, receiver, msg_type) + data
return struct.pack(">Q", siphash(key, packed_data))
class SerialMessage(object):
def __init__(self)... | Fix python siphashing to match c implementation | Fix python siphashing to match c implementation
Signed-off-by: Jan Losinski <577c4104c61edf9f052c616c0c23e67bef4a9955@wh2.tu-dresden.de>
| Python | bsd-3-clause | janLo/automation_mesh,janLo/automation_mesh,janLo/automation_mesh | import serial
import struct
from siphashc import siphash
+
- def _hash(key: str, sender: int, receiver: int, msg_type: int, data: bytes):
+ def _hash(key: bytes, sender: int, receiver: int, msg_type: int, data: bytes):
- packed_data = struct.pack(">h>hBs", sender, receiver, msg_type, data)
+ packed_da... | Fix python siphashing to match c implementation | ## Code Before:
import serial
import struct
from siphashc import siphash
def _hash(key: str, sender: int, receiver: int, msg_type: int, data: bytes):
packed_data = struct.pack(">h>hBs", sender, receiver, msg_type, data)
return struct.pack("Q", siphash(key, packed_data))
class SerialMessage(object):
def _... |
b2bab786c4af3dcca7d35b1e6ecff8699e542ec4 | pytest_girder/pytest_girder/plugin.py | pytest_girder/pytest_girder/plugin.py | from .fixtures import * # noqa
def pytest_addoption(parser):
group = parser.getgroup('girder')
group.addoption('--mock-db', action='store_true', default=False,
help='Whether or not to mock the database using mongomock.')
group.addoption('--mongo-uri', action='store', default='mongodb:... | import os
from .fixtures import * # noqa
def pytest_configure(config):
"""
Create the necessary directories for coverage. This is necessary because neither coverage nor
pytest-cov have support for making the data_file directory before running.
"""
covPlugin = config.pluginmanager.get_plugin('_cov... | Add a pytest hook for creating the coverage data_file directory | Add a pytest hook for creating the coverage data_file directory
| Python | apache-2.0 | jbeezley/girder,jbeezley/girder,girder/girder,kotfic/girder,jbeezley/girder,data-exp-lab/girder,Xarthisius/girder,data-exp-lab/girder,girder/girder,RafaelPalomar/girder,jbeezley/girder,girder/girder,kotfic/girder,manthey/girder,kotfic/girder,girder/girder,RafaelPalomar/girder,Xarthisius/girder,RafaelPalomar/girder,Xart... | + import os
from .fixtures import * # noqa
+
+
+ def pytest_configure(config):
+ """
+ Create the necessary directories for coverage. This is necessary because neither coverage nor
+ pytest-cov have support for making the data_file directory before running.
+ """
+ covPlugin = config.pluginmana... | Add a pytest hook for creating the coverage data_file directory | ## Code Before:
from .fixtures import * # noqa
def pytest_addoption(parser):
group = parser.getgroup('girder')
group.addoption('--mock-db', action='store_true', default=False,
help='Whether or not to mock the database using mongomock.')
group.addoption('--mongo-uri', action='store', d... |
931e2d1e8ba3fd6b129a6d74e3a1ad9984c1938a | benchmarks/benchmarks/bench_random.py | benchmarks/benchmarks/bench_random.py | from __future__ import absolute_import, division, print_function
from .common import Benchmark
import numpy as np
class Random(Benchmark):
params = ['normal', 'uniform', 'weibull 1', 'binomial 10 0.5',
'poisson 10']
def setup(self, name):
items = name.split()
name = items.pop(... | from __future__ import absolute_import, division, print_function
from .common import Benchmark
import numpy as np
from numpy.lib import NumpyVersion
class Random(Benchmark):
params = ['normal', 'uniform', 'weibull 1', 'binomial 10 0.5',
'poisson 10']
def setup(self, name):
items = nam... | Add benchmark tests for numpy.random.randint. | ENH: Add benchmark tests for numpy.random.randint.
This add benchmarks randint. There is one set of benchmarks for the
default dtype, 'l', that can be tracked back, and another set for the
new dtypes 'bool', 'uint8', 'uint16', 'uint32', and 'uint64'.
| Python | bsd-3-clause | shoyer/numpy,Dapid/numpy,jakirkham/numpy,WarrenWeckesser/numpy,chatcannon/numpy,WarrenWeckesser/numpy,b-carter/numpy,anntzer/numpy,ssanderson/numpy,simongibbons/numpy,nbeaver/numpy,SiccarPoint/numpy,numpy/numpy,Eric89GXL/numpy,kiwifb/numpy,seberg/numpy,rgommers/numpy,ESSS/numpy,shoyer/numpy,anntzer/numpy,utke1/numpy,dw... | from __future__ import absolute_import, division, print_function
from .common import Benchmark
import numpy as np
+ from numpy.lib import NumpyVersion
class Random(Benchmark):
params = ['normal', 'uniform', 'weibull 1', 'binomial 10 0.5',
'poisson 10']
def setup(self, ... | Add benchmark tests for numpy.random.randint. | ## Code Before:
from __future__ import absolute_import, division, print_function
from .common import Benchmark
import numpy as np
class Random(Benchmark):
params = ['normal', 'uniform', 'weibull 1', 'binomial 10 0.5',
'poisson 10']
def setup(self, name):
items = name.split()
n... |
ca8e15d50b816c29fc2a0df27d0266826e38b5b8 | cellcounter/statistics/serializers.py | cellcounter/statistics/serializers.py | from rest_framework.serializers import ModelSerializer
from .models import CountInstance
class CountInstanceSerializer(ModelSerializer):
class Meta:
model = CountInstance
| from rest_framework.serializers import ModelSerializer
from .models import CountInstance
class CountInstanceSerializer(ModelSerializer):
class Meta:
model = CountInstance
fields = ('count_total',)
| Update serializer to deal with new model | Update serializer to deal with new model
| Python | mit | cellcounter/cellcounter,haematologic/cellcounter,cellcounter/cellcounter,cellcounter/cellcounter,haematologic/cellcounter,haematologic/cellcounter,cellcounter/cellcounter | from rest_framework.serializers import ModelSerializer
from .models import CountInstance
class CountInstanceSerializer(ModelSerializer):
class Meta:
model = CountInstance
+ fields = ('count_total',)
| Update serializer to deal with new model | ## Code Before:
from rest_framework.serializers import ModelSerializer
from .models import CountInstance
class CountInstanceSerializer(ModelSerializer):
class Meta:
model = CountInstance
## Instruction:
Update serializer to deal with new model
## Code After:
from rest_framework.serializers import ModelSe... |
c1b433e5ed4c06b956b4d27f6da4e8b1dab54aaf | services/cloudwatch/sample.py | services/cloudwatch/sample.py | '''
===================================
Boto 3 - CloudWatch Service Example
===================================
This application implements the CloudWatch service that lets you gets
information from Amazon Cloud Watch. See the README for more details.
'''
import boto3
'''
Define your AWS credentials:
'''
AWS_ACCESS_KE... | '''
===================================
Boto 3 - CloudWatch Service Example
===================================
This application implements the CloudWatch service that lets you gets
information from Amazon Cloud Watch. See the README for more details.
'''
import boto3
'''
Define your AWS credentials:
'''
AWS_ACCESS_KE... | Fix issue in cloudwacth service credentials | Fix issue in cloudwacth service credentials
| Python | mit | rolandovillca/aws_samples_boto3_sdk | '''
===================================
Boto 3 - CloudWatch Service Example
===================================
This application implements the CloudWatch service that lets you gets
information from Amazon Cloud Watch. See the README for more details.
'''
import boto3
'''
Define your AWS credenti... | Fix issue in cloudwacth service credentials | ## Code Before:
'''
===================================
Boto 3 - CloudWatch Service Example
===================================
This application implements the CloudWatch service that lets you gets
information from Amazon Cloud Watch. See the README for more details.
'''
import boto3
'''
Define your AWS credentials:
'... |
6f7dba3beccca655b84879ccd0f3071d15536b2f | test/utils.py | test/utils.py | import string
import random
def generate_string(str_len=6, src=string.ascii_lowercase):
return "".join(random.choice(src) for x in xrange(str_len))
def lorem_ipsum():
words_count = random.randint(20, 50)
lorem = list([])
for i in xrange(words_count):
word_length = random.randint(4, 8)
... | import string
import random
def generate_string(str_len=6, src=string.ascii_lowercase):
return "".join(random.choice(src) for x in xrange(str_len))
def lorem_ipsum(words_count=30):
lorem = list([])
for i in xrange(words_count):
word_length = random.randint(4, 8)
lorem.append(generate_str... | Add word_count parameter for lorem_ipsum generator | Add word_count parameter for lorem_ipsum generator
| Python | mit | sarutobi/Rynda,sarutobi/flowofkindness,sarutobi/ritmserdtsa,sarutobi/ritmserdtsa,sarutobi/flowofkindness,sarutobi/Rynda,sarutobi/ritmserdtsa,sarutobi/ritmserdtsa,sarutobi/Rynda,sarutobi/flowofkindness,sarutobi/flowofkindness,sarutobi/Rynda | import string
import random
+
def generate_string(str_len=6, src=string.ascii_lowercase):
return "".join(random.choice(src) for x in xrange(str_len))
- def lorem_ipsum():
- words_count = random.randint(20, 50)
+
+ def lorem_ipsum(words_count=30):
lorem = list([])
for i in xrange(word... | Add word_count parameter for lorem_ipsum generator | ## Code Before:
import string
import random
def generate_string(str_len=6, src=string.ascii_lowercase):
return "".join(random.choice(src) for x in xrange(str_len))
def lorem_ipsum():
words_count = random.randint(20, 50)
lorem = list([])
for i in xrange(words_count):
word_length = random.randin... |
d80f7a89b5bc23802ad5ec9bb8cc6ad523976718 | test_gitnl.py | test_gitnl.py | from __future__ import print_function, division, absolute_import
import unittest
import gitnl
class GitnlTestCase(unittest.TestCase):
"""Tests from 'gitnl.py'."""
def test_push_remotename_branchfrom(self):
desired = 'push remotename branchfrom'
actual = gitnl.parse_to_git('push my branch bra... | from __future__ import print_function, division, absolute_import
import unittest
import gitnl
class GitnlTestCase(unittest.TestCase):
"""Tests from 'gitnl.py'."""
def test_push_remotename_branchfrom(self):
desired = 'push remotename branchfrom'
actual = gitnl.parse_to_git('push my branch bra... | Add rename branch locally test | Add rename branch locally test
| Python | mit | eteq/gitnl,eteq/gitnl | from __future__ import print_function, division, absolute_import
import unittest
import gitnl
class GitnlTestCase(unittest.TestCase):
"""Tests from 'gitnl.py'."""
def test_push_remotename_branchfrom(self):
desired = 'push remotename branchfrom'
actual = gitnl.parse_to... | Add rename branch locally test | ## Code Before:
from __future__ import print_function, division, absolute_import
import unittest
import gitnl
class GitnlTestCase(unittest.TestCase):
"""Tests from 'gitnl.py'."""
def test_push_remotename_branchfrom(self):
desired = 'push remotename branchfrom'
actual = gitnl.parse_to_git('pu... |
fb213097e838ddfa40d9f71f1705d7af661cfbdf | tests/unit.py | tests/unit.py | import unittest
from github2.issues import Issue
from github2.client import Github
class ReprTests(unittest.TestCase):
"""__repr__ must return strings, not unicode objects."""
def test_issue(self):
"""Issues can have non-ASCII characters in the title."""
i = Issue(title=u'abcdé')
sel... | import unittest
from github2.issues import Issue
from github2.client import Github
class ReprTests(unittest.TestCase):
"""__repr__ must return strings, not unicode objects."""
def test_issue(self):
"""Issues can have non-ASCII characters in the title."""
i = Issue(title=u'abcdé')
sel... | Allow tests to be run with Python <2.6. | Allow tests to be run with Python <2.6.
| Python | bsd-3-clause | ask/python-github2 | import unittest
from github2.issues import Issue
from github2.client import Github
class ReprTests(unittest.TestCase):
"""__repr__ must return strings, not unicode objects."""
def test_issue(self):
"""Issues can have non-ASCII characters in the title."""
i = Issue(tit... | Allow tests to be run with Python <2.6. | ## Code Before:
import unittest
from github2.issues import Issue
from github2.client import Github
class ReprTests(unittest.TestCase):
"""__repr__ must return strings, not unicode objects."""
def test_issue(self):
"""Issues can have non-ASCII characters in the title."""
i = Issue(title=u'abc... |
15996286496d913c25290362ba2dba2d349bd5f6 | imageManagerUtils/settings.py | imageManagerUtils/settings.py |
import os
import sys
import subprocess
# This path is the location of the caller script
MAIN_SCRIPT_PATH = os.path.dirname(os.path.abspath(sys.argv[0]))
# Set up the path to settings.sh
settings_path = os.path.join(MAIN_SCRIPT_PATH, 'settings.sh')
if not os.path.isfile(settings_path):
print('Cannot find settings.... |
import os
import sys
import subprocess
# This path is the location of the caller script
MAIN_SCRIPT_PATH = os.path.dirname(os.path.abspath(sys.argv[0]))
# Set up the path to settings.sh
settings_path = os.path.join(MAIN_SCRIPT_PATH, 'settings.sh')
if not os.path.isfile(settings_path):
print('Cannot find settings.... | Fix bug of invoking /bin/sh on several OSs | Fix bug of invoking /bin/sh on several OSs
| Python | mit | snippits/qemu_image,snippits/qemu_image,snippits/qemu_image |
import os
import sys
import subprocess
# This path is the location of the caller script
MAIN_SCRIPT_PATH = os.path.dirname(os.path.abspath(sys.argv[0]))
# Set up the path to settings.sh
settings_path = os.path.join(MAIN_SCRIPT_PATH, 'settings.sh')
if not os.path.isfile(settings_path):
print(... | Fix bug of invoking /bin/sh on several OSs | ## Code Before:
import os
import sys
import subprocess
# This path is the location of the caller script
MAIN_SCRIPT_PATH = os.path.dirname(os.path.abspath(sys.argv[0]))
# Set up the path to settings.sh
settings_path = os.path.join(MAIN_SCRIPT_PATH, 'settings.sh')
if not os.path.isfile(settings_path):
print('Canno... |
59b015bb3e45497b7ec86bf1799e8442a30b65da | py/PMUtil.py | py/PMUtil.py |
from __future__ import absolute_import, division, print_function
import sys
import time
import datetime
def timeStamp():
'''Return time stamp'''
t = time.time()
fmt = '[%Y-%m-%d %H:%M:%S]'
return datetime.datetime.fromtimestamp(t).strftime(fmt)
def printStatus(msg):
'''Print status message'''
... |
from __future__ import absolute_import, division, print_function
import sys
import time
import datetime
def timeStamp():
'''Return time stamp'''
t = time.time()
fmt = '[%Y-%m-%d %H:%M:%S]'
return datetime.datetime.fromtimestamp(t).strftime(fmt)
def printStatus(msg):
'''Print status message'''
... | Exit method. - (New) Added exit method. | Exit method.
- (New) Added exit method.
| Python | mit | dacuevas/PMAnalyzer,dacuevas/PMAnalyzer,dacuevas/PMAnalyzer,dacuevas/PMAnalyzer |
from __future__ import absolute_import, division, print_function
import sys
import time
import datetime
def timeStamp():
'''Return time stamp'''
t = time.time()
fmt = '[%Y-%m-%d %H:%M:%S]'
return datetime.datetime.fromtimestamp(t).strftime(fmt)
def printStatus(msg):
... | Exit method. - (New) Added exit method. | ## Code Before:
from __future__ import absolute_import, division, print_function
import sys
import time
import datetime
def timeStamp():
'''Return time stamp'''
t = time.time()
fmt = '[%Y-%m-%d %H:%M:%S]'
return datetime.datetime.fromtimestamp(t).strftime(fmt)
def printStatus(msg):
'''Print sta... |
764f8d9d7818076555cde5fcad29f3052b523771 | company/autocomplete_light_registry.py | company/autocomplete_light_registry.py | import autocomplete_light
from .models import Company
class CompanyAutocomplete(autocomplete_light.AutocompleteModelBase):
search_fields = ['^name']
model = Company
autocomplete_light.register(CompanyAutocomplete)
| import autocomplete_light
from .models import Company
class CompanyAutocomplete(autocomplete_light.AutocompleteModelBase):
search_fields = ['name', 'official_name', 'common_name']
model = Company
autocomplete_light.register(CompanyAutocomplete)
| Add more search fields to autocomplete | Add more search fields to autocomplete
| Python | bsd-3-clause | KlubJagiellonski/pola-backend,KlubJagiellonski/pola-backend,KlubJagiellonski/pola-backend,KlubJagiellonski/pola-backend | import autocomplete_light
from .models import Company
class CompanyAutocomplete(autocomplete_light.AutocompleteModelBase):
- search_fields = ['^name']
+ search_fields = ['name', 'official_name', 'common_name']
model = Company
autocomplete_light.register(CompanyAutocomplete)
| Add more search fields to autocomplete | ## Code Before:
import autocomplete_light
from .models import Company
class CompanyAutocomplete(autocomplete_light.AutocompleteModelBase):
search_fields = ['^name']
model = Company
autocomplete_light.register(CompanyAutocomplete)
## Instruction:
Add more search fields to autocomplete
## Code After:
import au... |
6f822cf46957d038588e7a71eb91f8ca9f9c95f1 | scaffolder/commands/install.py | scaffolder/commands/install.py |
from optparse import make_option
from optparse import OptionParser
from scaffolder.core.template import TemplateManager
from scaffolder.core.commands import BaseCommand
class InstallCommand(BaseCommand):
option_list = BaseCommand.option_list + (
make_option(
"-t",
"--target",
... |
from optparse import make_option
from optparse import OptionParser
from scaffolder import get_minion_path
from scaffolder.core.template import TemplateManager
from scaffolder.core.commands import BaseCommand
class InstallCommand(BaseCommand):
option_list = BaseCommand.option_list + (
make_option(
... | Use get_minion_path to get default dir. | InstallCommand: Use get_minion_path to get default dir.
| Python | mit | goliatone/minions |
from optparse import make_option
from optparse import OptionParser
+ from scaffolder import get_minion_path
from scaffolder.core.template import TemplateManager
from scaffolder.core.commands import BaseCommand
class InstallCommand(BaseCommand):
option_list = BaseCommand.option_list + (
m... | Use get_minion_path to get default dir. | ## Code Before:
from optparse import make_option
from optparse import OptionParser
from scaffolder.core.template import TemplateManager
from scaffolder.core.commands import BaseCommand
class InstallCommand(BaseCommand):
option_list = BaseCommand.option_list + (
make_option(
"-t",
"... |
95d9bb3a9500d80b5064c5fb4d5bd7b30406d1ae | conanfile.py | conanfile.py | from conans import ConanFile, CMake
class GrpccbConan(ConanFile):
name = "grpc_cb_core"
version = "0.2"
license = "Apache-2.0"
url = "https://github.com/jinq0123/grpc_cb_core"
description = "C++ gRPC core library with callback interface."
settings = "os", "compiler", "build_type", "arch"
op... | from conans import ConanFile, CMake
class GrpccbConan(ConanFile):
name = "grpc_cb_core"
version = "0.2"
license = "Apache-2.0"
url = "https://github.com/jinq0123/grpc_cb_core"
description = "C++ gRPC core library with callback interface."
settings = "os", "compiler", "build_type", "arch"
op... | Fix update remote to ConanCenter and grpc to highest buildable/supported version | Fix update remote to ConanCenter and grpc to highest buildable/supported version
| Python | apache-2.0 | jinq0123/grpc_cb_core,jinq0123/grpc_cb_core,jinq0123/grpc_cb_core | from conans import ConanFile, CMake
class GrpccbConan(ConanFile):
name = "grpc_cb_core"
version = "0.2"
license = "Apache-2.0"
url = "https://github.com/jinq0123/grpc_cb_core"
description = "C++ gRPC core library with callback interface."
settings = "os", "compiler", "build_ty... | Fix update remote to ConanCenter and grpc to highest buildable/supported version | ## Code Before:
from conans import ConanFile, CMake
class GrpccbConan(ConanFile):
name = "grpc_cb_core"
version = "0.2"
license = "Apache-2.0"
url = "https://github.com/jinq0123/grpc_cb_core"
description = "C++ gRPC core library with callback interface."
settings = "os", "compiler", "build_type... |
306e6939c5b369f4a4ef4bb4d16948dc1f027f53 | tests/test_initial_ismaster.py | tests/test_initial_ismaster.py |
import time
from mockupdb import MockupDB, wait_until
from pymongo import MongoClient
from tests import unittest
class TestInitialIsMaster(unittest.TestCase):
def test_initial_ismaster(self):
server = MockupDB()
server.run()
self.addCleanup(server.stop)
start = time.time()
... |
import time
from mockupdb import MockupDB, wait_until
from pymongo import MongoClient
from tests import unittest
class TestInitialIsMaster(unittest.TestCase):
def test_initial_ismaster(self):
server = MockupDB()
server.run()
self.addCleanup(server.stop)
start = time.time()
... | Update for PYTHON 985: MongoClient properties now block until connected. | Update for PYTHON 985: MongoClient properties now block until connected.
| Python | apache-2.0 | ajdavis/pymongo-mockup-tests |
import time
from mockupdb import MockupDB, wait_until
from pymongo import MongoClient
from tests import unittest
class TestInitialIsMaster(unittest.TestCase):
def test_initial_ismaster(self):
server = MockupDB()
server.run()
self.addCleanup(server.stop)
... | Update for PYTHON 985: MongoClient properties now block until connected. | ## Code Before:
import time
from mockupdb import MockupDB, wait_until
from pymongo import MongoClient
from tests import unittest
class TestInitialIsMaster(unittest.TestCase):
def test_initial_ismaster(self):
server = MockupDB()
server.run()
self.addCleanup(server.stop)
start = ... |
af5e90cb544e2e37819302f5750084fc17f7ee12 | make_example.py | make_example.py |
import os
import sys
import yaml
import subprocess
class SDBUSPlus(object):
def __init__(self, path):
self.path = path
def __call__(self, *a, **kw):
args = [
os.path.join(self.path, 'sdbus++'),
'-t',
os.path.join(self.path, 'templates')
]
... |
import os
import sys
import yaml
import subprocess
if __name__ == '__main__':
genfiles = {
'server-cpp': lambda x: '%s.cpp' % x,
'server-header': lambda x: os.path.join(
os.path.join(*x.split('.')), 'server.hpp')
}
with open(os.path.join('example', 'interfaces.yaml'), 'r') as ... | Remove sdbus++ template search workaround | Remove sdbus++ template search workaround
sdbus++ was fixed upstream to find its templates automatically.
Change-Id: I29020b9d1ea4ae8baaca5fe869625a3d96cd6eaf
Signed-off-by: Brad Bishop <713d098c0be4c8fd2bf36a94cd08699466677ecd@fuzziesquirrel.com>
| Python | apache-2.0 | openbmc/phosphor-inventory-manager,openbmc/phosphor-inventory-manager |
import os
import sys
import yaml
import subprocess
- class SDBUSPlus(object):
- def __init__(self, path):
- self.path = path
-
- def __call__(self, *a, **kw):
- args = [
- os.path.join(self.path, 'sdbus++'),
- '-t',
- os.path.join(self.path,... | Remove sdbus++ template search workaround | ## Code Before:
import os
import sys
import yaml
import subprocess
class SDBUSPlus(object):
def __init__(self, path):
self.path = path
def __call__(self, *a, **kw):
args = [
os.path.join(self.path, 'sdbus++'),
'-t',
os.path.join(self.path, 'templates')
... |
1e07e9424a1ac69e1e660e6a6f1e58bba15472c1 | make_spectra.py | make_spectra.py | import halospectra as hs
import randspectra as rs
import sys
snapnum=sys.argv[1]
sim=sys.argv[2]
#base="/n/hernquistfs1/mvogelsberger/projects/GFM/Production/Cosmo/Cosmo"+str(sim)+"_V6/L25n512/output/"
#savedir="/n/home11/spb/scratch/Cosmo/Cosmo"+str(sim)+"_V6_512/snapdir_"+str(snapnum).rjust(3,'0')
base="/home/spb/da... | import halospectra as hs
import randspectra as rs
import sys
snapnum=sys.argv[1]
sim=sys.argv[2]
#base="/n/hernquistfs1/mvogelsberger/projects/GFM/Production/Cosmo/Cosmo"+str(sim)+"_V6/L25n512/output/"
#savedir="/n/home11/spb/scratch/Cosmo/Cosmo"+str(sim)+"_V6_512/snapdir_"+str(snapnum).rjust(3,'0')
base="/home/spb/da... | Implement saving and loading the observer tau | Implement saving and loading the observer tau
| Python | mit | sbird/vw_spectra | import halospectra as hs
import randspectra as rs
import sys
snapnum=sys.argv[1]
sim=sys.argv[2]
#base="/n/hernquistfs1/mvogelsberger/projects/GFM/Production/Cosmo/Cosmo"+str(sim)+"_V6/L25n512/output/"
#savedir="/n/home11/spb/scratch/Cosmo/Cosmo"+str(sim)+"_V6_512/snapdir_"+str(snapnum).rjust(3,'0')
... | Implement saving and loading the observer tau | ## Code Before:
import halospectra as hs
import randspectra as rs
import sys
snapnum=sys.argv[1]
sim=sys.argv[2]
#base="/n/hernquistfs1/mvogelsberger/projects/GFM/Production/Cosmo/Cosmo"+str(sim)+"_V6/L25n512/output/"
#savedir="/n/home11/spb/scratch/Cosmo/Cosmo"+str(sim)+"_V6_512/snapdir_"+str(snapnum).rjust(3,'0')
ba... |
8316a60ba2887a511579e8cedb90b3a02fc1889a | dope/util.py | dope/util.py | from uuid import UUID
from werkzeug.routing import BaseConverter
class UUIDConverter(BaseConverter):
to_python = UUID
to_url = str
| from uuid import UUID
from werkzeug.routing import BaseConverter
class UUIDConverter(BaseConverter):
to_python = UUID
def to_url(self, obj):
return str(obj).replace('-', '')
| Drop dashes from download urls. | Drop dashes from download urls.
| Python | mit | mbr/dope,mbr/dope | from uuid import UUID
from werkzeug.routing import BaseConverter
class UUIDConverter(BaseConverter):
to_python = UUID
- to_url = str
+ def to_url(self, obj):
+ return str(obj).replace('-', '')
+ | Drop dashes from download urls. | ## Code Before:
from uuid import UUID
from werkzeug.routing import BaseConverter
class UUIDConverter(BaseConverter):
to_python = UUID
to_url = str
## Instruction:
Drop dashes from download urls.
## Code After:
from uuid import UUID
from werkzeug.routing import BaseConverter
class UUIDConverter(BaseConver... |
9d46df1680e3d799971e73ec73043c2a6c0590ce | scripts/build_tar.py | scripts/build_tar.py | import os
import subprocess
root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
tarfile = os.path.join(root_dir, "src_pkg.tar")
def _is_dir_newer(directory, filename):
file_mtime = os.stat(filename).st_mtime
for dirname, _, filenames in os.walk(directory):
for filename in filenam... | import os
import subprocess
root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
tarfile = os.path.join(root_dir, "src_pkg.tar")
def _is_dir_newer(directory, filename):
file_mtime = os.stat(filename).st_mtime
for dirname, _, filenames in os.walk(directory):
if _is_file_newer(dirna... | Fix building tar in deployment | Fix building tar in deployment
| Python | bsd-3-clause | vmalloc/mailboxer,Infinidat/lanister,vmalloc/mailboxer,Infinidat/lanister,getslash/mailboxer,vmalloc/mailboxer,getslash/mailboxer,getslash/mailboxer | import os
import subprocess
root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
tarfile = os.path.join(root_dir, "src_pkg.tar")
def _is_dir_newer(directory, filename):
file_mtime = os.stat(filename).st_mtime
for dirname, _, filenames in os.walk(directory):
+ if ... | Fix building tar in deployment | ## Code Before:
import os
import subprocess
root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
tarfile = os.path.join(root_dir, "src_pkg.tar")
def _is_dir_newer(directory, filename):
file_mtime = os.stat(filename).st_mtime
for dirname, _, filenames in os.walk(directory):
for fil... |
166bff52496bfb47c5a3a03585bd10fb449b8d77 | Lib/curses/__init__.py | Lib/curses/__init__.py |
__revision__ = "$Id$"
from _curses import *
from curses.wrapper import wrapper
|
__revision__ = "$Id$"
from _curses import *
from curses.wrapper import wrapper
# Some constants, most notably the ACS_* ones, are only added to the C
# _curses module's dictionary after initscr() is called. (Some
# versions of SGI's curses don't define values for those constants
# until initscr() has been called.) ... | Add wrapper for initscr() to copy the ACS_ and LINES,COLS bindings | Add wrapper for initscr() to copy the ACS_ and LINES,COLS bindings
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator |
__revision__ = "$Id$"
from _curses import *
from curses.wrapper import wrapper
+ # Some constants, most notably the ACS_* ones, are only added to the C
+ # _curses module's dictionary after initscr() is called. (Some
+ # versions of SGI's curses don't define values for those constants
+ # until initscr(... | Add wrapper for initscr() to copy the ACS_ and LINES,COLS bindings | ## Code Before:
__revision__ = "$Id$"
from _curses import *
from curses.wrapper import wrapper
## Instruction:
Add wrapper for initscr() to copy the ACS_ and LINES,COLS bindings
## Code After:
__revision__ = "$Id$"
from _curses import *
from curses.wrapper import wrapper
# Some constants, most notably the ACS_*... |
17faea99343e37036b7ee35e5d3273f98a52dba9 | Python/tomviz/utils.py | Python/tomviz/utils.py | import numpy as np
import vtk.numpy_interface.dataset_adapter as dsa
def get_scalars(dataobject):
do = dsa.WrapDataObject(dataobject)
# get the first
rawarray = do.PointData.GetScalars()
vtkarray = dsa.vtkDataArrayToVTKArray(rawarray, do)
vtkarray.Association = dsa.ArrayAssociation.POINT
return... | import numpy as np
import vtk.numpy_interface.dataset_adapter as dsa
import vtk.util.numpy_support as np_s
def get_scalars(dataobject):
do = dsa.WrapDataObject(dataobject)
# get the first
rawarray = do.PointData.GetScalars()
vtkarray = dsa.vtkDataArrayToVTKArray(rawarray, do)
vtkarray.Association =... | Fix numpy related errors on Mavericks. | Fix numpy related errors on Mavericks.
The problem was due to the fact that operations (like sqrt) can return a
float16 arrays which cannot be passed back to VTK directly. Added a
temporary conversion to float64. We should potentially handle this in
VTK.
| Python | bsd-3-clause | cryos/tomviz,thewtex/tomviz,cjh1/tomviz,cryos/tomviz,cryos/tomviz,Hovden/tomviz,Hovden/tomviz,yijiang1/tomviz,cjh1/tomviz,thewtex/tomviz,OpenChemistry/tomviz,mathturtle/tomviz,yijiang1/tomviz,cjh1/tomviz,mathturtle/tomviz,OpenChemistry/tomviz,thewtex/tomviz,OpenChemistry/tomviz,mathturtle/tomviz,OpenChemistry/tomviz | import numpy as np
import vtk.numpy_interface.dataset_adapter as dsa
+ import vtk.util.numpy_support as np_s
def get_scalars(dataobject):
do = dsa.WrapDataObject(dataobject)
# get the first
rawarray = do.PointData.GetScalars()
vtkarray = dsa.vtkDataArrayToVTKArray(rawarray, do)
vt... | Fix numpy related errors on Mavericks. | ## Code Before:
import numpy as np
import vtk.numpy_interface.dataset_adapter as dsa
def get_scalars(dataobject):
do = dsa.WrapDataObject(dataobject)
# get the first
rawarray = do.PointData.GetScalars()
vtkarray = dsa.vtkDataArrayToVTKArray(rawarray, do)
vtkarray.Association = dsa.ArrayAssociation.... |
e753038de039fd23f0d59bb0094f59fc73efe22b | flask_apscheduler/json.py | flask_apscheduler/json.py | import flask
import json
from datetime import datetime
from apscheduler.job import Job
from .utils import job_to_dict
class JSONEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return obj.isoformat()
if isinstance(obj, Job):
return job_to_d... | import datetime
import flask
import json
from apscheduler.job import Job
from .utils import job_to_dict
loads = json.loads
def dumps(obj, indent=None):
return json.dumps(obj, indent=indent, cls=JSONEncoder)
def jsonify(data, status=None):
indent = None
if flask.current_app.config['JSONIFY_PRETTYPRINT_... | Set a custom JSON Encoder to serialize date class. | Set a custom JSON Encoder to serialize date class.
| Python | apache-2.0 | viniciuschiele/flask-apscheduler | + import datetime
import flask
import json
- from datetime import datetime
from apscheduler.job import Job
from .utils import job_to_dict
+ loads = json.loads
-
- class JSONEncoder(json.JSONEncoder):
- def default(self, obj):
- if isinstance(obj, datetime):
- return obj.isoformat(... | Set a custom JSON Encoder to serialize date class. | ## Code Before:
import flask
import json
from datetime import datetime
from apscheduler.job import Job
from .utils import job_to_dict
class JSONEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return obj.isoformat()
if isinstance(obj, Job):
... |
edcfe2b156af23943478bc86592b4c8d5dc07e10 | flask_mongoengine/json.py | flask_mongoengine/json.py | from flask.json import JSONEncoder
from bson import json_util
from mongoengine.base import BaseDocument
from mongoengine import QuerySet
def _make_encoder(superclass):
class MongoEngineJSONEncoder(superclass):
'''
A JSONEncoder which provides serialization of MongoEngine
documents and quer... | from flask.json import JSONEncoder
from bson import json_util
from mongoengine.base import BaseDocument
try:
from mongoengine.base import BaseQuerySet
except ImportError as ie: # support mongoengine < 0.7
from mongoengine.queryset import QuerySet as BaseQuerySet
def _make_encoder(superclass):
class MongoEn... | Support older versions of MongoEngine | Support older versions of MongoEngine
| Python | bsd-3-clause | gerasim13/flask-mongoengine-1,rochacbruno/flask-mongoengine,quokkaproject/flask-mongoengine,quokkaproject/flask-mongoengine,gerasim13/flask-mongoengine-1,losintikfos/flask-mongoengine,rochacbruno/flask-mongoengine,losintikfos/flask-mongoengine | from flask.json import JSONEncoder
from bson import json_util
from mongoengine.base import BaseDocument
+ try:
- from mongoengine import QuerySet
+ from mongoengine.base import BaseQuerySet
-
+ except ImportError as ie: # support mongoengine < 0.7
+ from mongoengine.queryset import QuerySet as BaseQueryS... | Support older versions of MongoEngine | ## Code Before:
from flask.json import JSONEncoder
from bson import json_util
from mongoengine.base import BaseDocument
from mongoengine import QuerySet
def _make_encoder(superclass):
class MongoEngineJSONEncoder(superclass):
'''
A JSONEncoder which provides serialization of MongoEngine
do... |
3d7b5d61b7e985d409cd50c98d4bcbdc8ab9c723 | mailer.py | mailer.py | from marrow.mailer import Mailer as MarrowMailer
from message import Message
import sys
class Mailer:
MAILER = MarrowMailer(dict(manager=dict(use='immediate'), transport=dict(use='sendmail')))
@staticmethod
def send(message):
Mailer.MAILER.send(message)
@staticmethod
def start():
Mailer.MAILER.s... | from marrow.mailer import Mailer as MarrowMailer
from message import Message
import sys
import os
import pwd
import socket
class Mailer:
MAILER = MarrowMailer(dict(manager=dict(use='immediate'), transport=dict(use='sendmail')))
DEFAULT_AUTHOR = pwd.getpwuid(os.getuid()).pw_name + '@' + socket.getfqdn()
@stat... | Use current user as email author | Use current user as email author
| Python | isc | 2mv/raapija | from marrow.mailer import Mailer as MarrowMailer
from message import Message
import sys
+ import os
+ import pwd
+ import socket
class Mailer:
MAILER = MarrowMailer(dict(manager=dict(use='immediate'), transport=dict(use='sendmail')))
+ DEFAULT_AUTHOR = pwd.getpwuid(os.getuid()).pw_name + '@' +... | Use current user as email author | ## Code Before:
from marrow.mailer import Mailer as MarrowMailer
from message import Message
import sys
class Mailer:
MAILER = MarrowMailer(dict(manager=dict(use='immediate'), transport=dict(use='sendmail')))
@staticmethod
def send(message):
Mailer.MAILER.send(message)
@staticmethod
def start():
... |
445f244ddac6001b65f03d058a14178a19919eed | diamondash/config.py | diamondash/config.py | import yaml
from diamondash import utils
class ConfigError(Exception):
"""Raised when there is an error parsing a configuration"""
class ConfigMetaClass(type):
def __new__(mcs, name, bases, dict):
cls = type.__new__(mcs, name, bases, dict)
defaults = {}
for base in bases:
... | import yaml
from diamondash import utils
class ConfigError(Exception):
"""Raised when there is an error parsing a configuration"""
class ConfigMetaClass(type):
def __new__(mcs, name, bases, dict):
cls = type.__new__(mcs, name, bases, dict)
defaults = {}
for base in bases:
... | Allow Config to be initialised without any args | Allow Config to be initialised without any args
| Python | bsd-3-clause | praekelt/diamondash,praekelt/diamondash,praekelt/diamondash | import yaml
from diamondash import utils
class ConfigError(Exception):
"""Raised when there is an error parsing a configuration"""
class ConfigMetaClass(type):
def __new__(mcs, name, bases, dict):
cls = type.__new__(mcs, name, bases, dict)
defaults = {}
... | Allow Config to be initialised without any args | ## Code Before:
import yaml
from diamondash import utils
class ConfigError(Exception):
"""Raised when there is an error parsing a configuration"""
class ConfigMetaClass(type):
def __new__(mcs, name, bases, dict):
cls = type.__new__(mcs, name, bases, dict)
defaults = {}
for base in ... |
bfcec696308ee8bfd226a54c17a7e15d49e2aed7 | var/spack/repos/builtin/packages/nextflow/package.py | var/spack/repos/builtin/packages/nextflow/package.py | from spack import *
from glob import glob
import os
class Nextflow(Package):
"""Data-driven computational pipelines"""
homepage = "http://www.nextflow.io"
version('0.20.1', '0e4e0e3eca1c2c97f9b4bffd944b923a',
url='https://github.com/nextflow-io/nextflow/releases/download/v0.20.1/nextflow',
... | from spack import *
class Nextflow(Package):
"""Data-driven computational pipelines"""
homepage = "http://www.nextflow.io"
version('0.20.1', '0e4e0e3eca1c2c97f9b4bffd944b923a',
url='https://github.com/nextflow-io/nextflow/releases/download/v0.20.1/nextflow',
expand=False)
de... | Add standard header, use spack helpers | Add standard header, use spack helpers
Added the standard header (stolen from R).
Touched up the install to use set_executable rather than doing it
myself.
| Python | lgpl-2.1 | matthiasdiener/spack,mfherbst/spack,lgarren/spack,tmerrick1/spack,TheTimmy/spack,LLNL/spack,tmerrick1/spack,TheTimmy/spack,TheTimmy/spack,matthiasdiener/spack,LLNL/spack,iulian787/spack,matthiasdiener/spack,krafczyk/spack,tmerrick1/spack,EmreAtes/spack,TheTimmy/spack,tmerrick1/spack,iulian787/spack,matthiasdiener/spack... | from spack import *
+
- from glob import glob
- import os
class Nextflow(Package):
"""Data-driven computational pipelines"""
homepage = "http://www.nextflow.io"
version('0.20.1', '0e4e0e3eca1c2c97f9b4bffd944b923a',
url='https://github.com/nextflow-io/nextflow/releases/downl... | Add standard header, use spack helpers | ## Code Before:
from spack import *
from glob import glob
import os
class Nextflow(Package):
"""Data-driven computational pipelines"""
homepage = "http://www.nextflow.io"
version('0.20.1', '0e4e0e3eca1c2c97f9b4bffd944b923a',
url='https://github.com/nextflow-io/nextflow/releases/download/v0.20... |
0324d220872ef063cb39ce62264bd4835f260920 | test_project/urls.py | test_project/urls.py | from django.conf.urls import include, url
from django.contrib import admin
from django.views.generic import RedirectView
from test_app.models import DummyModel, MushroomSpot
from test_app.views import DummyDocumentOdt, DummyDocumentWeasyprint
from mapentity.registry import registry
handler403 = 'mapentity.views.hand... | from django.conf.urls import include, url
from django.contrib import admin
from django.views.generic import RedirectView
from test_app.models import DummyModel, MushroomSpot
from test_app.views import DummyDocumentOdt, DummyDocumentWeasyprint
from mapentity.registry import registry
from django.contrib.auth import view... | Replace str into call in url | Replace str into call in url
| Python | bsd-3-clause | makinacorpus/django-mapentity,makinacorpus/django-mapentity,makinacorpus/django-mapentity | from django.conf.urls import include, url
from django.contrib import admin
from django.views.generic import RedirectView
from test_app.models import DummyModel, MushroomSpot
from test_app.views import DummyDocumentOdt, DummyDocumentWeasyprint
from mapentity.registry import registry
+ from django.contrib.... | Replace str into call in url | ## Code Before:
from django.conf.urls import include, url
from django.contrib import admin
from django.views.generic import RedirectView
from test_app.models import DummyModel, MushroomSpot
from test_app.views import DummyDocumentOdt, DummyDocumentWeasyprint
from mapentity.registry import registry
handler403 = 'mape... |
d1ea64d6645f60df38221cbd194c26dff9686dcd | scripts/utils.py | scripts/utils.py | import sys
import hashlib
def e(s):
if type(s) == str:
return str
return s.encode('utf-8')
def d(s):
if type(s) == unicode:
return s
return unicode(s, 'utf-8')
def mkid(s):
return hashlib.sha1(e(s)).hexdigest()[:2*4]
class Logger(object):
def __init__(self):
self._mod... | import sys
import hashlib
def e(s):
if type(s) == str:
return str
return s.encode('utf-8')
def d(s):
if type(s) == unicode:
return s
return unicode(s, 'utf-8')
def mkid(s):
return hashlib.sha1(e(s)).hexdigest()[:2*4]
class Logger(object):
def __init__(self):
self._mod... | Handle logging unicode messages in python2. | Handle logging unicode messages in python2.
Former-commit-id: 257d94eb71d5597ff52a18ec1530d73496901ef4 | Python | mit | guilherme-pg/citationhunt,eggpi/citationhunt,guilherme-pg/citationhunt,eggpi/citationhunt,eggpi/citationhunt,guilherme-pg/citationhunt,guilherme-pg/citationhunt,eggpi/citationhunt | import sys
import hashlib
def e(s):
if type(s) == str:
return str
return s.encode('utf-8')
def d(s):
if type(s) == unicode:
return s
return unicode(s, 'utf-8')
def mkid(s):
return hashlib.sha1(e(s)).hexdigest()[:2*4]
class Logger(object):
d... | Handle logging unicode messages in python2. | ## Code Before:
import sys
import hashlib
def e(s):
if type(s) == str:
return str
return s.encode('utf-8')
def d(s):
if type(s) == unicode:
return s
return unicode(s, 'utf-8')
def mkid(s):
return hashlib.sha1(e(s)).hexdigest()[:2*4]
class Logger(object):
def __init__(self):
... |
9a698d1428fbe0744c9dba3532b778569dbe1dd4 | server.py | server.py | import socket
import sys
class SimpleServer(object):
"""Simple server using the socket library"""
def __init__(self, blocking=False, connection_oriented=True):
"""
The constructor initializes socket specifying the blocking status and
if it must be a connection oriented socket.
... |
import socket
import sys
__author__ = "Facundo Victor"
__license__ = "MIT"
__email__ = "facundovt@gmail.com"
class SimpleServer(object):
"""Simple server using the socket library"""
def __init__(self, blocking=False, connection_oriented=True):
"""
The constructor initializes socket specify... | Add docstrings and author reference | Add docstrings and author reference
| Python | mit | facundovictor/non-blocking-socket-samples | +
import socket
import sys
+
+
+ __author__ = "Facundo Victor"
+ __license__ = "MIT"
+ __email__ = "facundovt@gmail.com"
class SimpleServer(object):
"""Simple server using the socket library"""
def __init__(self, blocking=False, connection_oriented=True):
"""
The constr... | Add docstrings and author reference | ## Code Before:
import socket
import sys
class SimpleServer(object):
"""Simple server using the socket library"""
def __init__(self, blocking=False, connection_oriented=True):
"""
The constructor initializes socket specifying the blocking status and
if it must be a connection oriented... |
5f501af61b416dae0e46236a8e1f9684dcc66e21 | python/decoder_test.py | python/decoder_test.py | import argparse
import scanner
import numpy as np
import cv2
from decode import db
@db.loader('frame')
def load_frames(buf, metadata):
return np.frombuffer(buf, dtype=np.uint8) \
.reshape((metadata.height,metadata.width,3))
def extract_frames(args):
job = load_frames(args['dataset'], 'edr')
v... | import argparse
import scanner
import numpy as np
import cv2
from decode import db
@db.loader('frame')
def load_frames(buf, metadata):
return np.frombuffer(buf, dtype=np.uint8) \
.reshape((metadata.height,metadata.width,3))
def extract_frames(args):
job = load_frames(args['dataset'], 'edr')
v... | Write out concatenated frame on decode test failure | Write out concatenated frame on decode test failure
| Python | apache-2.0 | scanner-research/scanner,scanner-research/scanner,scanner-research/scanner,scanner-research/scanner | import argparse
import scanner
import numpy as np
import cv2
from decode import db
@db.loader('frame')
def load_frames(buf, metadata):
return np.frombuffer(buf, dtype=np.uint8) \
.reshape((metadata.height,metadata.width,3))
def extract_frames(args):
job = load_frames(arg... | Write out concatenated frame on decode test failure | ## Code Before:
import argparse
import scanner
import numpy as np
import cv2
from decode import db
@db.loader('frame')
def load_frames(buf, metadata):
return np.frombuffer(buf, dtype=np.uint8) \
.reshape((metadata.height,metadata.width,3))
def extract_frames(args):
job = load_frames(args['dataset... |
e2cba02550dfbe8628daf024a2a35c0dffb234e9 | python/cli/request.py | python/cli/request.py | import requests
import os
aport = os.environ.get('MYAPORT')
if aport is None:
aport = "80"
aport = "23456"
url1 = 'http://localhost:' + aport + '/'
url2 = 'http://localhost:' + aport + '/action/improvesimulateinvest'
url3 = 'http://localhost:' + aport + '/action/autosimulateinvest'
url4 = 'http://localhost:' + a... | import requests
import os
aport = os.environ.get('MYAPORT')
if aport is None:
aport = "80"
aport = "23456"
ahost = os.environ.get('MYAHOST')
if ahost is None:
ahost = "localhost"
url1 = 'http://' + ahost + ':' + aport + '/'
#headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
#hea... | Handle different environments, for automation (I4). | Handle different environments, for automation (I4).
| Python | agpl-3.0 | rroart/aether,rroart/aether,rroart/aether,rroart/aether,rroart/aether | import requests
import os
aport = os.environ.get('MYAPORT')
if aport is None:
aport = "80"
+ aport = "23456"
- aport = "23456"
-
+ ahost = os.environ.get('MYAHOST')
+ if ahost is None:
+ ahost = "localhost"
+
- url1 = 'http://localhost:' + aport + '/'
+ url1 = 'http://' + ahost + ':' +... | Handle different environments, for automation (I4). | ## Code Before:
import requests
import os
aport = os.environ.get('MYAPORT')
if aport is None:
aport = "80"
aport = "23456"
url1 = 'http://localhost:' + aport + '/'
url2 = 'http://localhost:' + aport + '/action/improvesimulateinvest'
url3 = 'http://localhost:' + aport + '/action/autosimulateinvest'
url4 = 'http:/... |
0adadcb3f04e2ecb98b5ca5de1afba2ba7208d23 | spacy/tests/parser/test_beam_parse.py | spacy/tests/parser/test_beam_parse.py | import spacy
import pytest
@pytest.mark.models
def test_beam_parse():
nlp = spacy.load('en_core_web_sm')
doc = nlp(u'Australia is a country', disable=['ner'])
ents = nlp.entity(doc, beam_width=2)
print(ents)
| from __future__ import unicode_literals
import pytest
@pytest.mark.models('en')
def test_beam_parse(EN):
doc = EN(u'Australia is a country', disable=['ner'])
ents = EN.entity(doc, beam_width=2)
print(ents)
| Fix beam parse model test | Fix beam parse model test
| Python | mit | aikramer2/spaCy,spacy-io/spaCy,recognai/spaCy,recognai/spaCy,explosion/spaCy,recognai/spaCy,explosion/spaCy,spacy-io/spaCy,recognai/spaCy,explosion/spaCy,spacy-io/spaCy,spacy-io/spaCy,aikramer2/spaCy,explosion/spaCy,spacy-io/spaCy,aikramer2/spaCy,spacy-io/spaCy,honnibal/spaCy,explosion/spaCy,honnibal/spaCy,aikramer2/sp... | - import spacy
+ from __future__ import unicode_literals
+
import pytest
+
- @pytest.mark.models
+ @pytest.mark.models('en')
- def test_beam_parse():
+ def test_beam_parse(EN):
- nlp = spacy.load('en_core_web_sm')
- doc = nlp(u'Australia is a country', disable=['ner'])
+ doc = EN(u'Australia is a cou... | Fix beam parse model test | ## Code Before:
import spacy
import pytest
@pytest.mark.models
def test_beam_parse():
nlp = spacy.load('en_core_web_sm')
doc = nlp(u'Australia is a country', disable=['ner'])
ents = nlp.entity(doc, beam_width=2)
print(ents)
## Instruction:
Fix beam parse model test
## Code After:
from __future__ impo... |
8d3931fd5effabf9c5d56cb03ae15630ae984963 | postalcodes_mexico/cli.py | postalcodes_mexico/cli.py |
"""Console script for postalcodes_mexico."""
import sys
import click
@click.command()
def main(args=None):
"""Console script for postalcodes_mexico."""
click.echo("Replace this message by putting your code into "
"postalcodes_mexico.cli.main")
click.echo("See click documentation at http://... |
"""Console script for postalcodes_mexico."""
import sys
import click
from postalcodes_mexico import postalcodes_mexico
@click.command()
@click.argument('postalcode', type=str)
def main(postalcode):
"""Console script for postalcodes_mexico."""
places = postalcodes_mexico.places(postalcode)
click.echo(pla... | Create simple CLI for the `places` function | Create simple CLI for the `places` function
| Python | mit | FlowFX/postalcodes_mexico |
"""Console script for postalcodes_mexico."""
import sys
import click
+ from postalcodes_mexico import postalcodes_mexico
+
@click.command()
- def main(args=None):
+ @click.argument('postalcode', type=str)
+ def main(postalcode):
"""Console script for postalcodes_mexico."""
+ places = postalc... | Create simple CLI for the `places` function | ## Code Before:
"""Console script for postalcodes_mexico."""
import sys
import click
@click.command()
def main(args=None):
"""Console script for postalcodes_mexico."""
click.echo("Replace this message by putting your code into "
"postalcodes_mexico.cli.main")
click.echo("See click document... |
8be6b576007f89fad50ea1dfacad46614c0a97c5 | apps/domain/src/main/core/exceptions.py | apps/domain/src/main/core/exceptions.py | """Specific PyGrid exceptions."""
class PyGridError(Exception):
def __init__(self, message):
super().__init__(message)
class AuthorizationError(PyGridError):
def __init__(self, message=""):
if not message:
message = "User is not authorized for this operation!"
super().__i... | """Specific PyGrid exceptions."""
class PyGridError(Exception):
def __init__(self, message):
super().__init__(message)
class AuthorizationError(PyGridError):
def __init__(self, message=""):
if not message:
message = "User is not authorized for this operation!"
super().__i... | ADD new exception -> EnvironmentNotFound! | ADD new exception -> EnvironmentNotFound!
| Python | apache-2.0 | OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft | """Specific PyGrid exceptions."""
class PyGridError(Exception):
def __init__(self, message):
super().__init__(message)
class AuthorizationError(PyGridError):
def __init__(self, message=""):
if not message:
message = "User is not authorized for this operati... | ADD new exception -> EnvironmentNotFound! | ## Code Before:
"""Specific PyGrid exceptions."""
class PyGridError(Exception):
def __init__(self, message):
super().__init__(message)
class AuthorizationError(PyGridError):
def __init__(self, message=""):
if not message:
message = "User is not authorized for this operation!"
... |
e0b82cf9ed24870cb313328e5539acc5fe7f6508 | stock_awesome/levels/chock_a_block.py | stock_awesome/levels/chock_a_block.py | import time
from stock_awesome.obj import market
def main():
"""
Algorithm: Wait for an ask, then send a fill or kill for the quantity of the ask at the ask
price.
"""
m = market.StockAPI('WEB29978261', 'NOWUEX', 'BBCM')
#collection of orders placed
orders = {}
filled = 0
upper... | import time
from stock_awesome.obj import market
def main():
"""
Algorithm: Wait for an ask, then send a fill or kill for the quantity of the ask at the ask
price.
"""
m = market.StockAPI('RAJ40214463', 'SSMCEX', 'IPSO')
#collection of orders placed
orders = {}
filled = 0
upper... | Add some (inefective) score maximizing attempts | Add some (inefective) score maximizing attempts
| Python | mit | ForeverWintr/stock_awesome | import time
from stock_awesome.obj import market
def main():
"""
Algorithm: Wait for an ask, then send a fill or kill for the quantity of the ask at the ask
price.
"""
- m = market.StockAPI('WEB29978261', 'NOWUEX', 'BBCM')
+ m = market.StockAPI('RAJ40214463', 'SSMCEX', ... | Add some (inefective) score maximizing attempts | ## Code Before:
import time
from stock_awesome.obj import market
def main():
"""
Algorithm: Wait for an ask, then send a fill or kill for the quantity of the ask at the ask
price.
"""
m = market.StockAPI('WEB29978261', 'NOWUEX', 'BBCM')
#collection of orders placed
orders = {}
fille... |
6bfb23294c2cc445479f4c8098b8e62647cf01bd | test/test_notification_integration.py | test/test_notification_integration.py | import os
import select
import groundstation.fs_watcher as fs_watcher
from groundstation.peer_socket import PeerSocket
from integration_fixture import StationIntegrationFixture, \
TestListener, \
TestClient
class StationFSWatcherIntegration(StationInteg... | import os
import select
import groundstation.fs_watcher as fs_watcher
from groundstation.peer_socket import PeerSocket
from groundstation.utils import path2id
from integration_fixture import StationIntegrationFixture, \
TestListener, \
TestClient
class... | Validate that we can translate a NEWOBJECT into a FETCHOBJECT | Validate that we can translate a NEWOBJECT into a FETCHOBJECT
| Python | mit | richo/groundstation,richo/groundstation,richo/groundstation,richo/groundstation,richo/groundstation | import os
import select
import groundstation.fs_watcher as fs_watcher
from groundstation.peer_socket import PeerSocket
+
+ from groundstation.utils import path2id
from integration_fixture import StationIntegrationFixture, \
TestListener, \
... | Validate that we can translate a NEWOBJECT into a FETCHOBJECT | ## Code Before:
import os
import select
import groundstation.fs_watcher as fs_watcher
from groundstation.peer_socket import PeerSocket
from integration_fixture import StationIntegrationFixture, \
TestListener, \
TestClient
class StationFSWatcherIntegrat... |
6fe5a416ed229e7ec8efab9d6b3dac43f16515b6 | corehq/apps/domain/__init__.py | corehq/apps/domain/__init__.py | from corehq.preindex import ExtraPreindexPlugin
from django.conf import settings
ExtraPreindexPlugin.register('domain', __file__, (
settings.NEW_USERS_GROUPS_DB, settings.NEW_FIXTURES_DB, 'meta'))
| from corehq.preindex import ExtraPreindexPlugin
from django.conf import settings
ExtraPreindexPlugin.register('domain', __file__, (
settings.NEW_DOMAINS_DB,
settings.NEW_USERS_GROUPS_DB,
settings.NEW_FIXTURES_DB,
'meta',
))
| Add the new domains db | Add the new domains db
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq | from corehq.preindex import ExtraPreindexPlugin
from django.conf import settings
ExtraPreindexPlugin.register('domain', __file__, (
- settings.NEW_USERS_GROUPS_DB, settings.NEW_FIXTURES_DB, 'meta'))
+ settings.NEW_DOMAINS_DB,
+ settings.NEW_USERS_GROUPS_DB,
+ settings.NEW_FIXTURES_DB,
+ 'me... | Add the new domains db | ## Code Before:
from corehq.preindex import ExtraPreindexPlugin
from django.conf import settings
ExtraPreindexPlugin.register('domain', __file__, (
settings.NEW_USERS_GROUPS_DB, settings.NEW_FIXTURES_DB, 'meta'))
## Instruction:
Add the new domains db
## Code After:
from corehq.preindex import ExtraPreindexPlugin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.