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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
932ee2737b822742996f234c90b715771fb876bf | tests/functional/api/view_pdf_test.py | tests/functional/api/view_pdf_test.py | import pytest
from tests.conftest import assert_cache_control
class TestViewPDFAPI:
def test_caching_is_disabled(self, test_app):
response = test_app.get("/pdf?url=http://example.com/foo.pdf")
assert_cache_control(
response.headers, ["max-age=0", "must-revalidate", "no-cache", "no-st... | from tests.conftest import assert_cache_control
class TestViewPDFAPI:
def test_caching_is_disabled(self, test_app):
response = test_app.get("/pdf?url=http://example.com/foo.pdf")
assert_cache_control(
response.headers, ["max-age=0", "must-revalidate", "no-cache", "no-store"]
)... | Fix lint errors after adding missing __init__ files | Fix lint errors after adding missing __init__ files
| Python | bsd-2-clause | hypothesis/via,hypothesis/via,hypothesis/via | - import pytest
-
from tests.conftest import assert_cache_control
class TestViewPDFAPI:
def test_caching_is_disabled(self, test_app):
response = test_app.get("/pdf?url=http://example.com/foo.pdf")
assert_cache_control(
response.headers, ["max-age=0", "must-revalidat... | Fix lint errors after adding missing __init__ files | ## Code Before:
import pytest
from tests.conftest import assert_cache_control
class TestViewPDFAPI:
def test_caching_is_disabled(self, test_app):
response = test_app.get("/pdf?url=http://example.com/foo.pdf")
assert_cache_control(
response.headers, ["max-age=0", "must-revalidate", "n... |
50f2cd076aae183376ab14d31594c104ac210738 | shivyc.py | shivyc.py |
import argparse
def get_arguments():
"""Set up the argument parser and return an object storing the
argument values.
return - An object storing argument values, as returned by
argparse.parse_args()
"""
parser = argparse.ArgumentParser(description="Compile C files.")
# The C file to com... |
import argparse
def get_arguments():
"""Set up the argument parser and return an object storing the
argument values.
return - An object storing argument values, as returned by
argparse.parse_args()
"""
parser = argparse.ArgumentParser(description="Compile C files.")
# The file name of ... | Rename file_name argument on command line | Rename file_name argument on command line
| Python | mit | ShivamSarodia/ShivyC,ShivamSarodia/ShivyC,ShivamSarodia/ShivyC |
import argparse
def get_arguments():
"""Set up the argument parser and return an object storing the
argument values.
return - An object storing argument values, as returned by
argparse.parse_args()
"""
parser = argparse.ArgumentParser(description="Compile C files."... | Rename file_name argument on command line | ## Code Before:
import argparse
def get_arguments():
"""Set up the argument parser and return an object storing the
argument values.
return - An object storing argument values, as returned by
argparse.parse_args()
"""
parser = argparse.ArgumentParser(description="Compile C files.")
# T... |
66a9d140feb3a0bd332031853fb1038622fd5c5b | oidc_apis/utils.py | oidc_apis/utils.py | from collections import OrderedDict
def combine_uniquely(iterable1, iterable2):
"""
Combine unique items of two sequences preserving order.
:type seq1: Iterable[Any]
:type seq2: Iterable[Any]
:rtype: list[Any]
"""
result = OrderedDict.fromkeys(iterable1)
for item in iterable2:
... | from collections import OrderedDict
import django
from oidc_provider import settings
from django.contrib.auth import BACKEND_SESSION_KEY
from django.contrib.auth import logout as django_user_logout
from users.models import LoginMethod, OidcClientOptions
from django.contrib.auth.views import redirect_to_login
def comb... | Implement current session auth method check | Implement current session auth method check
| Python | mit | mikkokeskinen/tunnistamo,mikkokeskinen/tunnistamo | from collections import OrderedDict
+ import django
+ from oidc_provider import settings
+ from django.contrib.auth import BACKEND_SESSION_KEY
+ from django.contrib.auth import logout as django_user_logout
+ from users.models import LoginMethod, OidcClientOptions
+ from django.contrib.auth.views import redirect_to_lo... | Implement current session auth method check | ## Code Before:
from collections import OrderedDict
def combine_uniquely(iterable1, iterable2):
"""
Combine unique items of two sequences preserving order.
:type seq1: Iterable[Any]
:type seq2: Iterable[Any]
:rtype: list[Any]
"""
result = OrderedDict.fromkeys(iterable1)
for item in it... |
a36fe5002bbf5dfcf27a3251cfed85c341e2156d | cbcollections.py | cbcollections.py | class defaultdict(dict):
"""Poor man's implementation of defaultdict for Python 2.4
"""
def __init__(self, default_factory=None, **kwargs):
self.default_factory = default_factory
super(defaultdict, self).__init__(**kwargs)
def __getitem__(self, key):
if self.default_factory is... | class defaultdict(dict):
"""Poor man's implementation of defaultdict for Python 2.4
"""
def __init__(self, default_factory=None, **kwargs):
self.default_factory = default_factory
super(defaultdict, self).__init__(**kwargs)
def __getitem__(self, key):
if self.default_factory is... | Save generated value for defaultdict | MB-6867: Save generated value for defaultdict
Instead of just returning value, keep it in dict.
Change-Id: I2a9862503b71f2234a4a450c48998b5f53a951bc
Reviewed-on: http://review.couchbase.org/21602
Tested-by: Bin Cui <ed18693fff32c00e22495f4877a3b901bed09041@gmail.com>
Reviewed-by: Pavel Paulau <dd88eded64e90046a680e3a... | Python | apache-2.0 | couchbase/couchbase-cli,couchbaselabs/couchbase-cli,membase/membase-cli,membase/membase-cli,couchbase/couchbase-cli,membase/membase-cli,couchbaselabs/couchbase-cli,couchbaselabs/couchbase-cli | class defaultdict(dict):
"""Poor man's implementation of defaultdict for Python 2.4
"""
def __init__(self, default_factory=None, **kwargs):
self.default_factory = default_factory
super(defaultdict, self).__init__(**kwargs)
def __getitem__(self, key):
if s... | Save generated value for defaultdict | ## Code Before:
class defaultdict(dict):
"""Poor man's implementation of defaultdict for Python 2.4
"""
def __init__(self, default_factory=None, **kwargs):
self.default_factory = default_factory
super(defaultdict, self).__init__(**kwargs)
def __getitem__(self, key):
if self.de... |
b27a51f19ea3f9d13672a0db51f7d2b05f9539f0 | kitten/validation.py | kitten/validation.py | import jsonschema
CORE_SCHEMA = {
'type': 'object',
'properties': {
'paradigm': {
'type': 'string',
},
'method': {
'type': 'string',
},
},
'additionalProperties': False,
}
VALIDATORS = {
'core': CORE_SCHEMA
}
def validate(request, schema_na... | import jsonschema
CORE_SCHEMA = {
'type': 'object',
'properties': {
'paradigm': {
'type': 'string',
},
'method': {
'type': 'string',
},
'address': {
'type': 'string',
},
},
'additionalProperties': False,
}
VALIDATORS ... | Add 'address' field to core schema | Add 'address' field to core schema
| Python | mit | thiderman/network-kitten | import jsonschema
CORE_SCHEMA = {
'type': 'object',
'properties': {
'paradigm': {
'type': 'string',
},
'method': {
'type': 'string',
},
+ 'address': {
+ 'type': 'string',
+ },
},
'additional... | Add 'address' field to core schema | ## Code Before:
import jsonschema
CORE_SCHEMA = {
'type': 'object',
'properties': {
'paradigm': {
'type': 'string',
},
'method': {
'type': 'string',
},
},
'additionalProperties': False,
}
VALIDATORS = {
'core': CORE_SCHEMA
}
def validate(re... |
fb0b956563efbcd22af8300fd4341e3cb277b80a | app/models/user.py | app/models/user.py | from app import db
from flask import Flask
from datetime import datetime
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
email = db.Column(db.String(120), unique=True)
name = db.Column(db.String(80))
bio = db.Column(db.String(180))... | from app import db
from flask import Flask
from datetime import datetime
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
email = db.Column(db.String(120), unique=True)
name = db.Column(db.String(80))
bio = db.Column(db.String(180))... | Add avatar_url and owner field for User | Add avatar_url and owner field for User
| Python | agpl-3.0 | lc-soft/GitDigger,lc-soft/GitDigger,lc-soft/GitDigger,lc-soft/GitDigger | from app import db
from flask import Flask
from datetime import datetime
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
email = db.Column(db.String(120), unique=True)
name = db.Column(db.String(80))
bio = db.Co... | Add avatar_url and owner field for User | ## Code Before:
from app import db
from flask import Flask
from datetime import datetime
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
email = db.Column(db.String(120), unique=True)
name = db.Column(db.String(80))
bio = db.Column... |
9f6d4d9e82ef575164535a8fb9ea80417458dd6b | website/files/models/dataverse.py | website/files/models/dataverse.py | import requests
from framework.auth.core import _get_current_user
from website.files.models.base import File, Folder, FileNode, FileVersion
__all__ = ('DataverseFile', 'DataverseFolder', 'DataverseFileNode')
class DataverseFileNode(FileNode):
provider = 'dataverse'
class DataverseFolder(DataverseFileNode, F... | from framework.auth.core import _get_current_user
from website.files.models.base import File, Folder, FileNode, FileVersion
__all__ = ('DataverseFile', 'DataverseFolder', 'DataverseFileNode')
class DataverseFileNode(FileNode):
provider = 'dataverse'
class DataverseFolder(DataverseFileNode, Folder):
pass
... | Move override logic into update rather than touch | Move override logic into update rather than touch
| Python | apache-2.0 | Johnetordoff/osf.io,mluke93/osf.io,SSJohns/osf.io,chrisseto/osf.io,hmoco/osf.io,caseyrygt/osf.io,GageGaskins/osf.io,acshi/osf.io,alexschiller/osf.io,caseyrollins/osf.io,ZobairAlijan/osf.io,wearpants/osf.io,GageGaskins/osf.io,brandonPurvis/osf.io,CenterForOpenScience/osf.io,SSJohns/osf.io,alexschiller/osf.io,adlius/osf.... | - import requests
-
from framework.auth.core import _get_current_user
from website.files.models.base import File, Folder, FileNode, FileVersion
__all__ = ('DataverseFile', 'DataverseFolder', 'DataverseFileNode')
class DataverseFileNode(FileNode):
provider = 'dataverse'
class Datave... | Move override logic into update rather than touch | ## Code Before:
import requests
from framework.auth.core import _get_current_user
from website.files.models.base import File, Folder, FileNode, FileVersion
__all__ = ('DataverseFile', 'DataverseFolder', 'DataverseFileNode')
class DataverseFileNode(FileNode):
provider = 'dataverse'
class DataverseFolder(Data... |
06d210cdc811f0051a489f335cc94a604e99a35d | werobot/session/mongodbstorage.py | werobot/session/mongodbstorage.py |
from werobot.session import SessionStorage
from werobot.utils import json_loads, json_dumps
class MongoDBStorage(SessionStorage):
"""
MongoDBStorage 会把你的 Session 数据储存在一个 MongoDB Collection 中 ::
import pymongo
import werobot
from werobot.session.mongodbstorage import MongoDBStorage
... |
from werobot.session import SessionStorage
from werobot.utils import json_loads, json_dumps
class MongoDBStorage(SessionStorage):
"""
MongoDBStorage 会把你的 Session 数据储存在一个 MongoDB Collection 中 ::
import pymongo
import werobot
from werobot.session.mongodbstorage import MongoDBStorage
... | Use new pymongo API in MongoDBStorage | Use new pymongo API in MongoDBStorage
| Python | mit | whtsky/WeRoBot,whtsky/WeRoBot,adam139/WeRobot,adam139/WeRobot,whtsky/WeRoBot,weberwang/WeRoBot,weberwang/WeRoBot |
from werobot.session import SessionStorage
from werobot.utils import json_loads, json_dumps
class MongoDBStorage(SessionStorage):
"""
MongoDBStorage 会把你的 Session 数据储存在一个 MongoDB Collection 中 ::
import pymongo
import werobot
from werobot.session.mongodbstorage ... | Use new pymongo API in MongoDBStorage | ## Code Before:
from werobot.session import SessionStorage
from werobot.utils import json_loads, json_dumps
class MongoDBStorage(SessionStorage):
"""
MongoDBStorage 会把你的 Session 数据储存在一个 MongoDB Collection 中 ::
import pymongo
import werobot
from werobot.session.mongodbstorage import M... |
841ca9cfbdb8faac9d8deb47b65717b5fb7c8eb4 | mfh.py | mfh.py | import os
import sys
import time
from multiprocessing import Process, Event
import mfhclient
import server
import update
from arguments import parse
from settings import HONEYPORT, HIVEPORT
def main():
update_event = Event()
mfhclient_process = Process(
args=(args, update_event,),
name="mfh... | import os
import sys
import time
from multiprocessing import Process, Event
import mfhclient
import server
import update
from arguments import parse
from settings import HONEYPORT, HIVEPORT
def main():
update_event = Event()
client = create_process("client", mfhclient.main, args, update_event)
serv = c... | Move all the process creation in a new function | Move all the process creation in a new function
This reduces the size of code.
| Python | mit | Zloool/manyfaced-honeypot | import os
import sys
import time
from multiprocessing import Process, Event
import mfhclient
import server
import update
from arguments import parse
from settings import HONEYPORT, HIVEPORT
def main():
update_event = Event()
+ client = create_process("client", mfhclient.main... | Move all the process creation in a new function | ## Code Before:
import os
import sys
import time
from multiprocessing import Process, Event
import mfhclient
import server
import update
from arguments import parse
from settings import HONEYPORT, HIVEPORT
def main():
update_event = Event()
mfhclient_process = Process(
args=(args, update_event,),
... |
5f128bbfc61169ac6b5f0e9f4dc6bcd05092382c | requests_cache/serializers/pipeline.py | requests_cache/serializers/pipeline.py | from typing import Any, List, Union
from ..models import CachedResponse
class Stage:
"""Generic class to wrap serialization steps with consistent ``dumps()`` and ``loads()`` methods"""
def __init__(self, obj: Any, dumps: str = "dumps", loads: str = "loads"):
self.obj = obj
self.dumps = getat... | from typing import Any, Callable, List, Union
from ..models import CachedResponse
class Stage:
"""Generic class to wrap serialization steps with consistent ``dumps()`` and ``loads()`` methods
Args:
obj: Serializer object or module, if applicable
dumps: Serialization function, or name of meth... | Allow Stage objects to take functions instead of object + method names | Allow Stage objects to take functions instead of object + method names
| Python | bsd-2-clause | reclosedev/requests-cache | - from typing import Any, List, Union
+ from typing import Any, Callable, List, Union
from ..models import CachedResponse
class Stage:
- """Generic class to wrap serialization steps with consistent ``dumps()`` and ``loads()`` methods"""
+ """Generic class to wrap serialization steps with consistent... | Allow Stage objects to take functions instead of object + method names | ## Code Before:
from typing import Any, List, Union
from ..models import CachedResponse
class Stage:
"""Generic class to wrap serialization steps with consistent ``dumps()`` and ``loads()`` methods"""
def __init__(self, obj: Any, dumps: str = "dumps", loads: str = "loads"):
self.obj = obj
se... |
657741f3d4df734afef228e707005dc21d540e34 | post-refunds-back.py | post-refunds-back.py | from __future__ import absolute_import, division, print_function, unicode_literals
import csv
from gratipay import wireup
from gratipay.models.exchange_route import ExchangeRoute
from gratipay.models.participant import Participant
from gratipay.billing.exchanges import record_exchange
db = wireup.db(wireup.env())
inp... | from __future__ import absolute_import, division, print_function, unicode_literals
import csv
from decimal import Decimal as D
from gratipay import wireup
from gratipay.models.exchange_route import ExchangeRoute
from gratipay.models.participant import Participant
from gratipay.billing.exchanges import record_exchange
... | Update post-back script for Braintree | Update post-back script for Braintree
| Python | mit | gratipay/gratipay.com,gratipay/gratipay.com,gratipay/gratipay.com,gratipay/gratipay.com | from __future__ import absolute_import, division, print_function, unicode_literals
import csv
+ from decimal import Decimal as D
from gratipay import wireup
from gratipay.models.exchange_route import ExchangeRoute
from gratipay.models.participant import Participant
from gratipay.billing.exchanges import ... | Update post-back script for Braintree | ## Code Before:
from __future__ import absolute_import, division, print_function, unicode_literals
import csv
from gratipay import wireup
from gratipay.models.exchange_route import ExchangeRoute
from gratipay.models.participant import Participant
from gratipay.billing.exchanges import record_exchange
db = wireup.db(w... |
022062c409ee06a719b5687ea1feb989c5cad627 | app/grandchallenge/pages/sitemaps.py | app/grandchallenge/pages/sitemaps.py | from grandchallenge.core.sitemaps import SubdomainSitemap
from grandchallenge.pages.models import Page
class PagesSitemap(SubdomainSitemap):
priority = 0.8
def items(self):
return Page.objects.filter(
permission_level=Page.ALL, challenge__hidden=False
)
| from grandchallenge.core.sitemaps import SubdomainSitemap
from grandchallenge.pages.models import Page
class PagesSitemap(SubdomainSitemap):
priority = 0.8
def items(self):
return Page.objects.filter(
permission_level=Page.ALL, challenge__hidden=False, hidden=False,
)
| Remove hidden public pages from sitemap | Remove hidden public pages from sitemap
| Python | apache-2.0 | comic/comic-django,comic/comic-django,comic/comic-django,comic/comic-django,comic/comic-django | from grandchallenge.core.sitemaps import SubdomainSitemap
from grandchallenge.pages.models import Page
class PagesSitemap(SubdomainSitemap):
priority = 0.8
def items(self):
return Page.objects.filter(
- permission_level=Page.ALL, challenge__hidden=False
+ per... | Remove hidden public pages from sitemap | ## Code Before:
from grandchallenge.core.sitemaps import SubdomainSitemap
from grandchallenge.pages.models import Page
class PagesSitemap(SubdomainSitemap):
priority = 0.8
def items(self):
return Page.objects.filter(
permission_level=Page.ALL, challenge__hidden=False
)
## Instruc... |
c5239c6bbb40ede4279b33b965c5ded26a78b2ae | app/tests/manual/test_twitter_api.py | app/tests/manual/test_twitter_api.py | from __future__ import absolute_import
from unittest import TestCase
from lib.twitter_api import authentication
class TestAuth(TestCase):
def test_generateAppAccessToken(self):
auth = authentication._generateAppAccessToken()
def test_getTweepyConnection(self):
auth = authentication._generat... | from __future__ import absolute_import
import os
import sys
import unittest
from unittest import TestCase
# Allow imports to be done when executing this file directly.
sys.path.insert(0, os.path.abspath(os.path.join(
os.path.dirname(__file__), os.path.pardir, os.path.pardir)
))
from lib.twitter_api import authen... | Update Twitter auth test to run directly | test: Update Twitter auth test to run directly
| Python | mit | MichaelCurrin/twitterverse,MichaelCurrin/twitterverse | from __future__ import absolute_import
+ import os
+ import sys
+ import unittest
from unittest import TestCase
+
+ # Allow imports to be done when executing this file directly.
+ sys.path.insert(0, os.path.abspath(os.path.join(
+ os.path.dirname(__file__), os.path.pardir, os.path.pardir)
+ ))
+
from lib... | Update Twitter auth test to run directly | ## Code Before:
from __future__ import absolute_import
from unittest import TestCase
from lib.twitter_api import authentication
class TestAuth(TestCase):
def test_generateAppAccessToken(self):
auth = authentication._generateAppAccessToken()
def test_getTweepyConnection(self):
auth = authent... |
c6862c5f864db4e77dd835f074efdd284667e6fd | util/ldjpp.py | util/ldjpp.py |
from __future__ import print_function
import argparse
import json
parser = argparse.ArgumentParser(description='Pretty-print LDJSON.')
parser.add_argument('--indent', metavar='N', type=int, default=2,
dest='indent', help='indentation for pretty-printing')
parser.add_argument('--file', metavar='FIL... |
from __future__ import print_function
import click
import json
from collections import OrderedDict
def json_loader(sortkeys):
def _loader(line):
if sortkeys:
return json.loads(line)
else:
# if --no-sortkeys, let's preserve file order
return json.JSONDecoder(obj... | Use click instead of argparse | Use click instead of argparse
| Python | mit | mhyfritz/goontools,mhyfritz/goontools,mhyfritz/goontools |
from __future__ import print_function
- import argparse
+ import click
import json
+ from collections import OrderedDict
- parser = argparse.ArgumentParser(description='Pretty-print LDJSON.')
- parser.add_argument('--indent', metavar='N', type=int, default=2,
- dest='indent', help='indenta... | Use click instead of argparse | ## Code Before:
from __future__ import print_function
import argparse
import json
parser = argparse.ArgumentParser(description='Pretty-print LDJSON.')
parser.add_argument('--indent', metavar='N', type=int, default=2,
dest='indent', help='indentation for pretty-printing')
parser.add_argument('--fil... |
b7decb588f5b6e4d15fb04fa59aa571e5570cbfe | djangae/contrib/contenttypes/apps.py | djangae/contrib/contenttypes/apps.py | from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
from django.contrib.contenttypes.management import update_contenttypes as django_update_contenttypes
from django.db.models.signals import post_migrate
from .management import update_contenttypes
from .models import SimulatedConte... | from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
from django.contrib.contenttypes.management import update_contenttypes as django_update_contenttypes
from django.db.models.signals import post_migrate
from .management import update_contenttypes
from .models import SimulatedConte... | Fix up for Django 1.9 | Fix up for Django 1.9
| Python | bsd-3-clause | grzes/djangae,potatolondon/djangae,grzes/djangae,potatolondon/djangae,grzes/djangae | from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
from django.contrib.contenttypes.management import update_contenttypes as django_update_contenttypes
from django.db.models.signals import post_migrate
from .management import update_contenttypes
from .models import ... | Fix up for Django 1.9 | ## Code Before:
from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
from django.contrib.contenttypes.management import update_contenttypes as django_update_contenttypes
from django.db.models.signals import post_migrate
from .management import update_contenttypes
from .models impor... |
dfd3bff4560d1711624b8508795eb3debbaafa40 | changes/api/snapshotimage_details.py | changes/api/snapshotimage_details.py | from __future__ import absolute_import
from flask.ext.restful import reqparse
from changes.api.base import APIView
from changes.config import db
from changes.models import SnapshotImage, SnapshotStatus
class SnapshotImageDetailsAPIView(APIView):
parser = reqparse.RequestParser()
parser.add_argument('status'... | from __future__ import absolute_import
from flask.ext.restful import reqparse
from changes.api.base import APIView
from changes.config import db
from changes.models import SnapshotImage, SnapshotStatus
class SnapshotImageDetailsAPIView(APIView):
parser = reqparse.RequestParser()
parser.add_argument('status'... | Mark snapshots as inactive if any are not valid | Mark snapshots as inactive if any are not valid
| Python | apache-2.0 | dropbox/changes,bowlofstew/changes,wfxiang08/changes,bowlofstew/changes,wfxiang08/changes,wfxiang08/changes,dropbox/changes,bowlofstew/changes,dropbox/changes,dropbox/changes,bowlofstew/changes,wfxiang08/changes | from __future__ import absolute_import
from flask.ext.restful import reqparse
from changes.api.base import APIView
from changes.config import db
from changes.models import SnapshotImage, SnapshotStatus
class SnapshotImageDetailsAPIView(APIView):
parser = reqparse.RequestParser()
pars... | Mark snapshots as inactive if any are not valid | ## Code Before:
from __future__ import absolute_import
from flask.ext.restful import reqparse
from changes.api.base import APIView
from changes.config import db
from changes.models import SnapshotImage, SnapshotStatus
class SnapshotImageDetailsAPIView(APIView):
parser = reqparse.RequestParser()
parser.add_a... |
f8b4b1a860b5c0a3ff16dbb8bbf83010bd9a1009 | feincms3/plugins/__init__.py | feincms3/plugins/__init__.py |
from . import html
from . import snippet
try:
from . import external
except ImportError: # pragma: no cover
pass
try:
from . import image
except ImportError: # pragma: no cover
pass
try:
from . import richtext
except ImportError: # pragma: no cover
pass
try:
from . import versatileimage... |
from . import html
from . import snippet
try:
import requests
except ImportError: # pragma: no cover
pass
else:
from . import external
try:
import imagefield
except ImportError: # pragma: no cover
pass
else:
from . import image
try:
import feincms3.cleanse
except ImportError: # pragma: ... | Stop hiding local import errors | feincms3.plugins: Stop hiding local import errors
| Python | bsd-3-clause | matthiask/feincms3,matthiask/feincms3,matthiask/feincms3 |
from . import html
from . import snippet
try:
- from . import external
+ import requests
except ImportError: # pragma: no cover
pass
+ else:
+ from . import external
try:
- from . import image
+ import imagefield
except ImportError: # pragma: no cover
pass
+ else:
+ ... | Stop hiding local import errors | ## Code Before:
from . import html
from . import snippet
try:
from . import external
except ImportError: # pragma: no cover
pass
try:
from . import image
except ImportError: # pragma: no cover
pass
try:
from . import richtext
except ImportError: # pragma: no cover
pass
try:
from . impor... |
b2eebbdcc14dd47d6ad8bb385966f13ed13890c1 | superdesk/coverages.py | superdesk/coverages.py | from superdesk.base_model import BaseModel
def init_app(app):
CoverageModel(app=app)
def rel(resource, embeddable=False):
return {
'type': 'objectid',
'data_relation': {'resource': resource, 'field': '_id', 'embeddable': embeddable}
}
class CoverageModel(BaseModel):
endpoint_name =... | from superdesk.base_model import BaseModel
def init_app(app):
CoverageModel(app=app)
def rel(resource, embeddable=False):
return {
'type': 'objectid',
'data_relation': {'resource': resource, 'field': '_id', 'embeddable': embeddable}
}
class CoverageModel(BaseModel):
endpoint_name =... | Fix data relation not working for custom Guids | Fix data relation not working for custom Guids
| Python | agpl-3.0 | plamut/superdesk,sivakuna-aap/superdesk,mdhaman/superdesk-aap,sivakuna-aap/superdesk,liveblog/superdesk,pavlovicnemanja/superdesk,petrjasek/superdesk,mugurrus/superdesk,ioanpocol/superdesk,pavlovicnemanja/superdesk,Aca-jov/superdesk,akintolga/superdesk,vied12/superdesk,gbbr/superdesk,fritzSF/superdesk,ancafarcas/superd... | from superdesk.base_model import BaseModel
def init_app(app):
CoverageModel(app=app)
def rel(resource, embeddable=False):
return {
'type': 'objectid',
'data_relation': {'resource': resource, 'field': '_id', 'embeddable': embeddable}
}
class CoverageModel(B... | Fix data relation not working for custom Guids | ## Code Before:
from superdesk.base_model import BaseModel
def init_app(app):
CoverageModel(app=app)
def rel(resource, embeddable=False):
return {
'type': 'objectid',
'data_relation': {'resource': resource, 'field': '_id', 'embeddable': embeddable}
}
class CoverageModel(BaseModel):
... |
4147e6f560889c75abbfd9c8e85ea38ffe408550 | suelta/mechanisms/facebook_platform.py | suelta/mechanisms/facebook_platform.py | from suelta.util import bytes
from suelta.sasl import Mechanism, register_mechanism
try:
import urlparse
except ImportError:
import urllib.parse as urlparse
class X_FACEBOOK_PLATFORM(Mechanism):
def __init__(self, sasl, name):
super(X_FACEBOOK_PLATFORM, self).__init__(sasl, name)
self.c... | from suelta.util import bytes
from suelta.sasl import Mechanism, register_mechanism
try:
import urlparse
except ImportError:
import urllib.parse as urlparse
class X_FACEBOOK_PLATFORM(Mechanism):
def __init__(self, sasl, name):
super(X_FACEBOOK_PLATFORM, self).__init__(sasl, name)
self.c... | Work around Python3's byte semantics. | Work around Python3's byte semantics.
| Python | mit | dwd/Suelta | from suelta.util import bytes
from suelta.sasl import Mechanism, register_mechanism
try:
import urlparse
except ImportError:
import urllib.parse as urlparse
class X_FACEBOOK_PLATFORM(Mechanism):
def __init__(self, sasl, name):
super(X_FACEBOOK_PLATFORM, self).__init_... | Work around Python3's byte semantics. | ## Code Before:
from suelta.util import bytes
from suelta.sasl import Mechanism, register_mechanism
try:
import urlparse
except ImportError:
import urllib.parse as urlparse
class X_FACEBOOK_PLATFORM(Mechanism):
def __init__(self, sasl, name):
super(X_FACEBOOK_PLATFORM, self).__init__(sasl, name... |
1dbe7acc945a545d3b18ec5025c19b26d1ed110f | test/test_sparql_construct_bindings.py | test/test_sparql_construct_bindings.py | from rdflib import Graph, URIRef, Literal, BNode
from rdflib.plugins.sparql import prepareQuery
from rdflib.compare import isomorphic
import unittest
class TestConstructInitBindings(unittest.TestCase):
def test_construct_init_bindings(self):
"""
This is issue https://github.com/RDFLib/rdflib/issu... | from rdflib import Graph, URIRef, Literal, BNode
from rdflib.plugins.sparql import prepareQuery
from rdflib.compare import isomorphic
import unittest
from nose.tools import eq_
class TestConstructInitBindings(unittest.TestCase):
def test_construct_init_bindings(self):
"""
This is issue https://gi... | Fix unit tests for python2 | Fix unit tests for python2
| Python | bsd-3-clause | RDFLib/rdflib,RDFLib/rdflib,RDFLib/rdflib,RDFLib/rdflib | from rdflib import Graph, URIRef, Literal, BNode
from rdflib.plugins.sparql import prepareQuery
from rdflib.compare import isomorphic
import unittest
+ from nose.tools import eq_
class TestConstructInitBindings(unittest.TestCase):
def test_construct_init_bindings(self):
"""
... | Fix unit tests for python2 | ## Code Before:
from rdflib import Graph, URIRef, Literal, BNode
from rdflib.plugins.sparql import prepareQuery
from rdflib.compare import isomorphic
import unittest
class TestConstructInitBindings(unittest.TestCase):
def test_construct_init_bindings(self):
"""
This is issue https://github.com/RD... |
2ebbe2f9f23621d10a70d0817d83da33b002299e | rest_surveys/urls.py | rest_surveys/urls.py | from __future__ import unicode_literals
from django.conf import settings
from django.conf.urls import include, url
from rest_framework_bulk.routes import BulkRouter
from rest_surveys.views import (
SurveyViewSet,
SurveyResponseViewSet,
)
# API
# With trailing slash appended:
router = BulkRouter()
router.regis... | from __future__ import unicode_literals
from django.conf import settings
from django.conf.urls import include, url
from rest_framework_bulk.routes import BulkRouter
from rest_surveys.views import (
SurveyViewSet,
SurveyResponseViewSet,
)
# API
# With trailing slash appended:
router = BulkRouter()
router.regis... | Set a default api path | Set a default api path
| Python | mit | danxshap/django-rest-surveys | from __future__ import unicode_literals
from django.conf import settings
from django.conf.urls import include, url
from rest_framework_bulk.routes import BulkRouter
from rest_surveys.views import (
SurveyViewSet,
SurveyResponseViewSet,
)
# API
# With trailing slash appended:
router =... | Set a default api path | ## Code Before:
from __future__ import unicode_literals
from django.conf import settings
from django.conf.urls import include, url
from rest_framework_bulk.routes import BulkRouter
from rest_surveys.views import (
SurveyViewSet,
SurveyResponseViewSet,
)
# API
# With trailing slash appended:
router = BulkRoute... |
a7437e657f55cd708baba83421941e67d474daf7 | tests/test_utilities.py | tests/test_utilities.py | from __future__ import (absolute_import, division, print_function)
from folium.utilities import camelize
def test_camelize():
assert camelize('variable_name') == 'variableName'
assert camelize('variableName') == 'variableName'
assert camelize('name') == 'name'
assert camelize('very_long_variable_name... | from __future__ import (absolute_import, division, print_function)
from folium.utilities import camelize, deep_copy
from folium import Map, FeatureGroup, Marker
def test_camelize():
assert camelize('variable_name') == 'variableName'
assert camelize('variableName') == 'variableName'
assert camelize('name'... | Add test for deep_copy function | Add test for deep_copy function
| Python | mit | python-visualization/folium,ocefpaf/folium,ocefpaf/folium,python-visualization/folium | from __future__ import (absolute_import, division, print_function)
- from folium.utilities import camelize
+ from folium.utilities import camelize, deep_copy
+ from folium import Map, FeatureGroup, Marker
def test_camelize():
assert camelize('variable_name') == 'variableName'
assert camelize('v... | Add test for deep_copy function | ## Code Before:
from __future__ import (absolute_import, division, print_function)
from folium.utilities import camelize
def test_camelize():
assert camelize('variable_name') == 'variableName'
assert camelize('variableName') == 'variableName'
assert camelize('name') == 'name'
assert camelize('very_lo... |
fe05b5f694671a46dd3391b9cb6561923345c4b7 | rpi_gpio_http/app.py | rpi_gpio_http/app.py | from flask import Flask
import logging
import logging.config
import RPi.GPIO as GPIO
from .config import config, config_loader
from .channel import ChannelFactory
app = Flask('rpi_gpio_http')
logging.config.dictConfig(config['logger'])
logger = logging.getLogger(__name__)
logger.info("Config loaded from %s" % confi... | from flask import Flask
import logging
import logging.config
import RPi.GPIO as GPIO
from .config import config, config_loader
from .channel import ChannelFactory
app = Flask('rpi_gpio_http')
logging.config.dictConfig(config['logger'])
logger = logging.getLogger(__name__)
logger.info("Config loaded from %s" % confi... | Disable warnings in GPIO lib | Disable warnings in GPIO lib
| Python | mit | voidpp/rpi-gpio-http | from flask import Flask
import logging
import logging.config
import RPi.GPIO as GPIO
from .config import config, config_loader
from .channel import ChannelFactory
app = Flask('rpi_gpio_http')
logging.config.dictConfig(config['logger'])
logger = logging.getLogger(__name__)
logger.info("Co... | Disable warnings in GPIO lib | ## Code Before:
from flask import Flask
import logging
import logging.config
import RPi.GPIO as GPIO
from .config import config, config_loader
from .channel import ChannelFactory
app = Flask('rpi_gpio_http')
logging.config.dictConfig(config['logger'])
logger = logging.getLogger(__name__)
logger.info("Config loaded ... |
378f55687131324bb5c43e3b50f9db5fe3b39662 | zaqar_ui/__init__.py | zaqar_ui/__init__.py |
import pbr.version
__version__ = pbr.version.VersionInfo(
'neutron_lbaas_dashboard').version_string()
|
import pbr.version
__version__ = pbr.version.VersionInfo('zaqar_ui').version_string()
| Fix Zaqar-ui with wrong reference pbr version | Fix Zaqar-ui with wrong reference pbr version
Change-Id: I84cdb865478a232886ba1059febf56735a0d91ba
| Python | apache-2.0 | openstack/zaqar-ui,openstack/zaqar-ui,openstack/zaqar-ui,openstack/zaqar-ui |
import pbr.version
+ __version__ = pbr.version.VersionInfo('zaqar_ui').version_string()
- __version__ = pbr.version.VersionInfo(
- 'neutron_lbaas_dashboard').version_string()
| Fix Zaqar-ui with wrong reference pbr version | ## Code Before:
import pbr.version
__version__ = pbr.version.VersionInfo(
'neutron_lbaas_dashboard').version_string()
## Instruction:
Fix Zaqar-ui with wrong reference pbr version
## Code After:
import pbr.version
__version__ = pbr.version.VersionInfo('zaqar_ui').version_string()
|
d659c685f40de7eb7b2ccd007888177fb158e139 | tests/integration/players.py | tests/integration/players.py | import urllib.parse
import urllib.request
def create_player(username, password, email):
url = 'https://localhost:3000/players'
values = {'username' : username,
'password' : password,
'email' : email }
data = urllib.parse.urlencode(values)
data = data.encode('utf-8') # da... |
import requests
def create_player(username, password, email):
url = 'https://localhost:3000/players'
values = {'username' : username,
'password' : password,
'email' : email }
r = requests.post(url, params=values, verify=False)
r.raise_for_status()
if (r.status_cod... | Switch to requests library instead of urllib | Switch to requests library instead of urllib
| Python | mit | dropshot/dropshot-server | - import urllib.parse
+
- import urllib.request
+ import requests
def create_player(username, password, email):
url = 'https://localhost:3000/players'
values = {'username' : username,
'password' : password,
'email' : email }
- data = urllib.parse.urlencode(val... | Switch to requests library instead of urllib | ## Code Before:
import urllib.parse
import urllib.request
def create_player(username, password, email):
url = 'https://localhost:3000/players'
values = {'username' : username,
'password' : password,
'email' : email }
data = urllib.parse.urlencode(values)
data = data.enco... |
eeeba609afe732b8e95aa535e70d4cdd2ae1aac7 | tests/unit/test_cufflinks.py | tests/unit/test_cufflinks.py | import os
import unittest
import shutil
from bcbio.rnaseq import cufflinks
from bcbio.utils import file_exists, safe_makedir
from nose.plugins.attrib import attr
DATA_DIR = os.path.join(os.path.dirname(__file__), "bcbio-nextgen-test-data", "data")
class TestCufflinks(unittest.TestCase):
merged_gtf = os.path.join(... | import os
import unittest
import shutil
from bcbio.rnaseq import cufflinks
from bcbio.utils import file_exists, safe_makedir
from nose.plugins.attrib import attr
DATA_DIR = os.path.join(os.path.dirname(__file__), "bcbio-nextgen-test-data", "data")
class TestCufflinks(unittest.TestCase):
merged_gtf = os.path.join(... | Remove some cruft from the cufflinks test. | Remove some cruft from the cufflinks test.
| Python | mit | vladsaveliev/bcbio-nextgen,biocyberman/bcbio-nextgen,verdurin/bcbio-nextgen,fw1121/bcbio-nextgen,gifford-lab/bcbio-nextgen,chapmanb/bcbio-nextgen,Cyberbio-Lab/bcbio-nextgen,hjanime/bcbio-nextgen,verdurin/bcbio-nextgen,lbeltrame/bcbio-nextgen,verdurin/bcbio-nextgen,SciLifeLab/bcbio-nextgen,chapmanb/bcbio-nextgen,lpantan... | import os
import unittest
import shutil
from bcbio.rnaseq import cufflinks
from bcbio.utils import file_exists, safe_makedir
from nose.plugins.attrib import attr
DATA_DIR = os.path.join(os.path.dirname(__file__), "bcbio-nextgen-test-data", "data")
class TestCufflinks(unittest.TestCase):
merg... | Remove some cruft from the cufflinks test. | ## Code Before:
import os
import unittest
import shutil
from bcbio.rnaseq import cufflinks
from bcbio.utils import file_exists, safe_makedir
from nose.plugins.attrib import attr
DATA_DIR = os.path.join(os.path.dirname(__file__), "bcbio-nextgen-test-data", "data")
class TestCufflinks(unittest.TestCase):
merged_gtf... |
c956fbbbc6e4dbd713728c1feda6bce2956a0894 | runtime/Python3/src/antlr4/__init__.py | runtime/Python3/src/antlr4/__init__.py | from antlr4.Token import Token
from antlr4.InputStream import InputStream
from antlr4.FileStream import FileStream
from antlr4.BufferedTokenStream import TokenStream
from antlr4.CommonTokenStream import CommonTokenStream
from antlr4.Lexer import Lexer
from antlr4.Parser import Parser
from antlr4.dfa.DFA import DFA
from... | from antlr4.Token import Token
from antlr4.InputStream import InputStream
from antlr4.FileStream import FileStream
from antlr4.StdinStream import StdinStream
from antlr4.BufferedTokenStream import TokenStream
from antlr4.CommonTokenStream import CommonTokenStream
from antlr4.Lexer import Lexer
from antlr4.Parser import... | Allow importing StdinStream from antlr4 package | Allow importing StdinStream from antlr4 package
| Python | bsd-3-clause | parrt/antlr4,ericvergnaud/antlr4,antlr/antlr4,antlr/antlr4,ericvergnaud/antlr4,parrt/antlr4,ericvergnaud/antlr4,parrt/antlr4,antlr/antlr4,parrt/antlr4,parrt/antlr4,antlr/antlr4,antlr/antlr4,antlr/antlr4,ericvergnaud/antlr4,ericvergnaud/antlr4,ericvergnaud/antlr4,parrt/antlr4,antlr/antlr4,antlr/antlr4,ericvergnaud/antlr... | from antlr4.Token import Token
from antlr4.InputStream import InputStream
from antlr4.FileStream import FileStream
+ from antlr4.StdinStream import StdinStream
from antlr4.BufferedTokenStream import TokenStream
from antlr4.CommonTokenStream import CommonTokenStream
from antlr4.Lexer import Lexer
from antl... | Allow importing StdinStream from antlr4 package | ## Code Before:
from antlr4.Token import Token
from antlr4.InputStream import InputStream
from antlr4.FileStream import FileStream
from antlr4.BufferedTokenStream import TokenStream
from antlr4.CommonTokenStream import CommonTokenStream
from antlr4.Lexer import Lexer
from antlr4.Parser import Parser
from antlr4.dfa.DFA... |
7947d474da8bb086493890d81a6788d76e00b108 | numba/cuda/tests/__init__.py | numba/cuda/tests/__init__.py | from numba.testing import SerialSuite
from numba.testing import load_testsuite
from numba import cuda
from os.path import dirname, join
def load_tests(loader, tests, pattern):
suite = SerialSuite()
this_dir = dirname(__file__)
suite.addTests(load_testsuite(loader, join(this_dir, 'nocuda')))
suite.add... | from numba.testing import SerialSuite
from numba.testing import load_testsuite
from numba import cuda
from os.path import dirname, join
def load_tests(loader, tests, pattern):
suite = SerialSuite()
this_dir = dirname(__file__)
suite.addTests(load_testsuite(loader, join(this_dir, 'nocuda')))
if cuda.i... | Fix tests on machine without CUDA | Fix tests on machine without CUDA
| Python | bsd-2-clause | sklam/numba,numba/numba,seibert/numba,IntelLabs/numba,jriehl/numba,stonebig/numba,gmarkall/numba,cpcloud/numba,IntelLabs/numba,gmarkall/numba,jriehl/numba,cpcloud/numba,sklam/numba,cpcloud/numba,numba/numba,stonebig/numba,stefanseefeld/numba,sklam/numba,cpcloud/numba,seibert/numba,sklam/numba,gmarkall/numba,stefanseefe... | from numba.testing import SerialSuite
from numba.testing import load_testsuite
from numba import cuda
from os.path import dirname, join
def load_tests(loader, tests, pattern):
suite = SerialSuite()
this_dir = dirname(__file__)
suite.addTests(load_testsuite(loader, join(this_dir, 'no... | Fix tests on machine without CUDA | ## Code Before:
from numba.testing import SerialSuite
from numba.testing import load_testsuite
from numba import cuda
from os.path import dirname, join
def load_tests(loader, tests, pattern):
suite = SerialSuite()
this_dir = dirname(__file__)
suite.addTests(load_testsuite(loader, join(this_dir, 'nocuda')... |
910d1288adddd0c8dd500c1be5e488502c1ed335 | localflavor/nl/forms.py | localflavor/nl/forms.py | """NL-specific Form helpers."""
from __future__ import unicode_literals
from django import forms
from django.utils import six
from .nl_provinces import PROVINCE_CHOICES
from .validators import NLBSNFieldValidator, NLZipCodeFieldValidator
class NLZipCodeField(forms.CharField):
"""A Dutch zip code field."""
... | """NL-specific Form helpers."""
from __future__ import unicode_literals
from django import forms
from django.utils import six
from .nl_provinces import PROVINCE_CHOICES
from .validators import NLBSNFieldValidator, NLZipCodeFieldValidator
class NLZipCodeField(forms.CharField):
"""A Dutch zip code field."""
... | Fix the wikipedia link and include a warning | Fix the wikipedia link and include a warning
| Python | bsd-3-clause | django/django-localflavor,rsalmaso/django-localflavor | """NL-specific Form helpers."""
from __future__ import unicode_literals
from django import forms
from django.utils import six
from .nl_provinces import PROVINCE_CHOICES
from .validators import NLBSNFieldValidator, NLZipCodeFieldValidator
class NLZipCodeField(forms.CharField):
"""A Dut... | Fix the wikipedia link and include a warning | ## Code Before:
"""NL-specific Form helpers."""
from __future__ import unicode_literals
from django import forms
from django.utils import six
from .nl_provinces import PROVINCE_CHOICES
from .validators import NLBSNFieldValidator, NLZipCodeFieldValidator
class NLZipCodeField(forms.CharField):
"""A Dutch zip cod... |
2e5ec8483930ad328b0a212ccc4b746f73b18c4c | pinax/ratings/tests/tests.py | pinax/ratings/tests/tests.py | from django.test import TestCase
from django.contrib.auth.models import User
from pinax.ratings.models import Rating
from .models import Car
class Tests(TestCase):
def setUp(self):
self.paltman = User.objects.create(username="paltman")
self.jtauber = User.objects.create(username="jtauber")
... | from decimal import Decimal
from django.test import TestCase
from django.contrib.auth.models import User
from pinax.ratings.models import Rating
from .models import Car
class Tests(TestCase):
def setUp(self):
self.paltman = User.objects.create(username="paltman")
self.jtauber = User.objects.c... | Use explicit Decimal in test | Use explicit Decimal in test
| Python | mit | rizumu/pinax-ratings,pinax/pinax-ratings,arthur-wsw/pinax-ratings,arthur-wsw/pinax-ratings,pinax/pinax-ratings,arthur-wsw/pinax-ratings,pinax/pinax-ratings,rizumu/pinax-ratings,rizumu/pinax-ratings | + from decimal import Decimal
+
from django.test import TestCase
from django.contrib.auth.models import User
from pinax.ratings.models import Rating
from .models import Car
class Tests(TestCase):
def setUp(self):
self.paltman = User.objects.create(username="paltman")
... | Use explicit Decimal in test | ## Code Before:
from django.test import TestCase
from django.contrib.auth.models import User
from pinax.ratings.models import Rating
from .models import Car
class Tests(TestCase):
def setUp(self):
self.paltman = User.objects.create(username="paltman")
self.jtauber = User.objects.create(usernam... |
41a0fa6412427dadfb33c77da45bc88c576fa67c | rdo/drivers/base.py | rdo/drivers/base.py | from subprocess import call
class BaseDriver(object):
def __init__(self, config):
self.config = config
def do(self, cmd):
cmd = self.command(cmd)
call(cmd)
def command(self):
raise NotImplementedError()
| from subprocess import call
class BaseDriver(object):
def __init__(self, config):
self.config = config
def working_dir(self, cmd):
command = ' '.join(cmd)
working_dir = self.config.get('directory')
if working_dir:
command = 'cd %s && %s' % (working_dir, command)
... | Add a common function for deriving the working dir. | Add a common function for deriving the working dir.
| Python | bsd-3-clause | ionrock/rdo | from subprocess import call
class BaseDriver(object):
def __init__(self, config):
self.config = config
+ def working_dir(self, cmd):
+ command = ' '.join(cmd)
+ working_dir = self.config.get('directory')
+ if working_dir:
+ command = 'cd %s && %s' ... | Add a common function for deriving the working dir. | ## Code Before:
from subprocess import call
class BaseDriver(object):
def __init__(self, config):
self.config = config
def do(self, cmd):
cmd = self.command(cmd)
call(cmd)
def command(self):
raise NotImplementedError()
## Instruction:
Add a common function for deriving ... |
e985163d189883a2419e34021971709c9c7498c0 | request/__init__.py | request/__init__.py | __version__ = 0.23
__copyright__ = 'Copyright (c) 2009, Kyle Fuller'
__licence__ = 'BSD'
__author__ = 'Kyle Fuller <inbox@kylefuller.co.uk>, krisje8 <krisje8@gmail.com>'
__URL__ = 'http://kylefuller.co.uk/project/django-request/'
| __version__ = 0.23
__copyright__ = 'Copyright (c) 2009, Kyle Fuller'
__licence__ = 'BSD'
__author__ = 'Kyle Fuller <inbox@kylefuller.co.uk>, Jannis Leidel (jezdez), krisje8 <krisje8@gmail.com>'
__URL__ = 'http://kylefuller.co.uk/project/django-request/'
| Add jezdez to the authors | Add jezdez to the authors
| Python | bsd-2-clause | gnublade/django-request,kylef/django-request,kylef/django-request,kylef/django-request,gnublade/django-request,gnublade/django-request | __version__ = 0.23
__copyright__ = 'Copyright (c) 2009, Kyle Fuller'
__licence__ = 'BSD'
- __author__ = 'Kyle Fuller <inbox@kylefuller.co.uk>, krisje8 <krisje8@gmail.com>'
+ __author__ = 'Kyle Fuller <inbox@kylefuller.co.uk>, Jannis Leidel (jezdez), krisje8 <krisje8@gmail.com>'
__URL__ = 'http://kylefuller.co.u... | Add jezdez to the authors | ## Code Before:
__version__ = 0.23
__copyright__ = 'Copyright (c) 2009, Kyle Fuller'
__licence__ = 'BSD'
__author__ = 'Kyle Fuller <inbox@kylefuller.co.uk>, krisje8 <krisje8@gmail.com>'
__URL__ = 'http://kylefuller.co.uk/project/django-request/'
## Instruction:
Add jezdez to the authors
## Code After:
__version__ = 0.... |
5881436bea688ee49175192452dec18fad4ba9b2 | airflow/executors/__init__.py | airflow/executors/__init__.py | import logging
from airflow import configuration
from airflow.executors.base_executor import BaseExecutor
from airflow.executors.local_executor import LocalExecutor
from airflow.executors.sequential_executor import SequentialExecutor
# TODO Fix this emergency fix
try:
from airflow.executors.celery_executor import... | import logging
from airflow import configuration
from airflow.executors.base_executor import BaseExecutor
from airflow.executors.local_executor import LocalExecutor
from airflow.executors.sequential_executor import SequentialExecutor
from airflow.utils import AirflowException
_EXECUTOR = configuration.get('core', 'E... | Remove hack by only importing when configured | Remove hack by only importing when configured
| Python | apache-2.0 | asnir/airflow,DEVELByte/incubator-airflow,yati-sagade/incubator-airflow,OpringaoDoTurno/airflow,yk5/incubator-airflow,spektom/incubator-airflow,owlabs/incubator-airflow,preete-dixit-ck/incubator-airflow,malmiron/incubator-airflow,alexvanboxel/airflow,wndhydrnt/airflow,bolkedebruin/airflow,dhuang/incubator-airflow,ledsu... | import logging
from airflow import configuration
from airflow.executors.base_executor import BaseExecutor
from airflow.executors.local_executor import LocalExecutor
from airflow.executors.sequential_executor import SequentialExecutor
-
- # TODO Fix this emergency fix
- try:
- from airflow.executors.ce... | Remove hack by only importing when configured | ## Code Before:
import logging
from airflow import configuration
from airflow.executors.base_executor import BaseExecutor
from airflow.executors.local_executor import LocalExecutor
from airflow.executors.sequential_executor import SequentialExecutor
# TODO Fix this emergency fix
try:
from airflow.executors.celery... |
5ac310b7c5cee4a8c5f247ae117fda17fc4cb61a | pypocketexplore/jobs.py | pypocketexplore/jobs.py | from datetime import datetime
import requests as req
from pymongo import MongoClient
from pypocketexplore.config import MONGO_URI
from time import sleep
def extract_topic_items(topic):
db = MongoClient(MONGO_URI).get_default_database()
resp = req.get('http://localhost:5000/api/topic/{}'.format(topic))
da... | from datetime import datetime
import requests as req
from pymongo import MongoClient
from pypocketexplore.config import MONGO_URI
from time import sleep
from redis import StrictRedis
import rq
def extract_topic_items(topic):
r = StrictRedis()
def topic_in_queue(topic):
q = rq.Queue('topics', connec... | Fix bug to avoid duplicating topics | Fix bug to avoid duplicating topics
| Python | mit | Florents-Tselai/PyPocketExplore | from datetime import datetime
import requests as req
from pymongo import MongoClient
from pypocketexplore.config import MONGO_URI
from time import sleep
+ from redis import StrictRedis
+ import rq
+
def extract_topic_items(topic):
+ r = StrictRedis()
+
+ def topic_in_queue(topic):
+ ... | Fix bug to avoid duplicating topics | ## Code Before:
from datetime import datetime
import requests as req
from pymongo import MongoClient
from pypocketexplore.config import MONGO_URI
from time import sleep
def extract_topic_items(topic):
db = MongoClient(MONGO_URI).get_default_database()
resp = req.get('http://localhost:5000/api/topic/{}'.forma... |
edec2186f5a83789a5d6a5dbd112c9ff716c3d46 | src/python/datamodels/output_models.py | src/python/datamodels/output_models.py | import hashlib
class Store(object):
def __init__(self):
self.id = None
self.name = None
self.location = None
def __repr__(self):
return "%s,%s,%s" % (self.name, self.location.zipcode, self.location.coords)
class Customer(object):
def __init__(self):
self.id = None
... | import hashlib
class Store(object):
"""
Record for stores.
id -- integer
name -- string
location -- ZipcodeRecord
"""
def __init__(self):
self.id = None
self.name = None
self.location = None
def __repr__(self):
return "%s,%s,%s" % (self.name, self.loca... | Add docstrings to output models | Add docstrings to output models
| Python | apache-2.0 | rnowling/bigpetstore-data-generator,rnowling/bigpetstore-data-generator,rnowling/bigpetstore-data-generator | import hashlib
class Store(object):
+ """
+ Record for stores.
+
+ id -- integer
+ name -- string
+ location -- ZipcodeRecord
+ """
+
def __init__(self):
self.id = None
self.name = None
self.location = None
def __repr__(self):
retur... | Add docstrings to output models | ## Code Before:
import hashlib
class Store(object):
def __init__(self):
self.id = None
self.name = None
self.location = None
def __repr__(self):
return "%s,%s,%s" % (self.name, self.location.zipcode, self.location.coords)
class Customer(object):
def __init__(self):
... |
fb4aa211f64ed6fdc0443d03dd02dc52fc882978 | server/dummy/dummy_server.py | server/dummy/dummy_server.py |
import BaseHTTPServer
ServerClass = BaseHTTPServer.HTTPServer
RequestHandlerClass = BaseHTTPServer.BaseHTTPRequestHandler
SERVER_NAME = ''
SERVER_PORT = 9000
class JsonPostResponder(RequestHandlerClass):
def _get_content_from_stream(self, length, stream):
return stream.read(length)
def do_POST(self... |
import BaseHTTPServer
ServerClass = BaseHTTPServer.HTTPServer
RequestHandlerClass = BaseHTTPServer.BaseHTTPRequestHandler
SERVER_NAME = ''
SERVER_PORT = 9000
class JsonPostResponder(RequestHandlerClass):
def _get_content_from_stream(self, length, stream):
return stream.read(length)
def _transaction... | Clean up and refactor printing of request | Clean up and refactor printing of request
| Python | mit | jonspeicher/Puddle,jonspeicher/Puddle,jonspeicher/Puddle |
import BaseHTTPServer
ServerClass = BaseHTTPServer.HTTPServer
RequestHandlerClass = BaseHTTPServer.BaseHTTPRequestHandler
SERVER_NAME = ''
SERVER_PORT = 9000
class JsonPostResponder(RequestHandlerClass):
def _get_content_from_stream(self, length, stream):
return stream.read(lengt... | Clean up and refactor printing of request | ## Code Before:
import BaseHTTPServer
ServerClass = BaseHTTPServer.HTTPServer
RequestHandlerClass = BaseHTTPServer.BaseHTTPRequestHandler
SERVER_NAME = ''
SERVER_PORT = 9000
class JsonPostResponder(RequestHandlerClass):
def _get_content_from_stream(self, length, stream):
return stream.read(length)
... |
3e3f7b827e226146ec7d3efe523f1f900ac4e99a | sjconfparts/type.py | sjconfparts/type.py | class Type:
@classmethod
def str_to_list(xcls, str_object):
list = map(str.strip, str_object.split(','))
try:
list.remove('')
except ValueError:
pass
return list
@classmethod
def list_to_str(xcls, list_object):
return ', '.join(list_objec... | class Type:
@classmethod
def str_to_list(xcls, str_object):
list = map(str.strip, str_object.split(','))
try:
list.remove('')
except ValueError:
pass
return list
@classmethod
def list_to_str(xcls, list_object):
return ', '.join(list_objec... | Allow “enabled“, “enable”, “disabled“, “disable” as boolean values | Allow “enabled“, “enable”, “disabled“, “disable” as boolean values
| Python | lgpl-2.1 | SmartJog/sjconf,SmartJog/sjconf | class Type:
@classmethod
def str_to_list(xcls, str_object):
list = map(str.strip, str_object.split(','))
try:
list.remove('')
except ValueError:
pass
return list
@classmethod
def list_to_str(xcls, list_object):
... | Allow “enabled“, “enable”, “disabled“, “disable” as boolean values | ## Code Before:
class Type:
@classmethod
def str_to_list(xcls, str_object):
list = map(str.strip, str_object.split(','))
try:
list.remove('')
except ValueError:
pass
return list
@classmethod
def list_to_str(xcls, list_object):
return ', '... |
00aad9bc179aa4a090f703db9669e8ba49ff8f3c | bibliopixel/main/arguments.py | bibliopixel/main/arguments.py | from .. project import project
"""Common command line arguments for run and demo."""
def add_to_parser(parser):
parser.add_argument(
'-d', '--driver', default='simpixel',
help='Default driver type if no driver is specified')
parser.add_argument(
'-l', '--layout', default='matrix',
... | import json
from .. project import project
"""Common command line arguments for run and demo."""
COMPONENTS = 'driver', 'layout', 'animation'
def add_to_parser(parser):
parser.add_argument(
'-d', '--driver', default='simpixel',
help='Default driver type if no driver is specified')
parser.ad... | Allow json in component flags. | Allow json in component flags.
| Python | mit | ManiacalLabs/BiblioPixel,ManiacalLabs/BiblioPixel,rec/BiblioPixel,ManiacalLabs/BiblioPixel,ManiacalLabs/BiblioPixel,rec/BiblioPixel,rec/BiblioPixel,rec/BiblioPixel | + import json
from .. project import project
"""Common command line arguments for run and demo."""
+
+ COMPONENTS = 'driver', 'layout', 'animation'
def add_to_parser(parser):
parser.add_argument(
'-d', '--driver', default='simpixel',
help='Default driver type if no driver is sp... | Allow json in component flags. | ## Code Before:
from .. project import project
"""Common command line arguments for run and demo."""
def add_to_parser(parser):
parser.add_argument(
'-d', '--driver', default='simpixel',
help='Default driver type if no driver is specified')
parser.add_argument(
'-l', '--layout', defa... |
802d030087d7f15add5ccfa5d305555632575642 | changes/jobs/cleanup_tasks.py | changes/jobs/cleanup_tasks.py | from __future__ import absolute_import
from datetime import datetime, timedelta
from changes.config import queue
from changes.constants import Status
from changes.experimental.stats import RCount
from changes.models import Task
from changes.queue.task import TrackedTask, tracked_task
CHECK_TIME = timedelta(minutes=6... | from __future__ import absolute_import
from datetime import datetime, timedelta
from changes.config import queue
from changes.constants import Status
from changes.experimental.stats import RCount, incr
from changes.models import Task
from changes.queue.task import TrackedTask, tracked_task
CHECK_TIME = timedelta(min... | Add counter for cleanup tasks not following the decorator | Add counter for cleanup tasks not following the decorator
| Python | apache-2.0 | bowlofstew/changes,wfxiang08/changes,dropbox/changes,wfxiang08/changes,bowlofstew/changes,wfxiang08/changes,dropbox/changes,bowlofstew/changes,bowlofstew/changes,wfxiang08/changes,dropbox/changes,dropbox/changes | from __future__ import absolute_import
from datetime import datetime, timedelta
from changes.config import queue
from changes.constants import Status
- from changes.experimental.stats import RCount
+ from changes.experimental.stats import RCount, incr
from changes.models import Task
from changes.queue... | Add counter for cleanup tasks not following the decorator | ## Code Before:
from __future__ import absolute_import
from datetime import datetime, timedelta
from changes.config import queue
from changes.constants import Status
from changes.experimental.stats import RCount
from changes.models import Task
from changes.queue.task import TrackedTask, tracked_task
CHECK_TIME = tim... |
b6db7abfd59a1b97fbb4d1b867e3316c029c94ff | spec/Report_S06_spec.py | spec/Report_S06_spec.py | from expects import expect, equal
from primestg.report import Report
from ast import literal_eval
with description('Report S06 example'):
with before.all:
self.data_filenames = [
'spec/data/S06.xml',
# 'spec/data/S06_empty.xml'
]
self.report = []
for data_... | from expects import expect, equal
from primestg.report import Report
from ast import literal_eval
with description('Report S06 example'):
with before.all:
self.data_filenames = [
'spec/data/S06.xml',
'spec/data/S06_with_error.xml',
# 'spec/data/S06_empty.xml'
]... | TEST for correct an with errors S06 report | TEST for correct an with errors S06 report
| Python | agpl-3.0 | gisce/primestg | from expects import expect, equal
from primestg.report import Report
from ast import literal_eval
with description('Report S06 example'):
with before.all:
self.data_filenames = [
'spec/data/S06.xml',
+ 'spec/data/S06_with_error.xml',
# 'spec/data/... | TEST for correct an with errors S06 report | ## Code Before:
from expects import expect, equal
from primestg.report import Report
from ast import literal_eval
with description('Report S06 example'):
with before.all:
self.data_filenames = [
'spec/data/S06.xml',
# 'spec/data/S06_empty.xml'
]
self.report = []
... |
d7ea1e9c7728b5e98e6c798ab3d5ef5b9066463c | barrage/basetestcases.py | barrage/basetestcases.py | from .baselauncher import BaseLauncher
class BaseTestCases(BaseLauncher):
def handle_problem_set(self, name, problems):
for i, prob in enumerate(problems):
answer_got = self.get_answer(prob, name, i, len(problems))
if not answer_got:
return False
if not p... | from .baselauncher import BaseLauncher
class BaseTestCases(BaseLauncher):
def handle_problem_set(self, name, problems):
for i, prob in enumerate(problems):
answer_got = self.get_answer(prob, name, i, len(problems))
if not answer_got:
return False
if not p... | Fix a bug with application stdout print | Fix a bug with application stdout print
| Python | mit | vnetserg/barrage | from .baselauncher import BaseLauncher
class BaseTestCases(BaseLauncher):
def handle_problem_set(self, name, problems):
for i, prob in enumerate(problems):
answer_got = self.get_answer(prob, name, i, len(problems))
if not answer_got:
return False
... | Fix a bug with application stdout print | ## Code Before:
from .baselauncher import BaseLauncher
class BaseTestCases(BaseLauncher):
def handle_problem_set(self, name, problems):
for i, prob in enumerate(problems):
answer_got = self.get_answer(prob, name, i, len(problems))
if not answer_got:
return False
... |
8a6bc4a46141b42d4457fdc4d63df234f788253d | django_nose/plugin.py | django_nose/plugin.py |
class ResultPlugin(object):
"""
Captures the TestResult object for later inspection.
nose doesn't return the full test result object from any of its runner
methods. Pass an instance of this plugin to the TestProgram and use
``result`` after running the tests to get the TestResult object.
"""... | import sys
class ResultPlugin(object):
"""
Captures the TestResult object for later inspection.
nose doesn't return the full test result object from any of its runner
methods. Pass an instance of this plugin to the TestProgram and use
``result`` after running the tests to get the TestResult objec... | Allow coverage to work and keep stdout and be activated before initial imports. | Allow coverage to work and keep stdout and be activated before initial imports.
| Python | bsd-3-clause | aristiden7o/django-nose,harukaeru/django-nose,disqus/django-nose,dgladkov/django-nose,mzdaniel/django-nose,sociateru/django-nose,krinart/django-nose,alexhayes/django-nose,daineX/django-nose,harukaeru/django-nose,mzdaniel/django-nose,Deepomatic/django-nose,krinart/django-nose,fabiosantoscode/django-nose-123-fix,alexhaye... | -
+ import sys
class ResultPlugin(object):
"""
Captures the TestResult object for later inspection.
nose doesn't return the full test result object from any of its runner
methods. Pass an instance of this plugin to the TestProgram and use
``result`` after running the tests to get... | Allow coverage to work and keep stdout and be activated before initial imports. | ## Code Before:
class ResultPlugin(object):
"""
Captures the TestResult object for later inspection.
nose doesn't return the full test result object from any of its runner
methods. Pass an instance of this plugin to the TestProgram and use
``result`` after running the tests to get the TestResult... |
8ae27080b8ff9fe124733005a8006261a3d22266 | migrate/crud/versions/001_create_initial_tables.py | migrate/crud/versions/001_create_initial_tables.py | from sqlalchemy import *
from migrate import *
metadata = MetaData()
table = Table('crud_versions', metadata,
Column('id', Integer, primary_key=True),
Column('object_type', Text, nullable=False),
Column('object_id', Integer, nullable=False),
Column('commit_time', DateTime, nullable=False),
Col... | from sqlalchemy import *
from migrate import *
metadata = MetaData()
table = Table('crud_versions', metadata,
Column('id', Integer, primary_key=True),
Column('object_type', Text, nullable=False),
Column('object_id', Integer, nullable=False),
Column('commit_time', DateTime, nullable=False),
Col... | Fix some of the schema. | Fix some of the schema. | Python | bsd-3-clause | mikeboers/Nitrogen,mikeboers/Nitrogen,mikeboers/Nitrogen,mikeboers/Nitrogen,mikeboers/Nitrogen,mikeboers/Nitrogen | from sqlalchemy import *
from migrate import *
metadata = MetaData()
table = Table('crud_versions', metadata,
Column('id', Integer, primary_key=True),
Column('object_type', Text, nullable=False),
Column('object_id', Integer, nullable=False),
Column('commit_time', DateTime, null... | Fix some of the schema. | ## Code Before:
from sqlalchemy import *
from migrate import *
metadata = MetaData()
table = Table('crud_versions', metadata,
Column('id', Integer, primary_key=True),
Column('object_type', Text, nullable=False),
Column('object_id', Integer, nullable=False),
Column('commit_time', DateTime, nullable... |
91acec032abeb942bf90d6522a4d9d38ad624d46 | tests/test_buffs.py | tests/test_buffs.py | import unittest
from buffs import *
class StatusEffectTests(unittest.TestCase):
"""
StatusEffect is the base class for buffs
"""
def test_init(self):
test_name = 'testman'
test_duration = 10
st_ef = StatusEffect(name=test_name, duration=test_duration)
self.assertEqual... | import unittest
from buffs import *
class StatusEffectTests(unittest.TestCase):
"""
StatusEffect is the base class for buffs
"""
def test_init(self):
test_name = 'testman'
test_duration = 10
st_ef = StatusEffect(name=test_name, duration=test_duration)
self.assertEqual... | Test for the BeneficialBuff class | Test for the BeneficialBuff class
| Python | mit | Enether/python_wow | import unittest
from buffs import *
class StatusEffectTests(unittest.TestCase):
"""
StatusEffect is the base class for buffs
"""
def test_init(self):
test_name = 'testman'
test_duration = 10
st_ef = StatusEffect(name=test_name, duration=test_duration)... | Test for the BeneficialBuff class | ## Code Before:
import unittest
from buffs import *
class StatusEffectTests(unittest.TestCase):
"""
StatusEffect is the base class for buffs
"""
def test_init(self):
test_name = 'testman'
test_duration = 10
st_ef = StatusEffect(name=test_name, duration=test_duration)
... |
6430785e60fcef9bbac3cf4e7c70981f5af6affa | fluent_contents/plugins/sharedcontent/models.py | fluent_contents/plugins/sharedcontent/models.py | from django.db import models
from django.utils.translation import ugettext_lazy as _
from parler.models import TranslatableModel, TranslatedFields
from fluent_contents.models import ContentItem, PlaceholderField
class SharedContent(TranslatableModel):
"""
The parent hosting object for shared content
"""
... | from django.db import models
from django.utils.translation import ugettext_lazy as _
from parler.models import TranslatableModel, TranslatedFields
from fluent_contents.models import ContentItem, PlaceholderField, ContentItemRelation
class SharedContent(TranslatableModel):
"""
The parent hosting object for sha... | Add ContentItemRelation to SharedContent model | Add ContentItemRelation to SharedContent model
Displays objects in the admin delete screen.
| Python | apache-2.0 | jpotterm/django-fluent-contents,django-fluent/django-fluent-contents,django-fluent/django-fluent-contents,ixc/django-fluent-contents,edoburu/django-fluent-contents,jpotterm/django-fluent-contents,django-fluent/django-fluent-contents,pombredanne/django-fluent-contents,jpotterm/django-fluent-contents,pombredanne/django-f... | from django.db import models
from django.utils.translation import ugettext_lazy as _
from parler.models import TranslatableModel, TranslatedFields
- from fluent_contents.models import ContentItem, PlaceholderField
+ from fluent_contents.models import ContentItem, PlaceholderField, ContentItemRelation
clas... | Add ContentItemRelation to SharedContent model | ## Code Before:
from django.db import models
from django.utils.translation import ugettext_lazy as _
from parler.models import TranslatableModel, TranslatedFields
from fluent_contents.models import ContentItem, PlaceholderField
class SharedContent(TranslatableModel):
"""
The parent hosting object for shared c... |
fc21802b68cf9a907218dab5b0e22cd8f1dc75d0 | djcelery/backends/database.py | djcelery/backends/database.py | from celery.backends.base import BaseDictBackend
from djcelery.models import TaskMeta, TaskSetMeta
class DatabaseBackend(BaseDictBackend):
"""The database backends. Using Django models to store task metadata."""
def _store_result(self, task_id, result, status, traceback=None):
"""Store return value ... | from celery.backends.base import BaseDictBackend
from djcelery.models import TaskMeta, TaskSetMeta
class DatabaseBackend(BaseDictBackend):
"""The database backends. Using Django models to store task metadata."""
TaskModel = TaskMeta
TaskSetModel = TaskSetMeta
def _store_result(self, task_id, result,... | Make it possible to override the models used to store task/taskset state | DatabaseBackend: Make it possible to override the models used to store task/taskset state
| Python | bsd-3-clause | Amanit/django-celery,kanemra/django-celery,axiom-data-science/django-celery,celery/django-celery,alexhayes/django-celery,digimarc/django-celery,tkanemoto/django-celery,iris-edu-int/django-celery,CloudNcodeInc/django-celery,Amanit/django-celery,CloudNcodeInc/django-celery,iris-edu-int/django-celery,CloudNcodeInc/django-... | from celery.backends.base import BaseDictBackend
from djcelery.models import TaskMeta, TaskSetMeta
class DatabaseBackend(BaseDictBackend):
"""The database backends. Using Django models to store task metadata."""
+ TaskModel = TaskMeta
+ TaskSetModel = TaskSetMeta
def _store_result(... | Make it possible to override the models used to store task/taskset state | ## Code Before:
from celery.backends.base import BaseDictBackend
from djcelery.models import TaskMeta, TaskSetMeta
class DatabaseBackend(BaseDictBackend):
"""The database backends. Using Django models to store task metadata."""
def _store_result(self, task_id, result, status, traceback=None):
"""Sto... |
97535245f7da3d7e54d64dc384d6cd81caa9a689 | tests/test_story.py | tests/test_story.py | from py101 import Story
from py101 import variables
from py101 import lists
import unittest
class TestStory(unittest.TestCase):
def test_name(self):
self.assertEqual(Story().name, 'py101', "name should be py101")
class TestAdventureVariables(unittest.TestCase):
good_solution = """
myinteger = 4
myst... | import py101
import py101.boilerplate
import py101.introduction
import py101.lists
import py101.variables
import unittest
class TestStory(unittest.TestCase):
def test_name(self):
self.assertEqual(py101.Story().name, 'py101', "name should be py101")
class AdventureData(object):
def __init__(self, tes... | Refactor tests to remove duplicate code | Refactor tests to remove duplicate code
| Python | mit | sophilabs/py101 | - from py101 import Story
- from py101 import variables
- from py101 import lists
+ import py101
+ import py101.boilerplate
+ import py101.introduction
+ import py101.lists
+ import py101.variables
import unittest
class TestStory(unittest.TestCase):
def test_name(self):
- self.assertEqual(Story(... | Refactor tests to remove duplicate code | ## Code Before:
from py101 import Story
from py101 import variables
from py101 import lists
import unittest
class TestStory(unittest.TestCase):
def test_name(self):
self.assertEqual(Story().name, 'py101', "name should be py101")
class TestAdventureVariables(unittest.TestCase):
good_solution = """
my... |
510afd0c93c333e86511fb6f6b9e96a434d54d00 | zerver/migrations/0174_userprofile_delivery_email.py | zerver/migrations/0174_userprofile_delivery_email.py | from __future__ import unicode_literals
from django.db import migrations, models
from django.apps import apps
from django.db.models import F
from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps
def copy_email_field(apps: StateApps, schema_edi... | from __future__ import unicode_literals
from django.db import migrations, models
from django.apps import apps
from django.db.models import F
from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps
def copy_email_field(apps: StateApps, schema_edi... | Disable atomic for delivery_email migration. | migrations: Disable atomic for delivery_email migration.
I'm not sure theoretically why this should be required only for some
installations, but these articles all suggest the root problem is
doing these two migrations together atomically (creating the field and
setting a value for it), so the right answer is to decla... | Python | apache-2.0 | dhcrzf/zulip,zulip/zulip,zulip/zulip,showell/zulip,dhcrzf/zulip,hackerkid/zulip,jackrzhang/zulip,eeshangarg/zulip,tommyip/zulip,brainwane/zulip,tommyip/zulip,synicalsyntax/zulip,tommyip/zulip,shubhamdhama/zulip,rht/zulip,dhcrzf/zulip,timabbott/zulip,shubhamdhama/zulip,rht/zulip,brainwane/zulip,hackerkid/zulip,synicalsy... | from __future__ import unicode_literals
from django.db import migrations, models
from django.apps import apps
from django.db.models import F
from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps
def copy_email_field(apps: S... | Disable atomic for delivery_email migration. | ## Code Before:
from __future__ import unicode_literals
from django.db import migrations, models
from django.apps import apps
from django.db.models import F
from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps
def copy_email_field(apps: State... |
50fa164c4b09845bfa262c2f6959a3c5dfd6f76b | fluentcheck/classes/is_cls.py | fluentcheck/classes/is_cls.py | from typing import Any
from ..assertions_is.booleans import __IsBool
from ..assertions_is.collections import __IsCollections
from ..assertions_is.dicts import __IsDicts
from ..assertions_is.emptiness import __IsEmptiness
from ..assertions_is.geo import __IsGeo
from ..assertions_is.numbers import __IsNumbers
from ..ass... | from typing import Any
from ..assertions_is.booleans import __IsBool
from ..assertions_is.collections import __IsCollections
from ..assertions_is.dicts import __IsDicts
from ..assertions_is.emptiness import __IsEmptiness
from ..assertions_is.geo import __IsGeo
from ..assertions_is.numbers import __IsNumbers
from ..ass... | Remove methods with unnecessary super delegation. | Remove methods with unnecessary super delegation. | Python | mit | csparpa/check | from typing import Any
from ..assertions_is.booleans import __IsBool
from ..assertions_is.collections import __IsCollections
from ..assertions_is.dicts import __IsDicts
from ..assertions_is.emptiness import __IsEmptiness
from ..assertions_is.geo import __IsGeo
from ..assertions_is.numbers import __IsNu... | Remove methods with unnecessary super delegation. | ## Code Before:
from typing import Any
from ..assertions_is.booleans import __IsBool
from ..assertions_is.collections import __IsCollections
from ..assertions_is.dicts import __IsDicts
from ..assertions_is.emptiness import __IsEmptiness
from ..assertions_is.geo import __IsGeo
from ..assertions_is.numbers import __IsNu... |
a15d2956cfd48e0d46d5d4cf567af05641b4c8e6 | yunity/api/utils.py | yunity/api/utils.py | from django.http import JsonResponse
class ApiBase(object):
@classmethod
def success(cls, data, status=200):
"""
:type data: dict
:type status: int
:rtype JsonResponse
"""
return JsonResponse(data, status=status)
@classmethod
def error(cls, error, stat... | from functools import wraps
from json import loads as load_json
from django.http import JsonResponse
class ApiBase(object):
@classmethod
def validation_failure(cls, message, status=400):
"""
:type message: str
:type status: int
:rtype JsonResponse
"""
return J... | Implement JSON request validation decorator | Implement JSON request validation decorator
with @NerdyProjects
| Python | agpl-3.0 | yunity/foodsaving-backend,yunity/foodsaving-backend,yunity/yunity-core,yunity/foodsaving-backend,yunity/yunity-core | + from functools import wraps
+ from json import loads as load_json
+
from django.http import JsonResponse
class ApiBase(object):
+ @classmethod
+ def validation_failure(cls, message, status=400):
+ """
+ :type message: str
+ :type status: int
+ :rtype JsonResponse
+
... | Implement JSON request validation decorator | ## Code Before:
from django.http import JsonResponse
class ApiBase(object):
@classmethod
def success(cls, data, status=200):
"""
:type data: dict
:type status: int
:rtype JsonResponse
"""
return JsonResponse(data, status=status)
@classmethod
def error(... |
31f887979d2129bec80311e94b91cf0f77772f26 | zou/app/utils/fs.py | zou/app/utils/fs.py | import os
import shutil
import errno
def mkdir_p(path):
try:
os.makedirs(path)
except OSError as exception:
if exception.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
def rm_rf(path):
if os.path.exists(path):
shutil.rmtree(path)
| import os
import shutil
import errno
def mkdir_p(path):
try:
os.makedirs(path)
except OSError as exception:
if exception.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
def rm_rf(path):
if os.path.exists(path):
shutil.rmtree(path)
... | Add a new copy file util function | Add a new copy file util function
| Python | agpl-3.0 | cgwire/zou | import os
import shutil
import errno
def mkdir_p(path):
try:
os.makedirs(path)
except OSError as exception:
if exception.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
def rm_rf(path):
if os.path.exists... | Add a new copy file util function | ## Code Before:
import os
import shutil
import errno
def mkdir_p(path):
try:
os.makedirs(path)
except OSError as exception:
if exception.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
def rm_rf(path):
if os.path.exists(path):
shut... |
463fa89c143cd4493ea3704f177c5aba0ebb2af7 | idiokit/xmpp/_resolve.py | idiokit/xmpp/_resolve.py | from __future__ import absolute_import
from .. import idiokit, dns
DEFAULT_XMPP_PORT = 5222
@idiokit.stream
def _add_port_and_count(port):
count = 0
while True:
try:
family, ip = yield idiokit.next()
except StopIteration:
idiokit.stop(count)
yield idiokit.se... | from __future__ import absolute_import
from .. import idiokit, dns
DEFAULT_XMPP_PORT = 5222
@idiokit.stream
def _add_port(port):
while True:
family, ip = yield idiokit.next()
yield idiokit.send(family, ip, port)
def _resolve_host(host, port):
return dns.host_lookup(host) | _add_port(port)
... | Fix SRV logic. RFC 6120 states that the fallback logic shouldn't be applied when the entity (client in this case) receives an answer to the SRV query but fails to establish a connection using the answer data. | idiokit.xmpp: Fix SRV logic. RFC 6120 states that the fallback logic shouldn't be applied when the entity (client in this case) receives an answer to the SRV query but fails to establish a connection using the answer data.
| Python | mit | abusesa/idiokit | from __future__ import absolute_import
from .. import idiokit, dns
DEFAULT_XMPP_PORT = 5222
@idiokit.stream
- def _add_port_and_count(port):
+ def _add_port(port):
- count = 0
-
while True:
- try:
- family, ip = yield idiokit.next()
+ family, ip = yield idiokit... | Fix SRV logic. RFC 6120 states that the fallback logic shouldn't be applied when the entity (client in this case) receives an answer to the SRV query but fails to establish a connection using the answer data. | ## Code Before:
from __future__ import absolute_import
from .. import idiokit, dns
DEFAULT_XMPP_PORT = 5222
@idiokit.stream
def _add_port_and_count(port):
count = 0
while True:
try:
family, ip = yield idiokit.next()
except StopIteration:
idiokit.stop(count)
... |
7e71e21734abb2b12e309ea37910c90f7b837651 | go/base/tests/test_decorators.py | go/base/tests/test_decorators.py | """Test for go.base.decorators."""
from go.vumitools.tests.helpers import djangotest_imports
with djangotest_imports(globals()):
from go.base.tests.helpers import GoDjangoTestCase
from go.base.decorators import render_exception
from django.template.response import TemplateResponse
class CatchableDummyEr... | """Test for go.base.decorators."""
from go.vumitools.tests.helpers import djangotest_imports
with djangotest_imports(globals()):
from go.base.tests.helpers import GoDjangoTestCase
from go.base.decorators import render_exception
from django.template.response import TemplateResponse
class CatchableDumm... | Move Django-specific pieces into the django_imports block. | Move Django-specific pieces into the django_imports block.
| Python | bsd-3-clause | praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go | """Test for go.base.decorators."""
from go.vumitools.tests.helpers import djangotest_imports
with djangotest_imports(globals()):
from go.base.tests.helpers import GoDjangoTestCase
from go.base.decorators import render_exception
from django.template.response import TemplateResponse
+ ... | Move Django-specific pieces into the django_imports block. | ## Code Before:
"""Test for go.base.decorators."""
from go.vumitools.tests.helpers import djangotest_imports
with djangotest_imports(globals()):
from go.base.tests.helpers import GoDjangoTestCase
from go.base.decorators import render_exception
from django.template.response import TemplateResponse
class ... |
a50aeb81a588f8297f194d793cb8f8cf0e15a411 | lambda/list_member.py | lambda/list_member.py | from __future__ import print_function
from enum import IntEnum
import yaml
MemberFlag = IntEnum('MemberFlag', [
'digest',
'digest2',
'modPost',
'preapprove',
'noPost',
'diagnostic',
'moderator',
'myopic',
'superadmin',
'admin',
'protected',
'ccErrors',
'reports',
... | from __future__ import print_function
from enum import IntEnum
import yaml
MemberFlag = IntEnum('MemberFlag', [
'digest',
'digest2',
'modPost',
'preapprove',
'noPost',
'diagnostic',
'moderator',
'myopic',
'superadmin',
'admin',
'protected',
'ccErrors',
'reports',
... | Convert list member addresses to non-unicode strings when possible. | Convert list member addresses to non-unicode strings when possible.
| Python | mit | ilg/LambdaMLM | from __future__ import print_function
from enum import IntEnum
import yaml
MemberFlag = IntEnum('MemberFlag', [
'digest',
'digest2',
'modPost',
'preapprove',
'noPost',
'diagnostic',
'moderator',
'myopic',
'superadmin',
'admin',
'protected',... | Convert list member addresses to non-unicode strings when possible. | ## Code Before:
from __future__ import print_function
from enum import IntEnum
import yaml
MemberFlag = IntEnum('MemberFlag', [
'digest',
'digest2',
'modPost',
'preapprove',
'noPost',
'diagnostic',
'moderator',
'myopic',
'superadmin',
'admin',
'protected',
'ccErrors',
... |
bd59db76bb81218d04224e44773eae9d3d9dfc21 | rplugin/python3/denite/source/toc.py | rplugin/python3/denite/source/toc.py |
from .base import Base
class Source(Base):
def __init__(self, vim):
super().__init__(vim)
self.name = 'vimtex_toc'
self.kind = 'file'
@staticmethod
def format_number(n):
if not n or n['frontmatter'] or n['backmatter']:
return ''
num = [str(n[k]) for... |
from .base import Base
class Source(Base):
def __init__(self, vim):
super().__init__(vim)
self.name = 'vimtex_toc'
self.kind = 'file'
@staticmethod
def format_number(n):
if not n or not type(n) is dict or n['frontmatter'] or n['backmatter']:
return ''
... | Fix Denite support for vim8. | Fix Denite support for vim8.
| Python | mit | lervag/vimtex,Aster89/vimtex,Aster89/vimtex,kmarius/vimtex,lervag/vimtex,kmarius/vimtex |
from .base import Base
class Source(Base):
def __init__(self, vim):
super().__init__(vim)
self.name = 'vimtex_toc'
self.kind = 'file'
@staticmethod
def format_number(n):
- if not n or n['frontmatter'] or n['backmatter']:
+ if not n or... | Fix Denite support for vim8. | ## Code Before:
from .base import Base
class Source(Base):
def __init__(self, vim):
super().__init__(vim)
self.name = 'vimtex_toc'
self.kind = 'file'
@staticmethod
def format_number(n):
if not n or n['frontmatter'] or n['backmatter']:
return ''
num ... |
dc461956408ffa35e2391fccf4231d60144985f7 | yunity/groups/api.py | yunity/groups/api.py | from rest_framework import filters
from rest_framework import status, viewsets
from rest_framework.decorators import detail_route
from rest_framework.permissions import IsAuthenticated, IsAuthenticatedOrReadOnly
from rest_framework.response import Response
from yunity.groups.serializers import GroupSerializer
from yuni... | from rest_framework import filters
from rest_framework import status, viewsets
from rest_framework.decorators import detail_route
from rest_framework.permissions import IsAuthenticated, IsAuthenticatedOrReadOnly, BasePermission
from rest_framework.response import Response
from yunity.groups.serializers import GroupSeri... | Fix permissions for groups endpoint | Fix permissions for groups endpoint
| Python | agpl-3.0 | yunity/yunity-core,yunity/yunity-core,yunity/foodsaving-backend,yunity/foodsaving-backend,yunity/foodsaving-backend | from rest_framework import filters
from rest_framework import status, viewsets
from rest_framework.decorators import detail_route
- from rest_framework.permissions import IsAuthenticated, IsAuthenticatedOrReadOnly
+ from rest_framework.permissions import IsAuthenticated, IsAuthenticatedOrReadOnly, BasePermission
... | Fix permissions for groups endpoint | ## Code Before:
from rest_framework import filters
from rest_framework import status, viewsets
from rest_framework.decorators import detail_route
from rest_framework.permissions import IsAuthenticated, IsAuthenticatedOrReadOnly
from rest_framework.response import Response
from yunity.groups.serializers import GroupSeri... |
0f7ebec0442da08b12cd88f2558146d5c5a551ad | K2fov/tests/test_plot.py | K2fov/tests/test_plot.py | """Tests K2fov.plot"""
from .. import plot
def test_basics():
"""Make sure this runs without exception."""
try:
import matplotlib
plot.create_context_plot(180, 0)
plot.create_context_plot_zoomed(180, 0)
except ImportError:
pass
| """Tests K2fov.plot"""
from .. import plot
"""
def test_basics():
# Make sure this runs without exception.
try:
import matplotlib
plot.create_context_plot(180, 0)
plot.create_context_plot_zoomed(180, 0)
except ImportError:
pass
"""
| Simplify plot test for now | Simplify plot test for now
| Python | mit | KeplerGO/K2fov,mrtommyb/K2fov | """Tests K2fov.plot"""
from .. import plot
-
+ """
def test_basics():
- """Make sure this runs without exception."""
+ # Make sure this runs without exception.
try:
import matplotlib
plot.create_context_plot(180, 0)
plot.create_context_plot_zoomed(180, 0)
e... | Simplify plot test for now | ## Code Before:
"""Tests K2fov.plot"""
from .. import plot
def test_basics():
"""Make sure this runs without exception."""
try:
import matplotlib
plot.create_context_plot(180, 0)
plot.create_context_plot_zoomed(180, 0)
except ImportError:
pass
## Instruction:
Simplify plo... |
3427b2583c38ed7ec5239c36faa82536f3f95a3b | automata/pda/stack.py | automata/pda/stack.py | """Classes and methods for working with PDA stacks."""
class PDAStack(object):
"""A PDA stack."""
def __init__(self, stack, **kwargs):
"""Initialize the new PDA stack."""
if isinstance(stack, PDAStack):
self._init_from_stack_obj(stack)
else:
self.stack = list(s... | """Classes and methods for working with PDA stacks."""
class PDAStack(object):
"""A PDA stack."""
def __init__(self, stack):
"""Initialize the new PDA stack."""
self.stack = list(stack)
def top(self):
"""Return the symbol at the top of the stack."""
if self.stack:
... | Remove copy constructor for PDAStack | Remove copy constructor for PDAStack
The copy() method is already sufficient.
| Python | mit | caleb531/automata | """Classes and methods for working with PDA stacks."""
class PDAStack(object):
"""A PDA stack."""
- def __init__(self, stack, **kwargs):
+ def __init__(self, stack):
"""Initialize the new PDA stack."""
- if isinstance(stack, PDAStack):
- self._init_from_stack_obj... | Remove copy constructor for PDAStack | ## Code Before:
"""Classes and methods for working with PDA stacks."""
class PDAStack(object):
"""A PDA stack."""
def __init__(self, stack, **kwargs):
"""Initialize the new PDA stack."""
if isinstance(stack, PDAStack):
self._init_from_stack_obj(stack)
else:
sel... |
3990e3aa64cff288def07ee36e24026cc15282c0 | taiga/projects/issues/serializers.py | taiga/projects/issues/serializers.py |
from rest_framework import serializers
from taiga.base.serializers import PickleField, NeighborsSerializerMixin
from . import models
class IssueSerializer(serializers.ModelSerializer):
tags = PickleField(required=False)
comment = serializers.SerializerMethodField("get_comment")
is_closed = serializers.... |
from rest_framework import serializers
from taiga.base.serializers import PickleField, NeighborsSerializerMixin
from . import models
class IssueSerializer(serializers.ModelSerializer):
tags = PickleField(required=False)
is_closed = serializers.Field(source="is_closed")
class Meta:
model = mode... | Remove unnecessary field from IssueSerializer | Remove unnecessary field from IssueSerializer
| Python | agpl-3.0 | forging2012/taiga-back,EvgeneOskin/taiga-back,xdevelsistemas/taiga-back-community,seanchen/taiga-back,bdang2012/taiga-back-casting,Rademade/taiga-back,crr0004/taiga-back,dayatz/taiga-back,rajiteh/taiga-back,dycodedev/taiga-back,crr0004/taiga-back,obimod/taiga-back,Zaneh-/bearded-tribble-back,seanchen/taiga-back,gauravj... |
from rest_framework import serializers
from taiga.base.serializers import PickleField, NeighborsSerializerMixin
from . import models
class IssueSerializer(serializers.ModelSerializer):
tags = PickleField(required=False)
- comment = serializers.SerializerMethodField("get_comment")
... | Remove unnecessary field from IssueSerializer | ## Code Before:
from rest_framework import serializers
from taiga.base.serializers import PickleField, NeighborsSerializerMixin
from . import models
class IssueSerializer(serializers.ModelSerializer):
tags = PickleField(required=False)
comment = serializers.SerializerMethodField("get_comment")
is_close... |
85e853a63d7fed79b931b337bb9e6678077cf8d5 | tests/integration/ssh/test_grains.py | tests/integration/ssh/test_grains.py | from __future__ import absolute_import
# Import Salt Testing Libs
from tests.support.case import SSHCase
from tests.support.unit import skipIf
# Import Salt Libs
import salt.utils
@skipIf(salt.utils.is_windows(), 'salt-ssh not available on Windows')
class SSHGrainsTest(SSHCase):
'''
testing grains with salt... | from __future__ import absolute_import
# Import Salt Testing Libs
from tests.support.case import SSHCase
from tests.support.unit import skipIf
# Import Salt Libs
import salt.utils
@skipIf(salt.utils.is_windows(), 'salt-ssh not available on Windows')
class SSHGrainsTest(SSHCase):
'''
testing grains with salt... | Add darwin value for ssh grain items tests on MacOSX | Add darwin value for ssh grain items tests on MacOSX
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | from __future__ import absolute_import
# Import Salt Testing Libs
from tests.support.case import SSHCase
from tests.support.unit import skipIf
# Import Salt Libs
import salt.utils
@skipIf(salt.utils.is_windows(), 'salt-ssh not available on Windows')
class SSHGrainsTest(SSHCase):
'''
... | Add darwin value for ssh grain items tests on MacOSX | ## Code Before:
from __future__ import absolute_import
# Import Salt Testing Libs
from tests.support.case import SSHCase
from tests.support.unit import skipIf
# Import Salt Libs
import salt.utils
@skipIf(salt.utils.is_windows(), 'salt-ssh not available on Windows')
class SSHGrainsTest(SSHCase):
'''
testing ... |
79bbc95abd2c1b41bcbd19d9ce1ffa330bd76b7a | source/views.py | source/views.py | from multiprocessing.pool import ThreadPool
from django.shortcuts import render
from .forms import SearchForm
from source import view_models
def index(request):
if request.method == 'GET':
form = SearchForm(request.GET)
if form.is_valid():
title = request.GET.__getitem__('movie_title'... | from multiprocessing.pool import ThreadPool
from django.shortcuts import render
from .forms import SearchForm
from source import view_models
def index(request):
if request.method == 'GET':
form = SearchForm(request.GET)
if form.is_valid():
title = request.GET.__getitem__('movie_title'... | Join threads or else the number of running threads increments by 5 at each request and will never stop until main process is killed | Join threads or else the number of running threads increments by 5 at each request and will never stop until main process is killed
| Python | mit | jeremyrea/caterblu,jeremyrea/caterblu,jeremyrea/caterblu,jeremyrea/caterblu | from multiprocessing.pool import ThreadPool
from django.shortcuts import render
from .forms import SearchForm
from source import view_models
def index(request):
if request.method == 'GET':
form = SearchForm(request.GET)
if form.is_valid():
title = request.GET._... | Join threads or else the number of running threads increments by 5 at each request and will never stop until main process is killed | ## Code Before:
from multiprocessing.pool import ThreadPool
from django.shortcuts import render
from .forms import SearchForm
from source import view_models
def index(request):
if request.method == 'GET':
form = SearchForm(request.GET)
if form.is_valid():
title = request.GET.__getitem... |
93926a9986ab4ba7704cd564d0052b6e60ff38cb | casepro/pods/base.py | casepro/pods/base.py | import json
from confmodel import fields, Config as ConfmodelConfig
from django.apps import AppConfig
class PodConfig(ConfmodelConfig):
'''
This is the config that all pods should use as the base for their own
config.
'''
index = fields.ConfigInt(
"A unique identifier for the specific inst... | import json
from confmodel import fields, Config as ConfmodelConfig
from django.apps import AppConfig
class PodConfig(ConfmodelConfig):
'''
This is the config that all pods should use as the base for their own
config.
'''
index = fields.ConfigInt(
"A unique identifier for the specific inst... | Add the class-level vars we need for pod angular components to PodPlugin | Add the class-level vars we need for pod angular components to PodPlugin
| Python | bsd-3-clause | rapidpro/casepro,praekelt/casepro,xkmato/casepro,rapidpro/casepro,praekelt/casepro,xkmato/casepro,praekelt/casepro,rapidpro/casepro | import json
from confmodel import fields, Config as ConfmodelConfig
from django.apps import AppConfig
class PodConfig(ConfmodelConfig):
'''
This is the config that all pods should use as the base for their own
config.
'''
index = fields.ConfigInt(
"A unique identifi... | Add the class-level vars we need for pod angular components to PodPlugin | ## Code Before:
import json
from confmodel import fields, Config as ConfmodelConfig
from django.apps import AppConfig
class PodConfig(ConfmodelConfig):
'''
This is the config that all pods should use as the base for their own
config.
'''
index = fields.ConfigInt(
"A unique identifier for t... |
aceeac7e9dd2735add937bc7141cfdb29b6201c7 | pywatson/watson.py | pywatson/watson.py | from pywatson.answer.answer import Answer
from pywatson.question.question import Question
import requests
class Watson:
"""The Watson API adapter class"""
def __init__(self, url, username, password):
self.url = url
self.username = username
self.password = password
def ask_questio... | from pywatson.answer.answer import Answer
from pywatson.question.question import Question
import requests
class Watson(object):
"""The Watson API adapter class"""
def __init__(self, url, username, password):
self.url = url
self.username = username
self.password = password
def ask... | Use __dict__ instead of to_dict() | Use __dict__ instead of to_dict()
| Python | mit | sherlocke/pywatson | from pywatson.answer.answer import Answer
from pywatson.question.question import Question
import requests
- class Watson:
+ class Watson(object):
"""The Watson API adapter class"""
def __init__(self, url, username, password):
self.url = url
self.username = username
... | Use __dict__ instead of to_dict() | ## Code Before:
from pywatson.answer.answer import Answer
from pywatson.question.question import Question
import requests
class Watson:
"""The Watson API adapter class"""
def __init__(self, url, username, password):
self.url = url
self.username = username
self.password = password
... |
d7c9bcbf25a6b45a462216f426608474aa66ceb0 | mysite/missions/models.py | mysite/missions/models.py | from django.db import models
class MissionStep(models.Model):
pass
class MissionStepCompletion(models.Model):
person = models.ForeignKey('profile.Person')
step = models.ForeignKey('MissionStep')
class Meta:
unique_together = ('person', 'step')
| from django.db import models
class Step(models.Model):
pass
class StepCompletion(models.Model):
person = models.ForeignKey('profile.Person')
step = models.ForeignKey('Step')
class Meta:
unique_together = ('person', 'step')
| Remove the redundant "Mission" prefix from the mission model names. | Remove the redundant "Mission" prefix from the mission model names.
| Python | agpl-3.0 | heeraj123/oh-mainline,vipul-sharma20/oh-mainline,sudheesh001/oh-mainline,willingc/oh-mainline,jledbetter/openhatch,jledbetter/openhatch,moijes12/oh-mainline,openhatch/oh-mainline,mzdaniel/oh-mainline,openhatch/oh-mainline,jledbetter/openhatch,waseem18/oh-mainline,waseem18/oh-mainline,SnappleCap/oh-mainline,Changaco/oh-... | from django.db import models
- class MissionStep(models.Model):
+ class Step(models.Model):
pass
- class MissionStepCompletion(models.Model):
+ class StepCompletion(models.Model):
person = models.ForeignKey('profile.Person')
- step = models.ForeignKey('MissionStep')
+ step = models.ForeignKe... | Remove the redundant "Mission" prefix from the mission model names. | ## Code Before:
from django.db import models
class MissionStep(models.Model):
pass
class MissionStepCompletion(models.Model):
person = models.ForeignKey('profile.Person')
step = models.ForeignKey('MissionStep')
class Meta:
unique_together = ('person', 'step')
## Instruction:
Remove the redun... |
a2e3f0590d5bd25993be5291c058c722896aa773 | tests/test_utils.py | tests/test_utils.py | import sys
import unittest
import numpy as np
import torch
sys.path.append("../metal")
from metal.utils import (
rargmax,
hard_to_soft,
recursive_merge_dicts
)
class UtilsTest(unittest.TestCase):
def test_rargmax(self):
x = np.array([2, 1, 2])
self.assertEqual(sorted(list(set(rargmax(... | import sys
import unittest
import numpy as np
import torch
sys.path.append("../metal")
from metal.utils import (
rargmax,
hard_to_soft,
recursive_merge_dicts
)
class UtilsTest(unittest.TestCase):
def test_rargmax(self):
x = np.array([2, 1, 2])
np.random.seed(1)
self.assertEqua... | Fix broken utils test with seed | Fix broken utils test with seed
| Python | apache-2.0 | HazyResearch/metal,HazyResearch/metal | import sys
import unittest
import numpy as np
import torch
sys.path.append("../metal")
from metal.utils import (
rargmax,
hard_to_soft,
recursive_merge_dicts
)
class UtilsTest(unittest.TestCase):
def test_rargmax(self):
x = np.array([2, 1, 2])
+ np.rand... | Fix broken utils test with seed | ## Code Before:
import sys
import unittest
import numpy as np
import torch
sys.path.append("../metal")
from metal.utils import (
rargmax,
hard_to_soft,
recursive_merge_dicts
)
class UtilsTest(unittest.TestCase):
def test_rargmax(self):
x = np.array([2, 1, 2])
self.assertEqual(sorted(l... |
df5e6bdd03ad666afdd9b61745eec95afc08e9cb | tests/test_views.py | tests/test_views.py | """ Tests for the main server file. """
from unittest import TestCase
from unittest.mock import patch
from app import views
class ViewsTestCase(TestCase):
""" Our main server testcase. """
def test_ping(self):
self.assertEqual(views.ping(None, None), 'pong')
@patch('app.views.notify_recipient')... | """ Tests for the main server file. """
from unittest import TestCase
from unittest.mock import patch
from app import views
class ViewsTestCase(TestCase):
""" Our main server testcase. """
def test_ping(self):
self.assertEqual(views.ping(None, None), 'pong')
@patch('app.views.notify_recipient')... | Fix last code quality issues | Fix last code quality issues
| Python | mit | DobaTech/github-review-slack-notifier | """ Tests for the main server file. """
from unittest import TestCase
from unittest.mock import patch
from app import views
class ViewsTestCase(TestCase):
""" Our main server testcase. """
def test_ping(self):
self.assertEqual(views.ping(None, None), 'pong')
@patch('... | Fix last code quality issues | ## Code Before:
""" Tests for the main server file. """
from unittest import TestCase
from unittest.mock import patch
from app import views
class ViewsTestCase(TestCase):
""" Our main server testcase. """
def test_ping(self):
self.assertEqual(views.ping(None, None), 'pong')
@patch('app.views.no... |
39091c3390d121d48097d64526f40d0a09702673 | src/zeit/today/tests.py | src/zeit/today/tests.py | import pkg_resources
import zeit.cms.testing
product_config = """\
<product-config zeit.today>
today-xml-url file://{base}/today.xml
</product-config>
""".format(base=pkg_resources.resource_filename(__name__, '.'))
TodayLayer = zeit.cms.testing.ZCMLLayer('ftesting.zcml', product_config=(
product_config +
... | import pkg_resources
import zeit.cms.testing
product_config = """\
<product-config zeit.today>
today-xml-url file://{base}/today.xml
</product-config>
""".format(base=pkg_resources.resource_filename(__name__, '.'))
CONFIG_LAYER = zeit.cms.testing.ProductConfigLayer(product_config, bases=(
zeit.cms.testing.CO... | Update to new testlayer API | ZON-5241: Update to new testlayer API
| Python | bsd-3-clause | ZeitOnline/zeit.today | import pkg_resources
import zeit.cms.testing
product_config = """\
<product-config zeit.today>
today-xml-url file://{base}/today.xml
</product-config>
""".format(base=pkg_resources.resource_filename(__name__, '.'))
- TodayLayer = zeit.cms.testing.ZCMLLayer('ftesting.zcml', product_config=(
- ... | Update to new testlayer API | ## Code Before:
import pkg_resources
import zeit.cms.testing
product_config = """\
<product-config zeit.today>
today-xml-url file://{base}/today.xml
</product-config>
""".format(base=pkg_resources.resource_filename(__name__, '.'))
TodayLayer = zeit.cms.testing.ZCMLLayer('ftesting.zcml', product_config=(
prod... |
81f7b2bdd0e916a001b954ce9bac24ebe4600150 | roboime/options.py | roboime/options.py |
#Position Log filename. Use None to disable.
position_log_filename = "math/pos_log.txt"
#position_log_filename = None
#Position Log with Noise filename. Use None to disable.
position_log_noise_filename = "math/pos_log_noise.txt"
#position_log_filename = None
#Command and Update Log filename. Use None to disable.
cmd... |
#Position Log filename. Use None to disable.
position_log_filename = "math/pos_log.txt"
#position_log_filename = None
#Command and Update Log filename. Use None to disable.
cmdupd_filename = "math/commands.txt"
#cmdupd_filename = None
#Gaussian noise addition variances
noise_var_x = 3.E-5
noise_var_y = 3.E-5
noise_v... | Add Q (generic) and R (3 values) to get more precise Kalman results | Add Q (generic) and R (3 values) to get more precise Kalman results
| Python | agpl-3.0 | roboime/pyroboime |
#Position Log filename. Use None to disable.
position_log_filename = "math/pos_log.txt"
- #position_log_filename = None
-
- #Position Log with Noise filename. Use None to disable.
- position_log_noise_filename = "math/pos_log_noise.txt"
#position_log_filename = None
#Command and Update Log filename. Use ... | Add Q (generic) and R (3 values) to get more precise Kalman results | ## Code Before:
#Position Log filename. Use None to disable.
position_log_filename = "math/pos_log.txt"
#position_log_filename = None
#Position Log with Noise filename. Use None to disable.
position_log_noise_filename = "math/pos_log_noise.txt"
#position_log_filename = None
#Command and Update Log filename. Use None... |
d6ce218b0da869f6b4319751c1fe59ef02fba6b6 | kremlin/imgutils.py | kremlin/imgutils.py | import os
from PIL import Image
def mkthumb(fp, h=128, w=128):
"""docstring for mkthumb"""
size = (h, w)
f, ext = os.path.splitext(fp)
im = Image.open(fp)
im.thumbnail(size, Image.ANTIALIAS)
im.save(f + ".thumbnail" + ext)
| import os
from PIL import Image
def mkthumb(fp, h=128, w=128):
"""docstring for mkthumb"""
size = (h, w)
f, ext = os.path.splitext(fp)
im = Image.open(fp)
im.thumbnail(size, Image.ANTIALIAS)
im.save('.thumbnail'.join([f, ext]))
| Use better string concatenation in mkthumb() | Use better string concatenation in mkthumb()
| Python | bsd-2-clause | glasnost/kremlin,glasnost/kremlin,glasnost/kremlin | import os
from PIL import Image
def mkthumb(fp, h=128, w=128):
"""docstring for mkthumb"""
size = (h, w)
f, ext = os.path.splitext(fp)
im = Image.open(fp)
im.thumbnail(size, Image.ANTIALIAS)
- im.save(f + ".thumbnail" + ext)
+ im.save('.thumbnail'.join([f, ext]))
... | Use better string concatenation in mkthumb() | ## Code Before:
import os
from PIL import Image
def mkthumb(fp, h=128, w=128):
"""docstring for mkthumb"""
size = (h, w)
f, ext = os.path.splitext(fp)
im = Image.open(fp)
im.thumbnail(size, Image.ANTIALIAS)
im.save(f + ".thumbnail" + ext)
## Instruction:
Use better string concatenation in m... |
09f65ff2a21cd00355193bcdee22a2289ead2d24 | tests/test_arguments.py | tests/test_arguments.py | from __future__ import print_function
import unittest
import wrapt
class TestArguments(unittest.TestCase):
def test_getcallargs(self):
def function(a, b=2, c=3, d=4, e=5, *args, **kwargs):
pass
expected = {'a': 10, 'c': 3, 'b': 20, 'e': 5, 'd': 40,
'args': (), 'kwarg... | from __future__ import print_function
import unittest
import wrapt
class TestArguments(unittest.TestCase):
def test_getcallargs(self):
def function(a, b=2, c=3, d=4, e=5, *args, **kwargs):
pass
expected = {'a': 10, 'c': 3, 'b': 20, 'e': 5, 'd': 40,
'args': (), 'kwarg... | Add test for unexpected unicode kwargs. | Add test for unexpected unicode kwargs.
| Python | bsd-2-clause | GrahamDumpleton/wrapt,GrahamDumpleton/wrapt | from __future__ import print_function
import unittest
import wrapt
class TestArguments(unittest.TestCase):
def test_getcallargs(self):
def function(a, b=2, c=3, d=4, e=5, *args, **kwargs):
pass
expected = {'a': 10, 'c': 3, 'b': 20, 'e': 5, 'd': 40,
... | Add test for unexpected unicode kwargs. | ## Code Before:
from __future__ import print_function
import unittest
import wrapt
class TestArguments(unittest.TestCase):
def test_getcallargs(self):
def function(a, b=2, c=3, d=4, e=5, *args, **kwargs):
pass
expected = {'a': 10, 'c': 3, 'b': 20, 'e': 5, 'd': 40,
'a... |
397eb3ee376acec005a8d7b5a4c2b2e0193a938d | tests/test_bookmarks.py | tests/test_bookmarks.py | import bookmarks
import unittest
class FlaskrTestCase(unittest.TestCase):
def setUp(self):
self.app = bookmarks.app.test_client()
# with bookmarks.app.app_context():
bookmarks.database.init_db()
def tearDown(self):
# with bookmarks.app.app_context():
bookmarks.database... | import bookmarks
import unittest
class FlaskrTestCase(unittest.TestCase):
def setUp(self):
self.app = bookmarks.app.test_client()
# with bookmarks.app.app_context():
bookmarks.database.init_db()
def tearDown(self):
# with bookmarks.app.app_context():
bookmarks.database... | Add param for confirm field on register test func | Add param for confirm field on register test func
| Python | apache-2.0 | byanofsky/bookmarks,byanofsky/bookmarks,byanofsky/bookmarks | import bookmarks
import unittest
class FlaskrTestCase(unittest.TestCase):
def setUp(self):
self.app = bookmarks.app.test_client()
# with bookmarks.app.app_context():
bookmarks.database.init_db()
def tearDown(self):
# with bookmarks.app.app_context():
... | Add param for confirm field on register test func | ## Code Before:
import bookmarks
import unittest
class FlaskrTestCase(unittest.TestCase):
def setUp(self):
self.app = bookmarks.app.test_client()
# with bookmarks.app.app_context():
bookmarks.database.init_db()
def tearDown(self):
# with bookmarks.app.app_context():
bo... |
95fbbe9bac94e171424cb8ee23a675a70607fb62 | tests/test_constants.py | tests/test_constants.py | from __future__ import absolute_import, unicode_literals
import unittest
from draftjs_exporter.constants import Enum, BLOCK_TYPES, ENTITY_TYPES, INLINE_STYLES
class EnumConstants(unittest.TestCase):
def test_enum_returns_the_key_if_valid(self):
foo_value = 'foo'
e = Enum(foo_value)
self... | from __future__ import absolute_import, unicode_literals
import unittest
from draftjs_exporter.constants import BLOCK_TYPES, ENTITY_TYPES, INLINE_STYLES, Enum
class EnumConstants(unittest.TestCase):
def test_enum_returns_the_key_if_valid(self):
foo_value = 'foo'
e = Enum(foo_value)
self... | Fix import order picked up by isort | Fix import order picked up by isort
| Python | mit | springload/draftjs_exporter,springload/draftjs_exporter,springload/draftjs_exporter | from __future__ import absolute_import, unicode_literals
import unittest
- from draftjs_exporter.constants import Enum, BLOCK_TYPES, ENTITY_TYPES, INLINE_STYLES
+ from draftjs_exporter.constants import BLOCK_TYPES, ENTITY_TYPES, INLINE_STYLES, Enum
class EnumConstants(unittest.TestCase):
def tes... | Fix import order picked up by isort | ## Code Before:
from __future__ import absolute_import, unicode_literals
import unittest
from draftjs_exporter.constants import Enum, BLOCK_TYPES, ENTITY_TYPES, INLINE_STYLES
class EnumConstants(unittest.TestCase):
def test_enum_returns_the_key_if_valid(self):
foo_value = 'foo'
e = Enum(foo_valu... |
aa6a74abc382bb6be86fa4a91132a9be51f365a5 | tests/test_data_checksums.py | tests/test_data_checksums.py | """ test data_checksums"""
from nose.tools import assert_equal
def test_data_checksums():
from pyne.data import data_checksums
assert_equal(len(data_checksums), 6)
assert_equal(data_checksums['/neutron/simple_xs'], '3d6e086977783dcdf07e5c6b0c2416be') | """ test data_checksums and hashing functions"""
import os
from nose.tools import assert_equal, assert_true
import pyne
# These tests require nuc_data
if not os.path.isfile(pyne.nuc_data):
raise RuntimeError("Tests require nuc_data.h5. Please run nuc_data_make.")
def test_data_checksums():
from pyne.data i... | Add test of internal hashes and guarded pyne.nuc_data use | Add test of internal hashes and guarded pyne.nuc_data use
| Python | bsd-3-clause | pyne/simplesim | - """ test data_checksums"""
- from nose.tools import assert_equal
+ """ test data_checksums and hashing functions"""
+ import os
+ from nose.tools import assert_equal, assert_true
+
+ import pyne
+
+ # These tests require nuc_data
+ if not os.path.isfile(pyne.nuc_data):
+ raise RuntimeError("Tests require nuc... | Add test of internal hashes and guarded pyne.nuc_data use | ## Code Before:
""" test data_checksums"""
from nose.tools import assert_equal
def test_data_checksums():
from pyne.data import data_checksums
assert_equal(len(data_checksums), 6)
assert_equal(data_checksums['/neutron/simple_xs'], '3d6e086977783dcdf07e5c6b0c2416be')
## Instruction:
Add test of internal ha... |
698732f1276f92a94143b0531906caf37e885c28 | trello_notifications.py | trello_notifications.py | try:
from trello import TrelloCommand
from output import Output
except ImportError:
from .trello import TrelloCommand
from .output import Output
class TrelloNotificationsCommand(TrelloCommand):
def work(self, connection):
self.options = [
{ 'name': "Unread", 'action': self.show_... | try:
from trello import TrelloCommand
from output import Output
except ImportError:
from .trello import TrelloCommand
from .output import Output
class TrelloNotificationsCommand(TrelloCommand):
def work(self, connection):
self.options = [
{ 'name': "Unread", 'action': self.show_... | Store connection and missing self | Store connection and missing self
| Python | mit | NicoSantangelo/sublime-text-trello | try:
from trello import TrelloCommand
from output import Output
except ImportError:
from .trello import TrelloCommand
from .output import Output
class TrelloNotificationsCommand(TrelloCommand):
def work(self, connection):
self.options = [
{ 'name': "Unread"... | Store connection and missing self | ## Code Before:
try:
from trello import TrelloCommand
from output import Output
except ImportError:
from .trello import TrelloCommand
from .output import Output
class TrelloNotificationsCommand(TrelloCommand):
def work(self, connection):
self.options = [
{ 'name': "Unread", 'act... |
9796e60975474006940af723a6cb8b16bc632ae0 | tz_app/context_processors.py | tz_app/context_processors.py | from django.conf import settings
from django.utils import timezone
try:
import pytz
except ImportError:
pytz = None
def timezones(request):
alt_timezone = request.session.get('alt_timezone', pytz.utc)
return {
'pytz': pytz,
'default_timezone_name': settings.TIME_ZONE,
'timezone... | from django.conf import settings
from django.utils import timezone
try:
import pytz
except ImportError:
pytz = None
def timezones(request):
alt_timezone = request.session.get('alt_timezone', (pytz or timezone).utc)
return {
'pytz': pytz,
'default_timezone_name': settings.TIME_ZONE,
... | Fix a bug when pytz isn't installed. | Fix a bug when pytz isn't installed.
| Python | bsd-3-clause | aaugustin/django-tz-demo | from django.conf import settings
from django.utils import timezone
try:
import pytz
except ImportError:
pytz = None
def timezones(request):
- alt_timezone = request.session.get('alt_timezone', pytz.utc)
+ alt_timezone = request.session.get('alt_timezone', (pytz or timezone).utc)
... | Fix a bug when pytz isn't installed. | ## Code Before:
from django.conf import settings
from django.utils import timezone
try:
import pytz
except ImportError:
pytz = None
def timezones(request):
alt_timezone = request.session.get('alt_timezone', pytz.utc)
return {
'pytz': pytz,
'default_timezone_name': settings.TIME_ZONE,
... |
c8b86afc53af25c845c8303111a6e7b17d8c26b4 | ciscripts/check/psqcppconan/check.py | ciscripts/check/psqcppconan/check.py | """Run tests and static analysis checks on a polysquare conan c++ project."""
import argparse
import os
def run(cont, util, shell, argv=None):
"""Run checks on this conan project."""
parser = argparse.ArgumentParser(description="""Run conan checks""")
parser.add_argument("--run-test-binaries",
... | """Run tests and static analysis checks on a polysquare conan c++ project."""
import argparse
import os
def run(cont, util, shell, argv=None):
"""Run checks on this conan project."""
parser = argparse.ArgumentParser(description="""Run conan checks""")
parser.add_argument("--run-test-binaries",
... | Allow the use of .exe | psqcppconan: Allow the use of .exe
| Python | mit | polysquare/polysquare-ci-scripts,polysquare/polysquare-ci-scripts | """Run tests and static analysis checks on a polysquare conan c++ project."""
import argparse
import os
def run(cont, util, shell, argv=None):
"""Run checks on this conan project."""
parser = argparse.ArgumentParser(description="""Run conan checks""")
parser.add_argument("--run-tes... | Allow the use of .exe | ## Code Before:
"""Run tests and static analysis checks on a polysquare conan c++ project."""
import argparse
import os
def run(cont, util, shell, argv=None):
"""Run checks on this conan project."""
parser = argparse.ArgumentParser(description="""Run conan checks""")
parser.add_argument("--run-test-bina... |
e3cb7ad226e3c26cbfa6f9f322ebdb4fde7e7d60 | coop_cms/apps/coop_bootstrap/templatetags/coop_bs.py | coop_cms/apps/coop_bootstrap/templatetags/coop_bs.py |
from __future__ import unicode_literals
from django import template
from coop_cms.templatetags.coop_utils import is_checkbox as _is_checkbox
from coop_cms.templatetags.coop_navigation import NavigationAsNestedUlNode
register = template.Library()
# Just for compatibility
@register.filter(name='is_checkbox')
def is... |
from __future__ import unicode_literals
from django import template
from coop_cms.templatetags.coop_utils import is_checkbox as _is_checkbox
from coop_cms.templatetags.coop_navigation import NavigationAsNestedUlNode, extract_kwargs
register = template.Library()
# Just for compatibility
@register.filter(name='is_c... | Fix "navigation_bootstrap" templatetag : arguments were ignored | Fix "navigation_bootstrap" templatetag : arguments were ignored
| Python | bsd-3-clause | ljean/coop_cms,ljean/coop_cms,ljean/coop_cms |
from __future__ import unicode_literals
from django import template
from coop_cms.templatetags.coop_utils import is_checkbox as _is_checkbox
- from coop_cms.templatetags.coop_navigation import NavigationAsNestedUlNode
+ from coop_cms.templatetags.coop_navigation import NavigationAsNestedUlNode, extract_k... | Fix "navigation_bootstrap" templatetag : arguments were ignored | ## Code Before:
from __future__ import unicode_literals
from django import template
from coop_cms.templatetags.coop_utils import is_checkbox as _is_checkbox
from coop_cms.templatetags.coop_navigation import NavigationAsNestedUlNode
register = template.Library()
# Just for compatibility
@register.filter(name='is_c... |
8a4b576d6df4ef1f174c8698ff9a86dbf2f5bd4a | workshops/models.py | workshops/models.py | from django.db import models
from django.db.models.deletion import PROTECT
from django_extensions.db.fields import AutoSlugField
class Workshop(models.Model):
event = models.ForeignKey('events.Event', PROTECT, related_name='workshops')
applicant = models.ForeignKey('cfp.Applicant', related_name='workshops')
... | from django.db import models
from django.db.models.deletion import PROTECT
from django_extensions.db.fields import AutoSlugField
class Workshop(models.Model):
event = models.ForeignKey('events.Event', PROTECT, related_name='workshops')
applicant = models.ForeignKey('cfp.Applicant', related_name='workshops')
... | Check price exists before using it | Check price exists before using it
| Python | bsd-3-clause | WebCampZg/conference-web,WebCampZg/conference-web,WebCampZg/conference-web | from django.db import models
from django.db.models.deletion import PROTECT
from django_extensions.db.fields import AutoSlugField
class Workshop(models.Model):
event = models.ForeignKey('events.Event', PROTECT, related_name='workshops')
applicant = models.ForeignKey('cfp.Applicant', related_nam... | Check price exists before using it | ## Code Before:
from django.db import models
from django.db.models.deletion import PROTECT
from django_extensions.db.fields import AutoSlugField
class Workshop(models.Model):
event = models.ForeignKey('events.Event', PROTECT, related_name='workshops')
applicant = models.ForeignKey('cfp.Applicant', related_nam... |
ea3660bcc1a9f7be619def8e26dd7b0ab4a873cf | estmator_project/est_client/forms.py | estmator_project/est_client/forms.py | from django.forms import ModelForm, Select, TextInput
from .models import Client, Company
class ClientCreateForm(ModelForm):
class Meta:
model = Client
fields = [
'company',
'first_name',
'last_name',
'title',
'cell',
'desk',
... | from django.forms import ModelForm, Select, TextInput
from .models import Client, Company
class ClientCreateForm(ModelForm):
class Meta:
model = Client
fields = [
'company',
'first_name',
'last_name',
'title',
'cell',
'desk',
... | Make fields required on new client and company | Make fields required on new client and company
| Python | mit | Estmator/EstmatorApp,Estmator/EstmatorApp,Estmator/EstmatorApp | from django.forms import ModelForm, Select, TextInput
from .models import Client, Company
class ClientCreateForm(ModelForm):
class Meta:
model = Client
fields = [
'company',
'first_name',
'last_name',
'title',
'c... | Make fields required on new client and company | ## Code Before:
from django.forms import ModelForm, Select, TextInput
from .models import Client, Company
class ClientCreateForm(ModelForm):
class Meta:
model = Client
fields = [
'company',
'first_name',
'last_name',
'title',
'cell',
... |
b7c52258d39e5c0ee8fba2be87e8e671e0c583c3 | xclib/postfix_io.py | xclib/postfix_io.py | import sys
import re
import logging
# Message formats described in `../doc/Protocol.md`
class postfix_io:
@classmethod
def read_request(cls, infd, outfd):
# "for line in sys.stdin:" would be more concise but adds unwanted buffering
while True:
line = infd.readline()
if ... | import sys
import re
import logging
# Message formats described in `../doc/Protocol.md`
class postfix_io:
@classmethod
def read_request(cls, infd, outfd):
# "for line in sys.stdin:" would be more concise but adds unwanted buffering
while True:
line = infd.readline()
if ... | Add quit command to postfix | Add quit command to postfix
| Python | mit | jsxc/xmpp-cloud-auth,jsxc/xmpp-cloud-auth,jsxc/xmpp-cloud-auth,jsxc/xmpp-cloud-auth | import sys
import re
import logging
# Message formats described in `../doc/Protocol.md`
class postfix_io:
@classmethod
def read_request(cls, infd, outfd):
# "for line in sys.stdin:" would be more concise but adds unwanted buffering
while True:
line = infd.re... | Add quit command to postfix | ## Code Before:
import sys
import re
import logging
# Message formats described in `../doc/Protocol.md`
class postfix_io:
@classmethod
def read_request(cls, infd, outfd):
# "for line in sys.stdin:" would be more concise but adds unwanted buffering
while True:
line = infd.readline()... |
3be9ef4c2ec4c2b10503633c55fd1634f4d5debb | comics/search/indexes.py | comics/search/indexes.py | from django.template.loader import get_template
from django.template import Context
from haystack import indexes
from haystack import site
from comics.core.models import Image
class ImageIndex(indexes.SearchIndex):
document = indexes.CharField(document=True, use_template=True)
rendered = indexes.CharField(in... | from django.template.loader import get_template
from django.template import Context
from haystack import indexes
from haystack import site
from comics.core.models import Image
class ImageIndex(indexes.SearchIndex):
document = indexes.CharField(document=True, use_template=True)
rendered = indexes.CharField(in... | Add get_updated_field to search index | Add get_updated_field to search index
| Python | agpl-3.0 | jodal/comics,jodal/comics,klette/comics,datagutten/comics,jodal/comics,datagutten/comics,jodal/comics,datagutten/comics,klette/comics,klette/comics,datagutten/comics | from django.template.loader import get_template
from django.template import Context
from haystack import indexes
from haystack import site
from comics.core.models import Image
class ImageIndex(indexes.SearchIndex):
document = indexes.CharField(document=True, use_template=True)
rendered ... | Add get_updated_field to search index | ## Code Before:
from django.template.loader import get_template
from django.template import Context
from haystack import indexes
from haystack import site
from comics.core.models import Image
class ImageIndex(indexes.SearchIndex):
document = indexes.CharField(document=True, use_template=True)
rendered = inde... |
b0701205f0b96645d3643bab5188f349cd604603 | binaries/streamer_binaries/__init__.py | binaries/streamer_binaries/__init__.py | import os
__version__ = '0.5.0'
# Module level variables.
ffmpeg = ''
"""The path to the installed FFmpeg binary."""
ffprobe = ''
"""The path to the installed FFprobe binary."""
packager = ''
"""The path to the installed Shaka Packager binary."""
# Get the directory path where this __init__.py file resides.
_dir_p... | import os
import platform
__version__ = '0.5.0'
# Get the directory path where this __init__.py file resides.
_dir_path = os.path.abspath(os.path.dirname(__file__))
# Compute the part of the file name that indicates the OS.
_os = {
'Linux': 'linux',
'Windows': 'win',
'Darwin': 'osx',
}[platform.system()]
# C... | Fix usage of local streamer_binaries module | build: Fix usage of local streamer_binaries module
The old code would search the directory for the binary to use. This
worked fine if the package were installed, but when adding the module
path to PYTHONPATH, this technique would fail because the folder would
have executables for all architetures.
Now we will comput... | Python | apache-2.0 | shaka-project/shaka-streamer,shaka-project/shaka-streamer | import os
+ import platform
__version__ = '0.5.0'
-
-
- # Module level variables.
- ffmpeg = ''
- """The path to the installed FFmpeg binary."""
- ffprobe = ''
- """The path to the installed FFprobe binary."""
- packager = ''
- """The path to the installed Shaka Packager binary."""
# Get the directory ... | Fix usage of local streamer_binaries module | ## Code Before:
import os
__version__ = '0.5.0'
# Module level variables.
ffmpeg = ''
"""The path to the installed FFmpeg binary."""
ffprobe = ''
"""The path to the installed FFprobe binary."""
packager = ''
"""The path to the installed Shaka Packager binary."""
# Get the directory path where this __init__.py file... |
d57670995709ae60e9cbed575b1ac9e63cba113a | src/env.py | src/env.py | class Environment:
def __init__(self, par=None, bnd=None):
if bnd:
self.binds = bnd
else:
self.binds = {}
self.parent = par
if par:
self.level = self.parent.level + 1
else:
self.level = 0
def get(self,... | class Environment:
def __init__(self, par=None, bnd=None):
if bnd:
self.binds = bnd
else:
self.binds = {}
self.parent = par
if par:
self.level = self.parent.level + 1
else:
self.level = 0
def get(self,... | Raise an error when a symbol cannot be found | Raise an error when a symbol cannot be found
| Python | mit | readevalprintlove/lithp,fogus/lithp,fogus/lithp,readevalprintlove/lithp,magomsk/lithp,readevalprintlove/lithp,fogus/lithp,magomsk/lithp,magomsk/lithp | class Environment:
def __init__(self, par=None, bnd=None):
if bnd:
self.binds = bnd
else:
self.binds = {}
self.parent = par
if par:
self.level = self.parent.level + 1
else:
self.le... | Raise an error when a symbol cannot be found | ## Code Before:
class Environment:
def __init__(self, par=None, bnd=None):
if bnd:
self.binds = bnd
else:
self.binds = {}
self.parent = par
if par:
self.level = self.parent.level + 1
else:
self.level = 0
... |
d1d0576b94ce000a77e08bd8353f5c1c10b0839f | setup.py | setup.py | from distutils.core import setup
setup(
name = 'AudioTranscode',
version = '1.0',
packages = ['audioTranscode'],
scripts = ['transcode'],
author = 'Jeffrey Aylesworth',
author_email = 'jeffrey@aylesworth.ca',
license = 'MIT',
url = 'http://github.com/jeffayle/Transcode'
)
| from distutils.core import setup
setup(
name = 'AudioTranscode',
version = '1.0',
packages = ['audioTranscode','audioTranscode.encoders','audioTranscode.decoders'],
scripts = ['transcode'],
author = 'Jeffrey Aylesworth',
author_email = 'jeffrey@aylesworth.ca',
license = 'MIT',
url = 'ht... | Include .encoders and .decoders packages with the distribution | Include .encoders and .decoders packages with the distribution | Python | isc | jeffayle/Transcode | from distutils.core import setup
setup(
name = 'AudioTranscode',
version = '1.0',
- packages = ['audioTranscode'],
+ packages = ['audioTranscode','audioTranscode.encoders','audioTranscode.decoders'],
scripts = ['transcode'],
author = 'Jeffrey Aylesworth',
author_email = 'jef... | Include .encoders and .decoders packages with the distribution | ## Code Before:
from distutils.core import setup
setup(
name = 'AudioTranscode',
version = '1.0',
packages = ['audioTranscode'],
scripts = ['transcode'],
author = 'Jeffrey Aylesworth',
author_email = 'jeffrey@aylesworth.ca',
license = 'MIT',
url = 'http://github.com/jeffayle/Transcode'
... |
ef7f0090bfb7f37fa584123520b02f69a3a392a0 | setup.py | setup.py |
from distutils.core import setup
setup(
name="workout",
version="0.2.0",
description="Store and display workout-data from FIT-files in mezzanine.",
author="Arnold Krille",
author_email="arnold@arnoldarts.de",
url="http://github.com/kampfschlaefer/mezzanine-workout",
license=open('LICENSE',... |
from distutils.core import setup
setup(
name="workout",
version="0.2.1",
description="Store and display workout-data from FIT-files in mezzanine.",
author="Arnold Krille",
author_email="arnold@arnoldarts.de",
url="http://github.com/kampfschlaefer/mezzanine-workout",
license=open('LICENSE',... | Fix inclusion of static files into the package | Fix inclusion of static files into the package
and increase the version-number a bit.
| Python | apache-2.0 | kampfschlaefer/mezzanine-workout,kampfschlaefer/mezzanine-workout,kampfschlaefer/mezzanine-workout |
from distutils.core import setup
setup(
name="workout",
- version="0.2.0",
+ version="0.2.1",
description="Store and display workout-data from FIT-files in mezzanine.",
author="Arnold Krille",
author_email="arnold@arnoldarts.de",
url="http://github.com/kampfschlaefer/mezz... | Fix inclusion of static files into the package | ## Code Before:
from distutils.core import setup
setup(
name="workout",
version="0.2.0",
description="Store and display workout-data from FIT-files in mezzanine.",
author="Arnold Krille",
author_email="arnold@arnoldarts.de",
url="http://github.com/kampfschlaefer/mezzanine-workout",
license... |
5c8754aefa0a0b2f9e49d95970475a66a6de9510 | start.py | start.py | from core.computer import Computer
from time import sleep
from console import start as start_console
# Initialize computer instance
computer = Computer()
computer.start_monitoring()
computer.processor.start_monitoring()
for mem in computer.nonvolatile_memory:
mem.start_monitoring()
computer.virtual_memory.start_mo... | from core.computer import Computer
from time import sleep
from console import start as start_console
# Initialize computer instance
computer = Computer()
computer.start_monitoring()
computer.processor.start_monitoring()
for mem in computer.nonvolatile_memory:
mem.start_monitoring()
computer.virtual_memory.start_mo... | Stop monitoring computer on shutdown. | Stop monitoring computer on shutdown.
| Python | bsd-3-clause | uzumaxy/pyspectator | from core.computer import Computer
from time import sleep
from console import start as start_console
# Initialize computer instance
computer = Computer()
computer.start_monitoring()
computer.processor.start_monitoring()
for mem in computer.nonvolatile_memory:
mem.start_monitoring()
computer.v... | Stop monitoring computer on shutdown. | ## Code Before:
from core.computer import Computer
from time import sleep
from console import start as start_console
# Initialize computer instance
computer = Computer()
computer.start_monitoring()
computer.processor.start_monitoring()
for mem in computer.nonvolatile_memory:
mem.start_monitoring()
computer.virtual... |
1d448b65840509c5f21abb7f5ad65a6ce20b139c | packs/travisci/actions/lib/action.py | packs/travisci/actions/lib/action.py | from st2actions.runners.pythonrunner import Action
import requests
class TravisCI(Action):
def __init__(self, config):
super(TravisCI, self).__init__(config)
def _init_header(self):
travis_header = {
'User_Agent': self.config['User-Agent'],
'Accept': self.config['Accep... | import requests
from st2actions.runners.pythonrunner import Action
API_URL = 'https://api.travis-ci.org'
HEADERS_ACCEPT = 'application/vnd.travis-ci.2+json'
HEADERS_HOST = ''
class TravisCI(Action):
def __init__(self, config):
super(TravisCI, self).__init__(config)
def _get_auth_headers(self):
... | Remove unnecessary values from the config - those should just be constants. | Remove unnecessary values from the config - those should just be constants.
| Python | apache-2.0 | StackStorm/st2contrib,StackStorm/st2contrib,pidah/st2contrib,pidah/st2contrib,pearsontechnology/st2contrib,StackStorm/st2contrib,pearsontechnology/st2contrib,tonybaloney/st2contrib,psychopenguin/st2contrib,digideskio/st2contrib,pearsontechnology/st2contrib,lmEshoo/st2contrib,tonybaloney/st2contrib,tonybaloney/st2contri... | + import requests
+
from st2actions.runners.pythonrunner import Action
- import requests
+
+ API_URL = 'https://api.travis-ci.org'
+ HEADERS_ACCEPT = 'application/vnd.travis-ci.2+json'
+ HEADERS_HOST = ''
class TravisCI(Action):
def __init__(self, config):
super(TravisCI, self).__init__(conf... | Remove unnecessary values from the config - those should just be constants. | ## Code Before:
from st2actions.runners.pythonrunner import Action
import requests
class TravisCI(Action):
def __init__(self, config):
super(TravisCI, self).__init__(config)
def _init_header(self):
travis_header = {
'User_Agent': self.config['User-Agent'],
'Accept': se... |
68eb1bd58b84c1937f6f8d15bb9ea9f02a402e22 | tests/cdscommon.py | tests/cdscommon.py |
import hashlib
import os
import shutil
import cdsapi
SAMPLE_DATA_FOLDER = os.path.join(os.path.dirname(__file__), 'sample-data')
EXTENSIONS = {'grib': '.grib', 'netcdf': '.nc'}
def ensure_data(dataset, request, folder=SAMPLE_DATA_FOLDER, name='{uuid}.grib'):
request_text = str(sorted(request.items())).encode('... |
import hashlib
import os
import shutil
import cdsapi
SAMPLE_DATA_FOLDER = os.path.join(os.path.dirname(__file__), 'sample-data')
EXTENSIONS = {'grib': '.grib', 'netcdf': '.nc'}
def ensure_data(dataset, request, folder=SAMPLE_DATA_FOLDER, name='{uuid}.grib'):
request_text = str(sorted(request.items())).encode('... | Drop impossible to get right code. | Drop impossible to get right code.
| Python | apache-2.0 | ecmwf/cfgrib |
import hashlib
import os
import shutil
import cdsapi
SAMPLE_DATA_FOLDER = os.path.join(os.path.dirname(__file__), 'sample-data')
EXTENSIONS = {'grib': '.grib', 'netcdf': '.nc'}
def ensure_data(dataset, request, folder=SAMPLE_DATA_FOLDER, name='{uuid}.grib'):
request_text = str(sorted(... | Drop impossible to get right code. | ## Code Before:
import hashlib
import os
import shutil
import cdsapi
SAMPLE_DATA_FOLDER = os.path.join(os.path.dirname(__file__), 'sample-data')
EXTENSIONS = {'grib': '.grib', 'netcdf': '.nc'}
def ensure_data(dataset, request, folder=SAMPLE_DATA_FOLDER, name='{uuid}.grib'):
request_text = str(sorted(request.it... |
db6b869eae416e72fa30b1d7271b0ed1d7dc1a55 | sqlalchemy_json/__init__.py | sqlalchemy_json/__init__.py | from sqlalchemy.ext.mutable import (
Mutable,
MutableDict)
from sqlalchemy_utils.types.json import JSONType
from . track import (
TrackedDict,
TrackedList)
__all__ = 'MutableJson', 'NestedMutableJson'
class NestedMutableDict(TrackedDict, Mutable):
@classmethod
def coerce(cls, key, value):
... | from sqlalchemy.ext.mutable import (
Mutable,
MutableDict)
from sqlalchemy_utils.types.json import JSONType
from . track import (
TrackedDict,
TrackedList)
__all__ = 'MutableJson', 'NestedMutableJson'
class NestedMutableDict(TrackedDict, Mutable):
@classmethod
def coerce(cls, key, value):
... | Fix error when setting JSON value to be `None` | Fix error when setting JSON value to be `None`
Previously this would raise an attribute error as `None` does not
have the `coerce` attribute.
| Python | bsd-2-clause | edelooff/sqlalchemy-json | from sqlalchemy.ext.mutable import (
Mutable,
MutableDict)
from sqlalchemy_utils.types.json import JSONType
from . track import (
TrackedDict,
TrackedList)
__all__ = 'MutableJson', 'NestedMutableJson'
class NestedMutableDict(TrackedDict, Mutable):
@classmethod
d... | Fix error when setting JSON value to be `None` | ## Code Before:
from sqlalchemy.ext.mutable import (
Mutable,
MutableDict)
from sqlalchemy_utils.types.json import JSONType
from . track import (
TrackedDict,
TrackedList)
__all__ = 'MutableJson', 'NestedMutableJson'
class NestedMutableDict(TrackedDict, Mutable):
@classmethod
def coerce(cls,... |
edf95105b7522b115dd4d3882ed57e707126c6af | timepiece/admin.py | timepiece/admin.py | from django.contrib import admin
from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType
class PermissionAdmin(admin.ModelAdmin):
list_display = ['__unicode__', 'codename']
list_filter = ['content_type__app_label']
class ContentTypeAdmin(admin.ModelAdmin)... | from django.contrib import admin
from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType
class PermissionAdmin(admin.ModelAdmin):
list_display = ['content_type', 'codename', 'name']
list_filter = ['content_type__app_label']
class ContentTypeAdmin(admin.Mo... | Update Python/Django: Remove unnecessary reference to __unicode__ | Update Python/Django: Remove unnecessary reference to __unicode__
| Python | mit | BocuStudio/django-timepiece,caktus/django-timepiece,arbitrahj/django-timepiece,caktus/django-timepiece,arbitrahj/django-timepiece,BocuStudio/django-timepiece,caktus/django-timepiece,BocuStudio/django-timepiece,arbitrahj/django-timepiece | from django.contrib import admin
from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType
class PermissionAdmin(admin.ModelAdmin):
- list_display = ['__unicode__', 'codename']
+ list_display = ['content_type', 'codename', 'name']
list_filte... | Update Python/Django: Remove unnecessary reference to __unicode__ | ## Code Before:
from django.contrib import admin
from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType
class PermissionAdmin(admin.ModelAdmin):
list_display = ['__unicode__', 'codename']
list_filter = ['content_type__app_label']
class ContentTypeAdmin(a... |
20017da43fe1bf5287b33d9d2fc7f597850bb5b5 | readthedocs/settings/proxito/base.py | readthedocs/settings/proxito/base.py |
class CommunityProxitoSettingsMixin:
ROOT_URLCONF = 'readthedocs.proxito.urls'
USE_SUBDOMAIN = True
@property
def MIDDLEWARE(self): # noqa
# Use our new middleware instead of the old one
classes = super().MIDDLEWARE
classes = list(classes)
index = classes.index(
... |
class CommunityProxitoSettingsMixin:
ROOT_URLCONF = 'readthedocs.proxito.urls'
USE_SUBDOMAIN = True
@property
def DATABASES(self):
# This keeps connections to the DB alive,
# which reduces latency with connecting to postgres
dbs = getattr(super(), 'DATABASES', {})
for... | Expand the logic in our proxito mixin. | Expand the logic in our proxito mixin.
This makes proxito mixin match production for .com/.org
in the areas where we are overriding the same things.
| Python | mit | rtfd/readthedocs.org,rtfd/readthedocs.org,rtfd/readthedocs.org,rtfd/readthedocs.org | +
class CommunityProxitoSettingsMixin:
ROOT_URLCONF = 'readthedocs.proxito.urls'
USE_SUBDOMAIN = True
+
+ @property
+ def DATABASES(self):
+ # This keeps connections to the DB alive,
+ # which reduces latency with connecting to postgres
+ dbs = getattr(super(), 'DAT... | Expand the logic in our proxito mixin. | ## Code Before:
class CommunityProxitoSettingsMixin:
ROOT_URLCONF = 'readthedocs.proxito.urls'
USE_SUBDOMAIN = True
@property
def MIDDLEWARE(self): # noqa
# Use our new middleware instead of the old one
classes = super().MIDDLEWARE
classes = list(classes)
index = clas... |
b4e5a284201d6d25607ff54aedcf6082e8a4d621 | st2client/st2client/models/reactor.py | st2client/st2client/models/reactor.py |
import logging
from st2client.models import core
LOG = logging.getLogger(__name__)
class Sensor(core.Resource):
_plural = 'Sensortypes'
_repr_attributes = ['name', 'pack']
class TriggerType(core.Resource):
_alias = 'Trigger'
_display_name = 'Trigger'
_plural = 'Triggertypes'
_plural_disp... |
import logging
from st2client.models import core
LOG = logging.getLogger(__name__)
class Sensor(core.Resource):
_plural = 'Sensortypes'
_repr_attributes = ['name', 'pack']
class TriggerType(core.Resource):
_alias = 'Trigger'
_display_name = 'Trigger'
_plural = 'Triggertypes'
_plural_disp... | Add Trigger model to client and alias it as TriggerSpecification. | Add Trigger model to client and alias it as TriggerSpecification.
| Python | apache-2.0 | pinterb/st2,peak6/st2,pixelrebel/st2,jtopjian/st2,pixelrebel/st2,alfasin/st2,pinterb/st2,Itxaka/st2,Plexxi/st2,lakshmi-kannan/st2,Itxaka/st2,grengojbo/st2,Plexxi/st2,jtopjian/st2,punalpatel/st2,punalpatel/st2,Plexxi/st2,nzlosh/st2,armab/st2,StackStorm/st2,punalpatel/st2,dennybaa/st2,nzlosh/st2,pixelrebel/st2,peak6/st2,... |
import logging
from st2client.models import core
LOG = logging.getLogger(__name__)
class Sensor(core.Resource):
_plural = 'Sensortypes'
_repr_attributes = ['name', 'pack']
class TriggerType(core.Resource):
_alias = 'Trigger'
_display_name = 'Trigger'
_plur... | Add Trigger model to client and alias it as TriggerSpecification. | ## Code Before:
import logging
from st2client.models import core
LOG = logging.getLogger(__name__)
class Sensor(core.Resource):
_plural = 'Sensortypes'
_repr_attributes = ['name', 'pack']
class TriggerType(core.Resource):
_alias = 'Trigger'
_display_name = 'Trigger'
_plural = 'Triggertypes'
... |
bd8901c18a6722660e7af742260ae4b8317a064b | youtube/tasks.py | youtube/tasks.py | import subprocess
import os
from pathlib import Path
from invoke import task
@task
def update(ctx):
"""
Update youtube-dl
"""
cmd = ['pipenv', 'update', 'youtube-dl']
subprocess.call(cmd)
@task
def clean(ctx):
"""
Clean up files
"""
import main
def rm(file_):
if file_.exists():
os.r... | import subprocess
import os
from pathlib import Path
from invoke import task
@task
def update(ctx):
"""
Update dependencies such as youtube-dl, etc.
"""
subprocess.call(['pipenv', 'update'])
@task
def clean(ctx):
"""
Clean up files
"""
import main
def rm(file_):
if file_.exists():
os.... | Update task now updates all dependencies | Update task now updates all dependencies
| Python | apache-2.0 | feihong/chinese-music-processors,feihong/chinese-music-processors | import subprocess
import os
from pathlib import Path
from invoke import task
@task
def update(ctx):
"""
- Update youtube-dl
+ Update dependencies such as youtube-dl, etc.
"""
+ subprocess.call(['pipenv', 'update'])
- cmd = ['pipenv', 'update', 'youtube-dl']
- subprocess.call(cmd)
... | Update task now updates all dependencies | ## Code Before:
import subprocess
import os
from pathlib import Path
from invoke import task
@task
def update(ctx):
"""
Update youtube-dl
"""
cmd = ['pipenv', 'update', 'youtube-dl']
subprocess.call(cmd)
@task
def clean(ctx):
"""
Clean up files
"""
import main
def rm(file_):
if file_.exis... |
532df8a669d7e54125c102ef4821272dc24aab23 | weasyprint/logger.py | weasyprint/logger.py |
from __future__ import division, unicode_literals
import logging
LOGGER = logging.getLogger('weasyprint')
# Default to logging to stderr.
if not LOGGER.handlers:
LOGGER.addHandler(logging.StreamHandler())
if LOGGER.level == logging.NOTSET:
LOGGER.setLevel(logging.INFO)
|
from __future__ import division, unicode_literals
import logging
LOGGER = logging.getLogger('weasyprint')
# Default to logging to stderr.
if not LOGGER.handlers:
handler = logging.StreamHandler()
formatter = logging.Formatter('%(levelname)s: %(message)s')
handler.setFormatter(formatter)
LOGGER.addH... | Add a better default formatter for logs | Add a better default formatter for logs
| Python | bsd-3-clause | Kozea/WeasyPrint,Kozea/WeasyPrint |
from __future__ import division, unicode_literals
import logging
LOGGER = logging.getLogger('weasyprint')
# Default to logging to stderr.
if not LOGGER.handlers:
- LOGGER.addHandler(logging.StreamHandler())
+ handler = logging.StreamHandler()
+ formatter = logging.Formatter('%(level... | Add a better default formatter for logs | ## Code Before:
from __future__ import division, unicode_literals
import logging
LOGGER = logging.getLogger('weasyprint')
# Default to logging to stderr.
if not LOGGER.handlers:
LOGGER.addHandler(logging.StreamHandler())
if LOGGER.level == logging.NOTSET:
LOGGER.setLevel(logging.INFO)
## Instruction:
Add... |
6049a916ea3adfe4ef8a7ae9dbfc918b69907ef4 | OnionLauncher/main.py | OnionLauncher/main.py | import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.uic import loadUi
class MainWindow(QMainWindow):
def __init__(self, *args):
super(MainWindow, self).__init__(*args)
loadUi("ui_files/main.ui", self)
self.tbAdd.clicked.connect(self.addRow)
self.tbRemove.clicked.connect(self.removeRo... | import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.uic import loadUi
class MainWindow(QMainWindow):
def __init__(self, *args):
super(MainWindow, self).__init__(*args)
loadUi("ui_files/main.ui", self)
buttons = {
self.tbAdd: self.addRow,
self.tbRemove: self.removeRow,
self.btn... | Put mouse clicks in it's own dictionary | Put mouse clicks in it's own dictionary
| Python | bsd-2-clause | neelchauhan/OnionLauncher | import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.uic import loadUi
class MainWindow(QMainWindow):
def __init__(self, *args):
super(MainWindow, self).__init__(*args)
loadUi("ui_files/main.ui", self)
- self.tbAdd.clicked.connect(self.addRow)
- self.tbRemove.click... | Put mouse clicks in it's own dictionary | ## Code Before:
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.uic import loadUi
class MainWindow(QMainWindow):
def __init__(self, *args):
super(MainWindow, self).__init__(*args)
loadUi("ui_files/main.ui", self)
self.tbAdd.clicked.connect(self.addRow)
self.tbRemove.clicked.conne... |
8a827d3e86cf2f6b9d36812e7058560ae120d4b2 | tests/test_watson.py | tests/test_watson.py | from pywatson.watson import Watson
class TestWatson:
def test_init(self, config):
watson = Watson(url=config['url'], username=config['username'], password=config['password'])
| from pywatson.answer.answer import Answer
from pywatson.watson import Watson
class TestWatson:
def test_ask_question_basic(self, watson):
answer = watson.ask_question('What is the Labour Code?')
assert type(answer) is Answer
| Add failing test for ask_question | Add failing test for ask_question
| Python | mit | sherlocke/pywatson | + from pywatson.answer.answer import Answer
from pywatson.watson import Watson
class TestWatson:
- def test_init(self, config):
- watson = Watson(url=config['url'], username=config['username'], password=config['password'])
+ def test_ask_question_basic(self, watson):
+ answer = watson.... | Add failing test for ask_question | ## Code Before:
from pywatson.watson import Watson
class TestWatson:
def test_init(self, config):
watson = Watson(url=config['url'], username=config['username'], password=config['password'])
## Instruction:
Add failing test for ask_question
## Code After:
from pywatson.answer.answer import Answer
from py... |
de324cc798da8694bab510efd51de4bfda528df7 | zinnia/views/entries.py | zinnia/views/entries.py | """Views for Zinnia entries"""
from django.views.generic.dates import BaseDateDetailView
from zinnia.models.entry import Entry
from zinnia.views.mixins.archives import ArchiveMixin
from zinnia.views.mixins.entry_protection import EntryProtectionMixin
from zinnia.views.mixins.callable_queryset import CallableQuerysetMi... | """Views for Zinnia entries"""
from django.views.generic.dates import BaseDateDetailView
from zinnia.models.entry import Entry
from zinnia.views.mixins.archives import ArchiveMixin
from zinnia.views.mixins.entry_preview import EntryPreviewMixin
from zinnia.views.mixins.entry_protection import EntryProtectionMixin
from... | Implement the EntryPreviewMixin in the EntryDetail view | Implement the EntryPreviewMixin in the EntryDetail view
| Python | bsd-3-clause | Maplecroft/django-blog-zinnia,ZuluPro/django-blog-zinnia,petecummings/django-blog-zinnia,Maplecroft/django-blog-zinnia,ZuluPro/django-blog-zinnia,petecummings/django-blog-zinnia,petecummings/django-blog-zinnia,aorzh/django-blog-zinnia,extertioner/django-blog-zinnia,Maplecroft/django-blog-zinnia,ghachey/django-blog-zinn... | """Views for Zinnia entries"""
from django.views.generic.dates import BaseDateDetailView
from zinnia.models.entry import Entry
from zinnia.views.mixins.archives import ArchiveMixin
+ from zinnia.views.mixins.entry_preview import EntryPreviewMixin
from zinnia.views.mixins.entry_protection import EntryProtec... | Implement the EntryPreviewMixin in the EntryDetail view | ## Code Before:
"""Views for Zinnia entries"""
from django.views.generic.dates import BaseDateDetailView
from zinnia.models.entry import Entry
from zinnia.views.mixins.archives import ArchiveMixin
from zinnia.views.mixins.entry_protection import EntryProtectionMixin
from zinnia.views.mixins.callable_queryset import Ca... |
e93a321e3d137fb21a42d0e0bfd257a537be05d3 | diy/parerga/config.py | diy/parerga/config.py |
import os
# directories constants
PARERGA_ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
PARERGA_ENTRY_DIR = os.path.join(PARERGA_ROOT_DIR, "p")
PARERGA_STATIC_DIR = os.path.join(PARERGA_ROOT_DIR, "static")
PARERGA_TEMPLATE_DIR = os.path.join(PARERGA_ROOT_DIR, "templates")
# database location
PARERGA_DB = os.... |
import os
# directories constants
PARERGA_ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PARERGA_ENTRY_DIR = os.path.join(PARERGA_ROOT_DIR, "p")
PARERGA_STATIC_DIR = os.path.join(PARERGA_ROOT_DIR, "static")
PARERGA_TEMPLATE_DIR = os.path.join(PARERGA_ROOT_DIR, "templates")
# database location... | Update path vars for the new source location | Update path vars for the new source location
| Python | bsd-3-clause | nadirs/parerga,nadirs/parerga |
import os
# directories constants
- PARERGA_ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
+ PARERGA_ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PARERGA_ENTRY_DIR = os.path.join(PARERGA_ROOT_DIR, "p")
PARERGA_STATIC_DIR = os.path.join(PARERGA_ROOT_DIR, "static")
PARERGA... | Update path vars for the new source location | ## Code Before:
import os
# directories constants
PARERGA_ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
PARERGA_ENTRY_DIR = os.path.join(PARERGA_ROOT_DIR, "p")
PARERGA_STATIC_DIR = os.path.join(PARERGA_ROOT_DIR, "static")
PARERGA_TEMPLATE_DIR = os.path.join(PARERGA_ROOT_DIR, "templates")
# database location
... |
2724b4dd7ed350baeae0a8e0ef53475f40b1208b | project_generator/tools/makearmclang.py | project_generator/tools/makearmclang.py |
from copy import deepcopy
import logging
from .makefile import MakefileTool
logger = logging.getLogger('progen.tools.armclang')
class MakefileArmclang(MakefileTool):
def __init__(self, workspace, env_settings):
MakefileTool.__init__(self, workspace, env_settings, logger)
@staticmethod
def get_... |
from copy import deepcopy
import logging
from .makefile import MakefileTool
logger = logging.getLogger('progen.tools.armclang')
class MakefileArmclang(MakefileTool):
def __init__(self, workspace, env_settings):
MakefileTool.__init__(self, workspace, env_settings, logger)
# enable preprocessing ... | Enable linker preprocessing for armclang. | Enable linker preprocessing for armclang.
This should be temporary; for some reason the .sct cpp shebang isn't working for me. Same result in any case.
| Python | apache-2.0 | project-generator/project_generator |
from copy import deepcopy
import logging
from .makefile import MakefileTool
logger = logging.getLogger('progen.tools.armclang')
class MakefileArmclang(MakefileTool):
def __init__(self, workspace, env_settings):
MakefileTool.__init__(self, workspace, env_settings, logger)
+ ... | Enable linker preprocessing for armclang. | ## Code Before:
from copy import deepcopy
import logging
from .makefile import MakefileTool
logger = logging.getLogger('progen.tools.armclang')
class MakefileArmclang(MakefileTool):
def __init__(self, workspace, env_settings):
MakefileTool.__init__(self, workspace, env_settings, logger)
@staticmet... |
9ae5ea3876fae6ef0bc092d87c71d9ea86040cf7 | InvenTree/company/api.py | InvenTree/company/api.py | from __future__ import unicode_literals
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import filters
from rest_framework import generics, permissions
from django.conf.urls import url
from .models import Company
from .serializers import CompanySerializer
class CompanyList(generic... | from __future__ import unicode_literals
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import filters
from rest_framework import generics, permissions
from django.conf.urls import url
from .models import Company
from .serializers import CompanySerializer
class CompanyList(generic... | Add RUD endpoint for Company | Add RUD endpoint for Company
| Python | mit | SchrodingersGat/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree,inventree/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree | from __future__ import unicode_literals
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import filters
from rest_framework import generics, permissions
from django.conf.urls import url
from .models import Company
from .serializers import CompanySerializer
... | Add RUD endpoint for Company | ## Code Before:
from __future__ import unicode_literals
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import filters
from rest_framework import generics, permissions
from django.conf.urls import url
from .models import Company
from .serializers import CompanySerializer
class Com... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.