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
52
3.32k
instruction
stringlengths
16
444
content
stringlengths
133
4.32k
fuzzy_diff
stringlengths
16
3.18k
7435d508ae95c69dcb596e74f62bfb030011201f
tests/general/test_required_folders.py
tests/general/test_required_folders.py
""" Test that the All Mail folder is enabled for Gmail. """ import pytest from inbox.auth.gmail import GmailAuthHandler from inbox.basicauth import GmailSettingError from inbox.crispin import GmailCrispinClient class AccountStub(object): id = 0 email_address = '[email protected]' access_token = None imap_endpoint = None def new_token(self): return ('foo', 22) def validate_token(self, new_token): return True class ConnectionStub(object): def logout(self): pass def get_auth_handler(monkeypatch, folders): g = GmailAuthHandler('gmail') def mock_connect(a): return ConnectionStub() g.connect_account = mock_connect monkeypatch.setattr(GmailCrispinClient, 'folder_names', lambda x: folders) return g def test_all_mail_missing(monkeypatch): """ Test that validate_folders throws a GmailSettingError if All Mail is not in the list of folders. """ g = get_auth_handler(monkeypatch, {'inbox': 'INBOX'}) with pytest.raises(GmailSettingError): g.verify_account(AccountStub()) def test_all_mail_present(monkeypatch): """ Test that the validate_folders passes if All Mail is present. """ g = get_auth_handler(monkeypatch, {'all': 'ALL', 'inbox': 'INBOX', 'trash': 'TRASH'}) assert g.verify_account(AccountStub())
""" Test that the All Mail folder is enabled for Gmail. """ import pytest from inbox.auth.gmail import GmailAuthHandler from inbox.basicauth import GmailSettingError from inbox.crispin import GmailCrispinClient class AccountStub(object): id = 0 email_address = '[email protected]' access_token = None imap_endpoint = None sync_state = 'running' def new_token(self): return ('foo', 22) def validate_token(self, new_token): return True class ConnectionStub(object): def logout(self): pass def get_auth_handler(monkeypatch, folders): g = GmailAuthHandler('gmail') def mock_connect(a): return ConnectionStub() g.connect_account = mock_connect monkeypatch.setattr(GmailCrispinClient, 'folder_names', lambda x: folders) return g def test_all_mail_missing(monkeypatch): """ Test that validate_folders throws a GmailSettingError if All Mail is not in the list of folders. """ g = get_auth_handler(monkeypatch, {'inbox': 'INBOX'}) with pytest.raises(GmailSettingError): g.verify_account(AccountStub()) def test_all_mail_present(monkeypatch): """ Test that the validate_folders passes if All Mail is present. """ g = get_auth_handler(monkeypatch, {'all': 'ALL', 'inbox': 'INBOX', 'trash': 'TRASH'}) assert g.verify_account(AccountStub())
Update mock Account in tests.
Update mock Account in tests.
Python
agpl-3.0
jobscore/sync-engine,jobscore/sync-engine,nylas/sync-engine,closeio/nylas,jobscore/sync-engine,nylas/sync-engine,closeio/nylas,jobscore/sync-engine,closeio/nylas,nylas/sync-engine,nylas/sync-engine,closeio/nylas
""" Test that the All Mail folder is enabled for Gmail. """ import pytest from inbox.auth.gmail import GmailAuthHandler from inbox.basicauth import GmailSettingError from inbox.crispin import GmailCrispinClient class AccountStub(object): id = 0 email_address = '[email protected]' access_token = None imap_endpoint = None + sync_state = 'running' def new_token(self): return ('foo', 22) def validate_token(self, new_token): return True class ConnectionStub(object): def logout(self): pass def get_auth_handler(monkeypatch, folders): g = GmailAuthHandler('gmail') def mock_connect(a): return ConnectionStub() g.connect_account = mock_connect monkeypatch.setattr(GmailCrispinClient, 'folder_names', lambda x: folders) return g def test_all_mail_missing(monkeypatch): """ Test that validate_folders throws a GmailSettingError if All Mail is not in the list of folders. """ g = get_auth_handler(monkeypatch, {'inbox': 'INBOX'}) with pytest.raises(GmailSettingError): g.verify_account(AccountStub()) def test_all_mail_present(monkeypatch): """ Test that the validate_folders passes if All Mail is present. """ g = get_auth_handler(monkeypatch, {'all': 'ALL', 'inbox': 'INBOX', 'trash': 'TRASH'}) assert g.verify_account(AccountStub())
Update mock Account in tests.
## Code Before: """ Test that the All Mail folder is enabled for Gmail. """ import pytest from inbox.auth.gmail import GmailAuthHandler from inbox.basicauth import GmailSettingError from inbox.crispin import GmailCrispinClient class AccountStub(object): id = 0 email_address = '[email protected]' access_token = None imap_endpoint = None def new_token(self): return ('foo', 22) def validate_token(self, new_token): return True class ConnectionStub(object): def logout(self): pass def get_auth_handler(monkeypatch, folders): g = GmailAuthHandler('gmail') def mock_connect(a): return ConnectionStub() g.connect_account = mock_connect monkeypatch.setattr(GmailCrispinClient, 'folder_names', lambda x: folders) return g def test_all_mail_missing(monkeypatch): """ Test that validate_folders throws a GmailSettingError if All Mail is not in the list of folders. """ g = get_auth_handler(monkeypatch, {'inbox': 'INBOX'}) with pytest.raises(GmailSettingError): g.verify_account(AccountStub()) def test_all_mail_present(monkeypatch): """ Test that the validate_folders passes if All Mail is present. """ g = get_auth_handler(monkeypatch, {'all': 'ALL', 'inbox': 'INBOX', 'trash': 'TRASH'}) assert g.verify_account(AccountStub()) ## Instruction: Update mock Account in tests. ## Code After: """ Test that the All Mail folder is enabled for Gmail. """ import pytest from inbox.auth.gmail import GmailAuthHandler from inbox.basicauth import GmailSettingError from inbox.crispin import GmailCrispinClient class AccountStub(object): id = 0 email_address = '[email protected]' access_token = None imap_endpoint = None sync_state = 'running' def new_token(self): return ('foo', 22) def validate_token(self, new_token): return True class ConnectionStub(object): def logout(self): pass def get_auth_handler(monkeypatch, folders): g = GmailAuthHandler('gmail') def mock_connect(a): return ConnectionStub() g.connect_account = mock_connect monkeypatch.setattr(GmailCrispinClient, 'folder_names', lambda x: folders) return g def test_all_mail_missing(monkeypatch): """ Test that validate_folders throws a GmailSettingError if All Mail is not in the list of folders. """ g = get_auth_handler(monkeypatch, {'inbox': 'INBOX'}) with pytest.raises(GmailSettingError): g.verify_account(AccountStub()) def test_all_mail_present(monkeypatch): """ Test that the validate_folders passes if All Mail is present. """ g = get_auth_handler(monkeypatch, {'all': 'ALL', 'inbox': 'INBOX', 'trash': 'TRASH'}) assert g.verify_account(AccountStub())
// ... existing code ... imap_endpoint = None sync_state = 'running' // ... rest of the code ...
f4e07b93ab81fd0a0dc59ec77fca596a2fcca738
froide/helper/form_utils.py
froide/helper/form_utils.py
import json from django.db import models class DjangoJSONEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, models.Model) and hasattr(obj, 'as_data'): return obj.as_data() return json.JSONEncoder.default(self, obj) class JSONMixin(object): def as_json(self): return json.dumps(self.as_data(), cls=DjangoJSONEncoder) def as_data(self): return { 'fields': { str(name): self.field_to_dict(name, field) for name, field in self.fields.items() }, 'errors': {f: e.get_json_data() for f, e in self.errors.items()}, 'nonFieldErrors': [e.get_json_data() for e in self.non_field_errors()] } def field_to_dict(self, name, field): return { "type": field.__class__.__name__, "widget_type": field.widget.__class__.__name__, "hidden": field.widget.is_hidden, "required": field.widget.is_required, "label": str(field.label), "help_text": str(field.help_text), "initial": self.get_initial_for_field(field, name), "placeholder": str(field.widget.attrs.get('placeholder', '')), "value": self[name].value() if self.is_bound else None }
import json from django.db import models class DjangoJSONEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, models.Model) and hasattr(obj, 'as_data'): return obj.as_data() return json.JSONEncoder.default(self, obj) def get_data(error): if isinstance(error, (dict, str)): return error return error.get_json_data() class JSONMixin(object): def as_json(self): return json.dumps(self.as_data(), cls=DjangoJSONEncoder) def as_data(self): return { 'fields': { str(name): self.field_to_dict(name, field) for name, field in self.fields.items() }, 'errors': {f: get_data(e) for f, e in self.errors.items()}, 'nonFieldErrors': [get_data(e) for e in self.non_field_errors()] } def field_to_dict(self, name, field): return { "type": field.__class__.__name__, "widget_type": field.widget.__class__.__name__, "hidden": field.widget.is_hidden, "required": field.widget.is_required, "label": str(field.label), "help_text": str(field.help_text), "initial": self.get_initial_for_field(field, name), "placeholder": str(field.widget.attrs.get('placeholder', '')), "value": self[name].value() if self.is_bound else None }
Fix serialization of form errors
Fix serialization of form errors
Python
mit
fin/froide,fin/froide,fin/froide,stefanw/froide,stefanw/froide,stefanw/froide,stefanw/froide,stefanw/froide,fin/froide
import json from django.db import models class DjangoJSONEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, models.Model) and hasattr(obj, 'as_data'): return obj.as_data() return json.JSONEncoder.default(self, obj) + def get_data(error): + if isinstance(error, (dict, str)): + return error + return error.get_json_data() + + class JSONMixin(object): def as_json(self): return json.dumps(self.as_data(), cls=DjangoJSONEncoder) def as_data(self): return { 'fields': { str(name): self.field_to_dict(name, field) for name, field in self.fields.items() }, - 'errors': {f: e.get_json_data() for f, e in self.errors.items()}, + 'errors': {f: get_data(e) for f, e in self.errors.items()}, - 'nonFieldErrors': [e.get_json_data() for e in self.non_field_errors()] + 'nonFieldErrors': [get_data(e) for e in self.non_field_errors()] } def field_to_dict(self, name, field): return { "type": field.__class__.__name__, "widget_type": field.widget.__class__.__name__, "hidden": field.widget.is_hidden, "required": field.widget.is_required, "label": str(field.label), "help_text": str(field.help_text), "initial": self.get_initial_for_field(field, name), "placeholder": str(field.widget.attrs.get('placeholder', '')), "value": self[name].value() if self.is_bound else None }
Fix serialization of form errors
## Code Before: import json from django.db import models class DjangoJSONEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, models.Model) and hasattr(obj, 'as_data'): return obj.as_data() return json.JSONEncoder.default(self, obj) class JSONMixin(object): def as_json(self): return json.dumps(self.as_data(), cls=DjangoJSONEncoder) def as_data(self): return { 'fields': { str(name): self.field_to_dict(name, field) for name, field in self.fields.items() }, 'errors': {f: e.get_json_data() for f, e in self.errors.items()}, 'nonFieldErrors': [e.get_json_data() for e in self.non_field_errors()] } def field_to_dict(self, name, field): return { "type": field.__class__.__name__, "widget_type": field.widget.__class__.__name__, "hidden": field.widget.is_hidden, "required": field.widget.is_required, "label": str(field.label), "help_text": str(field.help_text), "initial": self.get_initial_for_field(field, name), "placeholder": str(field.widget.attrs.get('placeholder', '')), "value": self[name].value() if self.is_bound else None } ## Instruction: Fix serialization of form errors ## Code After: import json from django.db import models class DjangoJSONEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, models.Model) and hasattr(obj, 'as_data'): return obj.as_data() return json.JSONEncoder.default(self, obj) def get_data(error): if isinstance(error, (dict, str)): return error return error.get_json_data() class JSONMixin(object): def as_json(self): return json.dumps(self.as_data(), cls=DjangoJSONEncoder) def as_data(self): return { 'fields': { str(name): self.field_to_dict(name, field) for name, field in self.fields.items() }, 'errors': {f: get_data(e) for f, e in self.errors.items()}, 'nonFieldErrors': [get_data(e) for e in self.non_field_errors()] } def field_to_dict(self, name, field): return { "type": field.__class__.__name__, "widget_type": field.widget.__class__.__name__, "hidden": field.widget.is_hidden, "required": field.widget.is_required, "label": str(field.label), "help_text": str(field.help_text), "initial": self.get_initial_for_field(field, name), "placeholder": str(field.widget.attrs.get('placeholder', '')), "value": self[name].value() if self.is_bound else None }
... def get_data(error): if isinstance(error, (dict, str)): return error return error.get_json_data() class JSONMixin(object): ... }, 'errors': {f: get_data(e) for f, e in self.errors.items()}, 'nonFieldErrors': [get_data(e) for e in self.non_field_errors()] } ...
af59d91afdddf9a5f3f673dd7bba98ad4538ec55
go_store_service/tests/test_api_handler.py
go_store_service/tests/test_api_handler.py
from unittest import TestCase from go_store_service.api_handler import ( ApiApplication, create_urlspec_regex, CollectionHandler, ElementHandler) class TestCreateUrlspecRegex(TestCase): def test_no_variables(self): self.assertEqual(create_urlspec_regex("/foo/bar"), "/foo/bar") class TestApiApplication(TestCase): def test_build_routes(self): collection_factory = lambda **kw: "collection" app = ApiApplication() app.collections = ( ('/:owner_id/store', collection_factory), ) [collection_route, elem_route] = app._build_routes() self.assertEqual(collection_route.handler_class, CollectionHandler) self.assertEqual(collection_route.regex.pattern, "/(?P<owner_id>[^/]*)/store$") self.assertEqual(collection_route.kwargs, { "collection_factory": collection_factory, }) self.assertEqual(elem_route.handler_class, ElementHandler) self.assertEqual(elem_route.regex.pattern, "/(?P<owner_id>[^/]*)/store/(?P<elem_id>[^/]*)$") self.assertEqual(elem_route.kwargs, { "collection_factory": collection_factory, })
from unittest import TestCase from go_store_service.api_handler import ( ApiApplication, create_urlspec_regex, CollectionHandler, ElementHandler) class TestCreateUrlspecRegex(TestCase): def test_no_variables(self): self.assertEqual(create_urlspec_regex("/foo/bar"), "/foo/bar") def test_one_variable(self): self.assertEqual( create_urlspec_regex("/:foo/bar"), "/(?P<foo>[^/]*)/bar") def test_two_variables(self): self.assertEqual( create_urlspec_regex("/:foo/bar/:baz"), "/(?P<foo>[^/]*)/bar/(?P<baz>[^/]*)") class TestApiApplication(TestCase): def test_build_routes(self): collection_factory = lambda **kw: "collection" app = ApiApplication() app.collections = ( ('/:owner_id/store', collection_factory), ) [collection_route, elem_route] = app._build_routes() self.assertEqual(collection_route.handler_class, CollectionHandler) self.assertEqual(collection_route.regex.pattern, "/(?P<owner_id>[^/]*)/store$") self.assertEqual(collection_route.kwargs, { "collection_factory": collection_factory, }) self.assertEqual(elem_route.handler_class, ElementHandler) self.assertEqual(elem_route.regex.pattern, "/(?P<owner_id>[^/]*)/store/(?P<elem_id>[^/]*)$") self.assertEqual(elem_route.kwargs, { "collection_factory": collection_factory, })
Add test for passing paths with variables to create_urlspec_regex.
Add test for passing paths with variables to create_urlspec_regex.
Python
bsd-3-clause
praekelt/go-store-service
from unittest import TestCase from go_store_service.api_handler import ( ApiApplication, create_urlspec_regex, CollectionHandler, ElementHandler) class TestCreateUrlspecRegex(TestCase): def test_no_variables(self): self.assertEqual(create_urlspec_regex("/foo/bar"), "/foo/bar") + + def test_one_variable(self): + self.assertEqual( + create_urlspec_regex("/:foo/bar"), "/(?P<foo>[^/]*)/bar") + + def test_two_variables(self): + self.assertEqual( + create_urlspec_regex("/:foo/bar/:baz"), + "/(?P<foo>[^/]*)/bar/(?P<baz>[^/]*)") class TestApiApplication(TestCase): def test_build_routes(self): collection_factory = lambda **kw: "collection" app = ApiApplication() app.collections = ( ('/:owner_id/store', collection_factory), ) [collection_route, elem_route] = app._build_routes() self.assertEqual(collection_route.handler_class, CollectionHandler) self.assertEqual(collection_route.regex.pattern, "/(?P<owner_id>[^/]*)/store$") self.assertEqual(collection_route.kwargs, { "collection_factory": collection_factory, }) self.assertEqual(elem_route.handler_class, ElementHandler) self.assertEqual(elem_route.regex.pattern, "/(?P<owner_id>[^/]*)/store/(?P<elem_id>[^/]*)$") self.assertEqual(elem_route.kwargs, { "collection_factory": collection_factory, })
Add test for passing paths with variables to create_urlspec_regex.
## Code Before: from unittest import TestCase from go_store_service.api_handler import ( ApiApplication, create_urlspec_regex, CollectionHandler, ElementHandler) class TestCreateUrlspecRegex(TestCase): def test_no_variables(self): self.assertEqual(create_urlspec_regex("/foo/bar"), "/foo/bar") class TestApiApplication(TestCase): def test_build_routes(self): collection_factory = lambda **kw: "collection" app = ApiApplication() app.collections = ( ('/:owner_id/store', collection_factory), ) [collection_route, elem_route] = app._build_routes() self.assertEqual(collection_route.handler_class, CollectionHandler) self.assertEqual(collection_route.regex.pattern, "/(?P<owner_id>[^/]*)/store$") self.assertEqual(collection_route.kwargs, { "collection_factory": collection_factory, }) self.assertEqual(elem_route.handler_class, ElementHandler) self.assertEqual(elem_route.regex.pattern, "/(?P<owner_id>[^/]*)/store/(?P<elem_id>[^/]*)$") self.assertEqual(elem_route.kwargs, { "collection_factory": collection_factory, }) ## Instruction: Add test for passing paths with variables to create_urlspec_regex. ## Code After: from unittest import TestCase from go_store_service.api_handler import ( ApiApplication, create_urlspec_regex, CollectionHandler, ElementHandler) class TestCreateUrlspecRegex(TestCase): def test_no_variables(self): self.assertEqual(create_urlspec_regex("/foo/bar"), "/foo/bar") def test_one_variable(self): self.assertEqual( create_urlspec_regex("/:foo/bar"), "/(?P<foo>[^/]*)/bar") def test_two_variables(self): self.assertEqual( create_urlspec_regex("/:foo/bar/:baz"), "/(?P<foo>[^/]*)/bar/(?P<baz>[^/]*)") class TestApiApplication(TestCase): def test_build_routes(self): collection_factory = lambda **kw: "collection" app = ApiApplication() app.collections = ( ('/:owner_id/store', collection_factory), ) [collection_route, elem_route] = app._build_routes() self.assertEqual(collection_route.handler_class, CollectionHandler) self.assertEqual(collection_route.regex.pattern, "/(?P<owner_id>[^/]*)/store$") self.assertEqual(collection_route.kwargs, { "collection_factory": collection_factory, }) self.assertEqual(elem_route.handler_class, ElementHandler) self.assertEqual(elem_route.regex.pattern, "/(?P<owner_id>[^/]*)/store/(?P<elem_id>[^/]*)$") self.assertEqual(elem_route.kwargs, { "collection_factory": collection_factory, })
// ... existing code ... self.assertEqual(create_urlspec_regex("/foo/bar"), "/foo/bar") def test_one_variable(self): self.assertEqual( create_urlspec_regex("/:foo/bar"), "/(?P<foo>[^/]*)/bar") def test_two_variables(self): self.assertEqual( create_urlspec_regex("/:foo/bar/:baz"), "/(?P<foo>[^/]*)/bar/(?P<baz>[^/]*)") // ... rest of the code ...
2fe315e1753aca8215228091e3a64af057020bc2
celery/loaders/__init__.py
celery/loaders/__init__.py
import os from celery.loaders.djangoapp import Loader as DjangoLoader from celery.loaders.default import Loader as DefaultLoader from django.conf import settings from django.core.management import setup_environ """ .. class:: Loader The current loader class. """ Loader = DefaultLoader if settings.configured: Loader = DjangoLoader else: if not callable(getattr(os, "fork", None)): # Platform doesn't support fork() # XXX On systems without fork, multiprocessing seems to be launching # the processes in some other way which does not copy the memory # of the parent process. This means that any configured env might # be lost. This is a hack to make it work on Windows. # A better way might be to use os.environ to set the currently # used configuration method so to propogate it to the "child" # processes. But this has to be experimented with. # [asksol/heyman] try: settings_mod = os.environ.get("DJANGO_SETTINGS_MODULE", "settings") project_settings = __import__(settings_mod, {}, {}, ['']) setup_environ(project_settings) Loader = DjangoLoader except ImportError: pass """ .. data:: current_loader The current loader instance. """ current_loader = Loader() """ .. data:: settings The global settings object. """ settings = current_loader.conf
import os from celery.loaders.djangoapp import Loader as DjangoLoader from celery.loaders.default import Loader as DefaultLoader from django.conf import settings from django.core.management import setup_environ """ .. class:: Loader The current loader class. """ Loader = DefaultLoader if settings.configured: Loader = DjangoLoader else: try: # A settings module may be defined, but Django didn't attempt to # load it yet. As an alternative to calling the private _setup(), # we could also check whether DJANGO_SETTINGS_MODULE is set. settings._setup() except ImportError: if not callable(getattr(os, "fork", None)): # Platform doesn't support fork() # XXX On systems without fork, multiprocessing seems to be launching # the processes in some other way which does not copy the memory # of the parent process. This means that any configured env might # be lost. This is a hack to make it work on Windows. # A better way might be to use os.environ to set the currently # used configuration method so to propogate it to the "child" # processes. But this has to be experimented with. # [asksol/heyman] try: settings_mod = os.environ.get("DJANGO_SETTINGS_MODULE", "settings") project_settings = __import__(settings_mod, {}, {}, ['']) setup_environ(project_settings) Loader = DjangoLoader except ImportError: pass else: Loader = DjangoLoader """ .. data:: current_loader The current loader instance. """ current_loader = Loader() """ .. data:: settings The global settings object. """ settings = current_loader.conf
Use a django settings module, if defined, even if it wasn't already loaded by Django (for example, when using ./celeryd directly rather than the celeryd management command.
Use a django settings module, if defined, even if it wasn't already loaded by Django (for example, when using ./celeryd directly rather than the celeryd management command.
Python
bsd-3-clause
frac/celery,WoLpH/celery,cbrepo/celery,frac/celery,mitsuhiko/celery,mitsuhiko/celery,ask/celery,WoLpH/celery,cbrepo/celery,ask/celery
import os from celery.loaders.djangoapp import Loader as DjangoLoader from celery.loaders.default import Loader as DefaultLoader from django.conf import settings from django.core.management import setup_environ """ .. class:: Loader The current loader class. """ Loader = DefaultLoader if settings.configured: Loader = DjangoLoader else: + try: + # A settings module may be defined, but Django didn't attempt to + # load it yet. As an alternative to calling the private _setup(), + # we could also check whether DJANGO_SETTINGS_MODULE is set. + settings._setup() + except ImportError: - if not callable(getattr(os, "fork", None)): + if not callable(getattr(os, "fork", None)): - # Platform doesn't support fork() + # Platform doesn't support fork() - # XXX On systems without fork, multiprocessing seems to be launching + # XXX On systems without fork, multiprocessing seems to be launching - # the processes in some other way which does not copy the memory + # the processes in some other way which does not copy the memory - # of the parent process. This means that any configured env might + # of the parent process. This means that any configured env might - # be lost. This is a hack to make it work on Windows. + # be lost. This is a hack to make it work on Windows. - # A better way might be to use os.environ to set the currently + # A better way might be to use os.environ to set the currently - # used configuration method so to propogate it to the "child" + # used configuration method so to propogate it to the "child" - # processes. But this has to be experimented with. + # processes. But this has to be experimented with. - # [asksol/heyman] + # [asksol/heyman] - try: + try: - settings_mod = os.environ.get("DJANGO_SETTINGS_MODULE", + settings_mod = os.environ.get("DJANGO_SETTINGS_MODULE", - "settings") + "settings") - project_settings = __import__(settings_mod, {}, {}, ['']) + project_settings = __import__(settings_mod, {}, {}, ['']) - setup_environ(project_settings) + setup_environ(project_settings) - Loader = DjangoLoader + Loader = DjangoLoader - except ImportError: + except ImportError: - pass + pass + else: + Loader = DjangoLoader """ .. data:: current_loader The current loader instance. """ current_loader = Loader() """ .. data:: settings The global settings object. """ settings = current_loader.conf
Use a django settings module, if defined, even if it wasn't already loaded by Django (for example, when using ./celeryd directly rather than the celeryd management command.
## Code Before: import os from celery.loaders.djangoapp import Loader as DjangoLoader from celery.loaders.default import Loader as DefaultLoader from django.conf import settings from django.core.management import setup_environ """ .. class:: Loader The current loader class. """ Loader = DefaultLoader if settings.configured: Loader = DjangoLoader else: if not callable(getattr(os, "fork", None)): # Platform doesn't support fork() # XXX On systems without fork, multiprocessing seems to be launching # the processes in some other way which does not copy the memory # of the parent process. This means that any configured env might # be lost. This is a hack to make it work on Windows. # A better way might be to use os.environ to set the currently # used configuration method so to propogate it to the "child" # processes. But this has to be experimented with. # [asksol/heyman] try: settings_mod = os.environ.get("DJANGO_SETTINGS_MODULE", "settings") project_settings = __import__(settings_mod, {}, {}, ['']) setup_environ(project_settings) Loader = DjangoLoader except ImportError: pass """ .. data:: current_loader The current loader instance. """ current_loader = Loader() """ .. data:: settings The global settings object. """ settings = current_loader.conf ## Instruction: Use a django settings module, if defined, even if it wasn't already loaded by Django (for example, when using ./celeryd directly rather than the celeryd management command. ## Code After: import os from celery.loaders.djangoapp import Loader as DjangoLoader from celery.loaders.default import Loader as DefaultLoader from django.conf import settings from django.core.management import setup_environ """ .. class:: Loader The current loader class. """ Loader = DefaultLoader if settings.configured: Loader = DjangoLoader else: try: # A settings module may be defined, but Django didn't attempt to # load it yet. As an alternative to calling the private _setup(), # we could also check whether DJANGO_SETTINGS_MODULE is set. settings._setup() except ImportError: if not callable(getattr(os, "fork", None)): # Platform doesn't support fork() # XXX On systems without fork, multiprocessing seems to be launching # the processes in some other way which does not copy the memory # of the parent process. This means that any configured env might # be lost. This is a hack to make it work on Windows. # A better way might be to use os.environ to set the currently # used configuration method so to propogate it to the "child" # processes. But this has to be experimented with. # [asksol/heyman] try: settings_mod = os.environ.get("DJANGO_SETTINGS_MODULE", "settings") project_settings = __import__(settings_mod, {}, {}, ['']) setup_environ(project_settings) Loader = DjangoLoader except ImportError: pass else: Loader = DjangoLoader """ .. data:: current_loader The current loader instance. """ current_loader = Loader() """ .. data:: settings The global settings object. """ settings = current_loader.conf
... else: try: # A settings module may be defined, but Django didn't attempt to # load it yet. As an alternative to calling the private _setup(), # we could also check whether DJANGO_SETTINGS_MODULE is set. settings._setup() except ImportError: if not callable(getattr(os, "fork", None)): # Platform doesn't support fork() # XXX On systems without fork, multiprocessing seems to be launching # the processes in some other way which does not copy the memory # of the parent process. This means that any configured env might # be lost. This is a hack to make it work on Windows. # A better way might be to use os.environ to set the currently # used configuration method so to propogate it to the "child" # processes. But this has to be experimented with. # [asksol/heyman] try: settings_mod = os.environ.get("DJANGO_SETTINGS_MODULE", "settings") project_settings = __import__(settings_mod, {}, {}, ['']) setup_environ(project_settings) Loader = DjangoLoader except ImportError: pass else: Loader = DjangoLoader ...
f17d9c3b45758c02f1f67cbec6709e42149369f5
packs/asserts/actions/object_equals.py
packs/asserts/actions/object_equals.py
import pprint import sys from st2actions.runners.pythonrunner import Action __all__ = [ 'AssertObjectEquals' ] class AssertObjectEquals(Action): def run(self, object, expected): ret = cmp(object, expected) if ret == 0: sys.stdout.write('EQUAL.') else: pprint.pprint('Input: \n%s' % object, stream=sys.stderr) pprint.pprint('Expected: \n%s' % expected, stream=sys.stderr) raise ValueError('Objects not equal. Input: %s, Expected: %s.' % (object, expected))
import pprint import sys from st2actions.runners.pythonrunner import Action __all__ = [ 'AssertObjectEquals' ] def cmp(x, y): return (x > y) - (x < y) class AssertObjectEquals(Action): def run(self, object, expected): ret = cmp(object, expected) if ret == 0: sys.stdout.write('EQUAL.') else: pprint.pprint('Input: \n%s' % object, stream=sys.stderr) pprint.pprint('Expected: \n%s' % expected, stream=sys.stderr) raise ValueError('Objects not equal. Input: %s, Expected: %s.' % (object, expected))
Make action python 3 compatible
Make action python 3 compatible
Python
apache-2.0
StackStorm/st2tests,StackStorm/st2tests,StackStorm/st2tests
import pprint import sys from st2actions.runners.pythonrunner import Action __all__ = [ 'AssertObjectEquals' ] + + + def cmp(x, y): + return (x > y) - (x < y) class AssertObjectEquals(Action): def run(self, object, expected): ret = cmp(object, expected) if ret == 0: sys.stdout.write('EQUAL.') else: pprint.pprint('Input: \n%s' % object, stream=sys.stderr) pprint.pprint('Expected: \n%s' % expected, stream=sys.stderr) raise ValueError('Objects not equal. Input: %s, Expected: %s.' % (object, expected))
Make action python 3 compatible
## Code Before: import pprint import sys from st2actions.runners.pythonrunner import Action __all__ = [ 'AssertObjectEquals' ] class AssertObjectEquals(Action): def run(self, object, expected): ret = cmp(object, expected) if ret == 0: sys.stdout.write('EQUAL.') else: pprint.pprint('Input: \n%s' % object, stream=sys.stderr) pprint.pprint('Expected: \n%s' % expected, stream=sys.stderr) raise ValueError('Objects not equal. Input: %s, Expected: %s.' % (object, expected)) ## Instruction: Make action python 3 compatible ## Code After: import pprint import sys from st2actions.runners.pythonrunner import Action __all__ = [ 'AssertObjectEquals' ] def cmp(x, y): return (x > y) - (x < y) class AssertObjectEquals(Action): def run(self, object, expected): ret = cmp(object, expected) if ret == 0: sys.stdout.write('EQUAL.') else: pprint.pprint('Input: \n%s' % object, stream=sys.stderr) pprint.pprint('Expected: \n%s' % expected, stream=sys.stderr) raise ValueError('Objects not equal. Input: %s, Expected: %s.' % (object, expected))
... ] def cmp(x, y): return (x > y) - (x < y) ...
f2ea241e9bb6e5e927a90c56438bf7883ae3744f
siemstress/__init__.py
siemstress/__init__.py
__version__ = '0.2' __author__ = 'Dan Persons <[email protected]>' __license__ = 'MIT License' __github__ = 'https://github.com/dogoncouch/siemstress' __all__ = ['core', 'querycore', 'query'] import siemstress.query
__version__ = '0.2' __author__ = 'Dan Persons <[email protected]>' __license__ = 'MIT License' __github__ = 'https://github.com/dogoncouch/siemstress' __all__ = ['core', 'querycore', 'query'] import siemstress.query import siemstress.trigger
Add trigger to module import
Add trigger to module import
Python
mit
dogoncouch/siemstress
__version__ = '0.2' __author__ = 'Dan Persons <[email protected]>' __license__ = 'MIT License' __github__ = 'https://github.com/dogoncouch/siemstress' __all__ = ['core', 'querycore', 'query'] import siemstress.query + import siemstress.trigger
Add trigger to module import
## Code Before: __version__ = '0.2' __author__ = 'Dan Persons <[email protected]>' __license__ = 'MIT License' __github__ = 'https://github.com/dogoncouch/siemstress' __all__ = ['core', 'querycore', 'query'] import siemstress.query ## Instruction: Add trigger to module import ## Code After: __version__ = '0.2' __author__ = 'Dan Persons <[email protected]>' __license__ = 'MIT License' __github__ = 'https://github.com/dogoncouch/siemstress' __all__ = ['core', 'querycore', 'query'] import siemstress.query import siemstress.trigger
// ... existing code ... import siemstress.query import siemstress.trigger // ... rest of the code ...
452ad6f3de797285a50094a4a145714e75204d95
bake/cmdline.py
bake/cmdline.py
import api as bake import sys # This def main(args=sys.argv[1:]): # Set up command line argument options optparser = bake.make_optparser() options, arguments = optparser.parse_args() bake.process_options(options) ## Configuration is stored in the bake.cfg file in the current directory config = bake.load_config() ## End processing of command line parameters ## Prepare for big loop # The overwrite command pushes lines onto the top of the bake parameter file if options.overwrite: lines = options.overwrite else: lines = [] # Load bake parameter file hin = open(options.file,'r') lines += hin.readlines() hin.close() # This mixIterator object is kind of the core of bake. (label, tokens, mixIterator) = bake.make_iterator(config['label']['label_tag'], config['label']['pattern'], lines, options.slice_start, options.slice_end) ## This is the main loop, iterating over each set of values bake.default_loop(label, tokens, mixIterator, config, options) if __name__ == '__main__': main()
import api as bake import sys def main(args=sys.argv[1:]): # Set up command line argument options optparser = bake.make_optparser() options, arguments = optparser.parse_args() bake.process_options(options) ## Configuration is stored in the bake.cfg file in the current directory config = bake.load_config() ## End processing of command line parameters ## Prepare for big loop # The overwrite command pushes lines onto the top of the bake parameter file if options.overwrite: lines = options.overwrite else: lines = [] # Load bake parameter file hin = open(options.file, 'r') lines += hin.readlines() hin.close() # This mixIterator object is kind of the core of bake. (label, tokens, mixIterator) = bake.make_iterator(config['label']['label_tag'], config['label']['pattern'], lines, options.slice_start, options.slice_end) ## This is the main loop, iterating over each set of values bake.default_loop(label, tokens, mixIterator, config, options) if __name__ == '__main__': main()
Make pep8 run mostly cleanly
Make pep8 run mostly cleanly
Python
mit
AlexSzatmary/bake
import api as bake import sys - # This + def main(args=sys.argv[1:]): # Set up command line argument options optparser = bake.make_optparser() options, arguments = optparser.parse_args() bake.process_options(options) ## Configuration is stored in the bake.cfg file in the current directory config = bake.load_config() ## End processing of command line parameters ## Prepare for big loop # The overwrite command pushes lines onto the top of the bake parameter file if options.overwrite: lines = options.overwrite else: lines = [] # Load bake parameter file - hin = open(options.file,'r') + hin = open(options.file, 'r') lines += hin.readlines() hin.close() # This mixIterator object is kind of the core of bake. - (label, tokens, + (label, tokens, mixIterator) = bake.make_iterator(config['label']['label_tag'], - config['label']['pattern'], + config['label']['pattern'], - lines, options.slice_start, + lines, options.slice_start, options.slice_end) - + ## This is the main loop, iterating over each set of values bake.default_loop(label, tokens, mixIterator, config, options) if __name__ == '__main__': main()
Make pep8 run mostly cleanly
## Code Before: import api as bake import sys # This def main(args=sys.argv[1:]): # Set up command line argument options optparser = bake.make_optparser() options, arguments = optparser.parse_args() bake.process_options(options) ## Configuration is stored in the bake.cfg file in the current directory config = bake.load_config() ## End processing of command line parameters ## Prepare for big loop # The overwrite command pushes lines onto the top of the bake parameter file if options.overwrite: lines = options.overwrite else: lines = [] # Load bake parameter file hin = open(options.file,'r') lines += hin.readlines() hin.close() # This mixIterator object is kind of the core of bake. (label, tokens, mixIterator) = bake.make_iterator(config['label']['label_tag'], config['label']['pattern'], lines, options.slice_start, options.slice_end) ## This is the main loop, iterating over each set of values bake.default_loop(label, tokens, mixIterator, config, options) if __name__ == '__main__': main() ## Instruction: Make pep8 run mostly cleanly ## Code After: import api as bake import sys def main(args=sys.argv[1:]): # Set up command line argument options optparser = bake.make_optparser() options, arguments = optparser.parse_args() bake.process_options(options) ## Configuration is stored in the bake.cfg file in the current directory config = bake.load_config() ## End processing of command line parameters ## Prepare for big loop # The overwrite command pushes lines onto the top of the bake parameter file if options.overwrite: lines = options.overwrite else: lines = [] # Load bake parameter file hin = open(options.file, 'r') lines += hin.readlines() hin.close() # This mixIterator object is kind of the core of bake. (label, tokens, mixIterator) = bake.make_iterator(config['label']['label_tag'], config['label']['pattern'], lines, options.slice_start, options.slice_end) ## This is the main loop, iterating over each set of values bake.default_loop(label, tokens, mixIterator, config, options) if __name__ == '__main__': main()
# ... existing code ... def main(args=sys.argv[1:]): # ... modified code ... # Load bake parameter file hin = open(options.file, 'r') lines += hin.readlines() ... # This mixIterator object is kind of the core of bake. (label, tokens, mixIterator) = bake.make_iterator(config['label']['label_tag'], config['label']['pattern'], lines, options.slice_start, options.slice_end) ## This is the main loop, iterating over each set of values # ... rest of the code ...
a8a257ef2bfb63d175f7db1cb91924adae125b5c
sympy/core/tests/test_compatibility.py
sympy/core/tests/test_compatibility.py
from sympy.core.compatibility import default_sort_key, as_int, ordered from sympy.core.singleton import S from sympy.utilities.pytest import raises from sympy.abc import x def test_default_sort_key(): func = lambda x: x assert sorted([func, x, func], key=default_sort_key) == [func, func, x] def test_as_int(): raises(ValueError, lambda : as_int(1.1)) raises(ValueError, lambda : as_int([])) def test_ordered(): "Issue 4111 - this was failing with python2/3 problems" assert(list(ordered([{1:3, 2:4, 9:10}, {1:3}])) == \ [{1: 3}, {1: 3, 2: 4, 9: 10}])
from sympy.core.compatibility import default_sort_key, as_int, ordered from sympy.core.singleton import S from sympy.utilities.pytest import raises from sympy.abc import x def test_default_sort_key(): func = lambda x: x assert sorted([func, x, func], key=default_sort_key) == [func, func, x] def test_as_int(): raises(ValueError, lambda : as_int(1.1)) raises(ValueError, lambda : as_int([])) def test_ordered(): # Issue 4111 - this had been failing with python2/3 problems assert(list(ordered([{1:3, 2:4, 9:10}, {1:3}])) == \ [{1: 3}, {1: 3, 2: 4, 9: 10}])
Change docstring to inline comment
Change docstring to inline comment This is in response to comment from smichr modified: sympy/core/tests/test_compatibility.py
Python
bsd-3-clause
Mitchkoens/sympy,Sumith1896/sympy,kaichogami/sympy,sunny94/temp,jamesblunt/sympy,pbrady/sympy,Vishluck/sympy,Titan-C/sympy,jaimahajan1997/sympy,kevalds51/sympy,yukoba/sympy,kevalds51/sympy,abhiii5459/sympy,debugger22/sympy,kumarkrishna/sympy,lindsayad/sympy,Vishluck/sympy,souravsingh/sympy,debugger22/sympy,yashsharan/sympy,abloomston/sympy,sunny94/temp,farhaanbukhsh/sympy,aktech/sympy,mcdaniel67/sympy,wanglongqi/sympy,saurabhjn76/sympy,madan96/sympy,hargup/sympy,souravsingh/sympy,Curious72/sympy,atsao72/sympy,atreyv/sympy,Davidjohnwilson/sympy,Designist/sympy,jamesblunt/sympy,VaibhavAgarwalVA/sympy,debugger22/sympy,Gadal/sympy,diofant/diofant,jbbskinny/sympy,dqnykamp/sympy,shikil/sympy,yashsharan/sympy,toolforger/sympy,Designist/sympy,Sumith1896/sympy,saurabhjn76/sympy,shikil/sympy,shipci/sympy,vipulroxx/sympy,postvakje/sympy,sahmed95/sympy,kaushik94/sympy,sampadsaha5/sympy,dqnykamp/sympy,meghana1995/sympy,iamutkarshtiwari/sympy,chaffra/sympy,liangjiaxing/sympy,Mitchkoens/sympy,grevutiu-gabriel/sympy,kaushik94/sympy,skidzo/sympy,ga7g08/sympy,postvakje/sympy,Mitchkoens/sympy,pandeyadarsh/sympy,Gadal/sympy,postvakje/sympy,kumarkrishna/sympy,kumarkrishna/sympy,AunShiLord/sympy,MechCoder/sympy,pbrady/sympy,cccfran/sympy,pbrady/sympy,abloomston/sympy,grevutiu-gabriel/sympy,liangjiaxing/sympy,yashsharan/sympy,wyom/sympy,rahuldan/sympy,jbbskinny/sympy,rahuldan/sympy,garvitr/sympy,madan96/sympy,AkademieOlympia/sympy,pandeyadarsh/sympy,chaffra/sympy,oliverlee/sympy,ga7g08/sympy,sunny94/temp,VaibhavAgarwalVA/sympy,mafiya69/sympy,Curious72/sympy,atsao72/sympy,shikil/sympy,aktech/sympy,souravsingh/sympy,Davidjohnwilson/sympy,maniteja123/sympy,lindsayad/sympy,bukzor/sympy,beni55/sympy,Davidjohnwilson/sympy,sahilshekhawat/sympy,asm666/sympy,drufat/sympy,MridulS/sympy,Shaswat27/sympy,beni55/sympy,Arafatk/sympy,Shaswat27/sympy,jbbskinny/sympy,iamutkarshtiwari/sympy,ChristinaZografou/sympy,wanglongqi/sympy,farhaanbukhsh/sympy,ahhda/sympy,wyom/sympy,emon10005/sympy,abhiii5459/sympy,cswiercz/sympy,ChristinaZografou/sympy,jaimahajan1997/sympy,Gadal/sympy,dqnykamp/sympy,kevalds51/sympy,Shaswat27/sympy,chaffra/sympy,liangjiaxing/sympy,jaimahajan1997/sympy,jamesblunt/sympy,moble/sympy,Vishluck/sympy,yukoba/sympy,Designist/sympy,atreyv/sympy,pandeyadarsh/sympy,hargup/sympy,skirpichev/omg,jerli/sympy,iamutkarshtiwari/sympy,hargup/sympy,vipulroxx/sympy,moble/sympy,cccfran/sympy,mafiya69/sympy,moble/sympy,vipulroxx/sympy,sahmed95/sympy,kaushik94/sympy,AkademieOlympia/sympy,MridulS/sympy,meghana1995/sympy,atreyv/sympy,asm666/sympy,madan96/sympy,AunShiLord/sympy,bukzor/sympy,oliverlee/sympy,ga7g08/sympy,Curious72/sympy,yukoba/sympy,wanglongqi/sympy,Titan-C/sympy,emon10005/sympy,cswiercz/sympy,farhaanbukhsh/sympy,abloomston/sympy,atsao72/sympy,beni55/sympy,rahuldan/sympy,drufat/sympy,meghana1995/sympy,toolforger/sympy,MechCoder/sympy,oliverlee/sympy,ChristinaZografou/sympy,jerli/sympy,mcdaniel67/sympy,Arafatk/sympy,sahmed95/sympy,sahilshekhawat/sympy,ahhda/sympy,maniteja123/sympy,emon10005/sympy,mcdaniel67/sympy,abhiii5459/sympy,jerli/sympy,saurabhjn76/sympy,MechCoder/sympy,sahilshekhawat/sympy,drufat/sympy,cswiercz/sympy,AunShiLord/sympy,garvitr/sympy,VaibhavAgarwalVA/sympy,garvitr/sympy,ahhda/sympy,shipci/sympy,wyom/sympy,toolforger/sympy,lindsayad/sympy,cccfran/sympy,aktech/sympy,maniteja123/sympy,kaichogami/sympy,sampadsaha5/sympy,Titan-C/sympy,MridulS/sympy,sampadsaha5/sympy,kaichogami/sympy,Arafatk/sympy,mafiya69/sympy,shipci/sympy,grevutiu-gabriel/sympy,skidzo/sympy,skidzo/sympy,asm666/sympy,AkademieOlympia/sympy,bukzor/sympy,Sumith1896/sympy
from sympy.core.compatibility import default_sort_key, as_int, ordered from sympy.core.singleton import S from sympy.utilities.pytest import raises from sympy.abc import x def test_default_sort_key(): func = lambda x: x assert sorted([func, x, func], key=default_sort_key) == [func, func, x] def test_as_int(): raises(ValueError, lambda : as_int(1.1)) raises(ValueError, lambda : as_int([])) def test_ordered(): - "Issue 4111 - this was failing with python2/3 problems" + # Issue 4111 - this had been failing with python2/3 problems assert(list(ordered([{1:3, 2:4, 9:10}, {1:3}])) == \ [{1: 3}, {1: 3, 2: 4, 9: 10}])
Change docstring to inline comment
## Code Before: from sympy.core.compatibility import default_sort_key, as_int, ordered from sympy.core.singleton import S from sympy.utilities.pytest import raises from sympy.abc import x def test_default_sort_key(): func = lambda x: x assert sorted([func, x, func], key=default_sort_key) == [func, func, x] def test_as_int(): raises(ValueError, lambda : as_int(1.1)) raises(ValueError, lambda : as_int([])) def test_ordered(): "Issue 4111 - this was failing with python2/3 problems" assert(list(ordered([{1:3, 2:4, 9:10}, {1:3}])) == \ [{1: 3}, {1: 3, 2: 4, 9: 10}]) ## Instruction: Change docstring to inline comment ## Code After: from sympy.core.compatibility import default_sort_key, as_int, ordered from sympy.core.singleton import S from sympy.utilities.pytest import raises from sympy.abc import x def test_default_sort_key(): func = lambda x: x assert sorted([func, x, func], key=default_sort_key) == [func, func, x] def test_as_int(): raises(ValueError, lambda : as_int(1.1)) raises(ValueError, lambda : as_int([])) def test_ordered(): # Issue 4111 - this had been failing with python2/3 problems assert(list(ordered([{1:3, 2:4, 9:10}, {1:3}])) == \ [{1: 3}, {1: 3, 2: 4, 9: 10}])
... def test_ordered(): # Issue 4111 - this had been failing with python2/3 problems assert(list(ordered([{1:3, 2:4, 9:10}, {1:3}])) == \ ...
ae0158c49224464084e0302897c91e9c9fa7ffbe
webview.py
webview.py
"""Main module for pyicemon webview""" import SimpleHTTPServer import SocketServer import threading import sys import os import logging from monitor import Monitor from publishers import WebsocketPublisher from connection import Connection PORT = 80 if __name__ == "__main__": logging.basicConfig(level=logging.WARN, filename="pyicemon.log") # Serve static HTTP content. os.chdir("static") handler = SimpleHTTPServer.SimpleHTTPRequestHandler httpd = SocketServer.TCPServer(("", PORT), handler) t = threading.Thread(target=httpd.serve_forever) t.daemon = True t.start() # Fire up pyicemon. host, port = sys.argv[1], sys.argv[2] mon = Monitor(Connection(host, int(port))) mon.addPublisher(WebsocketPublisher(port=9999)) mon.run()
"""Main module for pyicemon webview""" # Handle difference in module name between python2/3. try: from SimpleHTTPServer import SimpleHTTPRequestHandler except ImportError: from http.server import SimpleHTTPRequestHandler try: from SocketServer import TCPServer except ImportError: from socketserver import TCPServer import threading import sys import os import logging from monitor import Monitor from publishers import WebsocketPublisher from connection import Connection PORT = 80 if __name__ == "__main__": logging.basicConfig(level=logging.WARN, filename="pyicemon.log") # Serve static HTTP content. os.chdir("static") handler = SimpleHTTPRequestHandler httpd = TCPServer(("", PORT), handler) t = threading.Thread(target=httpd.serve_forever) t.daemon = True t.start() # Fire up pyicemon. host, port = sys.argv[1], sys.argv[2] mon = Monitor(Connection(host, int(port))) mon.addPublisher(WebsocketPublisher(port=9999)) mon.run()
Make it work with python3.
Make it work with python3.
Python
mit
DiscoViking/pyicemon,DiscoViking/pyicemon
"""Main module for pyicemon webview""" - import SimpleHTTPServer - import SocketServer + # Handle difference in module name between python2/3. + try: + from SimpleHTTPServer import SimpleHTTPRequestHandler + except ImportError: + from http.server import SimpleHTTPRequestHandler + + try: + from SocketServer import TCPServer + except ImportError: + from socketserver import TCPServer + import threading import sys import os import logging from monitor import Monitor from publishers import WebsocketPublisher from connection import Connection PORT = 80 if __name__ == "__main__": logging.basicConfig(level=logging.WARN, filename="pyicemon.log") # Serve static HTTP content. os.chdir("static") - handler = SimpleHTTPServer.SimpleHTTPRequestHandler + handler = SimpleHTTPRequestHandler - httpd = SocketServer.TCPServer(("", PORT), handler) + httpd = TCPServer(("", PORT), handler) t = threading.Thread(target=httpd.serve_forever) t.daemon = True t.start() # Fire up pyicemon. host, port = sys.argv[1], sys.argv[2] mon = Monitor(Connection(host, int(port))) mon.addPublisher(WebsocketPublisher(port=9999)) mon.run()
Make it work with python3.
## Code Before: """Main module for pyicemon webview""" import SimpleHTTPServer import SocketServer import threading import sys import os import logging from monitor import Monitor from publishers import WebsocketPublisher from connection import Connection PORT = 80 if __name__ == "__main__": logging.basicConfig(level=logging.WARN, filename="pyicemon.log") # Serve static HTTP content. os.chdir("static") handler = SimpleHTTPServer.SimpleHTTPRequestHandler httpd = SocketServer.TCPServer(("", PORT), handler) t = threading.Thread(target=httpd.serve_forever) t.daemon = True t.start() # Fire up pyicemon. host, port = sys.argv[1], sys.argv[2] mon = Monitor(Connection(host, int(port))) mon.addPublisher(WebsocketPublisher(port=9999)) mon.run() ## Instruction: Make it work with python3. ## Code After: """Main module for pyicemon webview""" # Handle difference in module name between python2/3. try: from SimpleHTTPServer import SimpleHTTPRequestHandler except ImportError: from http.server import SimpleHTTPRequestHandler try: from SocketServer import TCPServer except ImportError: from socketserver import TCPServer import threading import sys import os import logging from monitor import Monitor from publishers import WebsocketPublisher from connection import Connection PORT = 80 if __name__ == "__main__": logging.basicConfig(level=logging.WARN, filename="pyicemon.log") # Serve static HTTP content. os.chdir("static") handler = SimpleHTTPRequestHandler httpd = TCPServer(("", PORT), handler) t = threading.Thread(target=httpd.serve_forever) t.daemon = True t.start() # Fire up pyicemon. host, port = sys.argv[1], sys.argv[2] mon = Monitor(Connection(host, int(port))) mon.addPublisher(WebsocketPublisher(port=9999)) mon.run()
// ... existing code ... # Handle difference in module name between python2/3. try: from SimpleHTTPServer import SimpleHTTPRequestHandler except ImportError: from http.server import SimpleHTTPRequestHandler try: from SocketServer import TCPServer except ImportError: from socketserver import TCPServer import threading // ... modified code ... os.chdir("static") handler = SimpleHTTPRequestHandler httpd = TCPServer(("", PORT), handler) t = threading.Thread(target=httpd.serve_forever) // ... rest of the code ...
a7867806a6bd3abfd6bf2bcac6c490965be000e2
tests/test_completeness.py
tests/test_completeness.py
import unittest as unittest from syntax import Syntax from jscodegen import CodeGenerator def add_cases(generator): def class_decorator(cls): """Add tests to `cls` generated by `generator()`.""" for f, token in generator(): test = lambda self, i=token, f=f: f(self, i) test.__name__ = "test %s" % token.name setattr(cls, test.__name__, test) return cls return class_decorator def _test_tokens(): def t(self, to): c = CodeGenerator({}) func_name = to.name.lower() try: getattr(c, func_name) self.assertTrue(True, func_name) except AttributeError: self.fail("Not implemented: %s" % func_name) for token in Syntax: yield t, token class TestCase(unittest.TestCase): pass TestCase = add_cases(_test_tokens)(TestCase) if __name__=="__main__": unittest.main()
import unittest as unittest from jscodegen.syntax import Syntax from jscodegen import CodeGenerator def add_cases(generator): def class_decorator(cls): """Add tests to `cls` generated by `generator()`.""" for f, token in generator(): test = lambda self, i=token, f=f: f(self, i) test.__name__ = "test %s" % token.name setattr(cls, test.__name__, test) return cls return class_decorator def _test_tokens(): def t(self, to): c = CodeGenerator({}) func_name = to.name.lower() try: getattr(c, func_name) self.assertTrue(True, func_name) except AttributeError: self.fail("Not implemented: %s" % func_name) for token in Syntax: yield t, token class TestCase(unittest.TestCase): pass TestCase = add_cases(_test_tokens)(TestCase) if __name__=="__main__": unittest.main()
Fix an issue in the tests
Fix an issue in the tests
Python
mit
ksons/jscodegen.py
import unittest as unittest - from syntax import Syntax + from jscodegen.syntax import Syntax from jscodegen import CodeGenerator def add_cases(generator): def class_decorator(cls): """Add tests to `cls` generated by `generator()`.""" for f, token in generator(): test = lambda self, i=token, f=f: f(self, i) test.__name__ = "test %s" % token.name setattr(cls, test.__name__, test) return cls return class_decorator def _test_tokens(): def t(self, to): c = CodeGenerator({}) func_name = to.name.lower() try: getattr(c, func_name) self.assertTrue(True, func_name) except AttributeError: self.fail("Not implemented: %s" % func_name) for token in Syntax: yield t, token class TestCase(unittest.TestCase): pass TestCase = add_cases(_test_tokens)(TestCase) if __name__=="__main__": unittest.main() +
Fix an issue in the tests
## Code Before: import unittest as unittest from syntax import Syntax from jscodegen import CodeGenerator def add_cases(generator): def class_decorator(cls): """Add tests to `cls` generated by `generator()`.""" for f, token in generator(): test = lambda self, i=token, f=f: f(self, i) test.__name__ = "test %s" % token.name setattr(cls, test.__name__, test) return cls return class_decorator def _test_tokens(): def t(self, to): c = CodeGenerator({}) func_name = to.name.lower() try: getattr(c, func_name) self.assertTrue(True, func_name) except AttributeError: self.fail("Not implemented: %s" % func_name) for token in Syntax: yield t, token class TestCase(unittest.TestCase): pass TestCase = add_cases(_test_tokens)(TestCase) if __name__=="__main__": unittest.main() ## Instruction: Fix an issue in the tests ## Code After: import unittest as unittest from jscodegen.syntax import Syntax from jscodegen import CodeGenerator def add_cases(generator): def class_decorator(cls): """Add tests to `cls` generated by `generator()`.""" for f, token in generator(): test = lambda self, i=token, f=f: f(self, i) test.__name__ = "test %s" % token.name setattr(cls, test.__name__, test) return cls return class_decorator def _test_tokens(): def t(self, to): c = CodeGenerator({}) func_name = to.name.lower() try: getattr(c, func_name) self.assertTrue(True, func_name) except AttributeError: self.fail("Not implemented: %s" % func_name) for token in Syntax: yield t, token class TestCase(unittest.TestCase): pass TestCase = add_cases(_test_tokens)(TestCase) if __name__=="__main__": unittest.main()
// ... existing code ... import unittest as unittest from jscodegen.syntax import Syntax from jscodegen import CodeGenerator // ... rest of the code ...
4eda3f3535d28e2486745f33504c417ba6837c3a
stdnum/nz/__init__.py
stdnum/nz/__init__.py
"""Collection of New Zealand numbers."""
"""Collection of New Zealand numbers.""" # provide aliases from stdnum.nz import ird as vat # noqa: F401
Add missing vat alias for New Zealand
Add missing vat alias for New Zealand Closes https://github.com/arthurdejong/python-stdnum/pull/202
Python
lgpl-2.1
arthurdejong/python-stdnum,arthurdejong/python-stdnum,arthurdejong/python-stdnum
"""Collection of New Zealand numbers.""" + # provide aliases + from stdnum.nz import ird as vat # noqa: F401 +
Add missing vat alias for New Zealand
## Code Before: """Collection of New Zealand numbers.""" ## Instruction: Add missing vat alias for New Zealand ## Code After: """Collection of New Zealand numbers.""" # provide aliases from stdnum.nz import ird as vat # noqa: F401
# ... existing code ... """Collection of New Zealand numbers.""" # provide aliases from stdnum.nz import ird as vat # noqa: F401 # ... rest of the code ...
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="mfhclient_process", target=mfhclient.main, ) server_process = Process( args=(args, update_event,), name="server_process", target=server.main, ) if args.client is not None: mfhclient_process.start() if args.client is not None: server_process.start() if args.updater: trigger_process = Process( args=(update_event,), name="trigger_process", target=update.trigger, ) trigger_process.start() trigger_process.join() while mfhclient_process.is_alive() or server_process.is_alive(): time.sleep(5) else: if args.updater: # update.pull("origin", "master") sys.stdout.flush() os.execl(sys.executable, sys.executable, *sys.argv) if __name__ == '__main__': # Parse arguments args = parse() if args.c: args.client = HONEYPORT if args.s: args.server = HIVEPORT main()
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 = create_process("server", server.main, args, update_event) if args.client is not None: client.start() if args.client is not None: serv.start() if args.updater: trigger = create_process("trigger", update.trigger, update_event) trigger.start() trigger.join() while client.is_alive() or serv.is_alive(): time.sleep(5) else: if args.updater: update.pull("origin", "master") sys.stdout.flush() os.execl(sys.executable, sys.executable, *sys.argv) def create_process(name, function, *arguments): process = Process( args=arguments, name="{0}_process".format(name), target=function, ) return process if __name__ == '__main__': # Parse arguments args = parse() if args.c: args.client = HONEYPORT if args.s: args.server = HIVEPORT processes = {} main()
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, args, update_event) + serv = create_process("server", server.main, args, update_event) - mfhclient_process = Process( - args=(args, update_event,), - name="mfhclient_process", - target=mfhclient.main, - ) - server_process = Process( - args=(args, update_event,), - name="server_process", - target=server.main, - ) if args.client is not None: - mfhclient_process.start() + client.start() if args.client is not None: - server_process.start() + serv.start() if args.updater: + trigger = create_process("trigger", update.trigger, update_event) - trigger_process = Process( - args=(update_event,), - name="trigger_process", - target=update.trigger, - ) - trigger_process.start() + trigger.start() - trigger_process.join() + trigger.join() - while mfhclient_process.is_alive() or server_process.is_alive(): + while client.is_alive() or serv.is_alive(): time.sleep(5) else: if args.updater: - # update.pull("origin", "master") + update.pull("origin", "master") sys.stdout.flush() os.execl(sys.executable, sys.executable, *sys.argv) + + + def create_process(name, function, *arguments): + process = Process( + args=arguments, + name="{0}_process".format(name), + target=function, + ) + return process if __name__ == '__main__': # Parse arguments args = parse() if args.c: args.client = HONEYPORT if args.s: args.server = HIVEPORT + processes = {} 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,), name="mfhclient_process", target=mfhclient.main, ) server_process = Process( args=(args, update_event,), name="server_process", target=server.main, ) if args.client is not None: mfhclient_process.start() if args.client is not None: server_process.start() if args.updater: trigger_process = Process( args=(update_event,), name="trigger_process", target=update.trigger, ) trigger_process.start() trigger_process.join() while mfhclient_process.is_alive() or server_process.is_alive(): time.sleep(5) else: if args.updater: # update.pull("origin", "master") sys.stdout.flush() os.execl(sys.executable, sys.executable, *sys.argv) if __name__ == '__main__': # Parse arguments args = parse() if args.c: args.client = HONEYPORT if args.s: args.server = HIVEPORT main() ## Instruction: Move all the process creation in a new function ## Code After: 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 = create_process("server", server.main, args, update_event) if args.client is not None: client.start() if args.client is not None: serv.start() if args.updater: trigger = create_process("trigger", update.trigger, update_event) trigger.start() trigger.join() while client.is_alive() or serv.is_alive(): time.sleep(5) else: if args.updater: update.pull("origin", "master") sys.stdout.flush() os.execl(sys.executable, sys.executable, *sys.argv) def create_process(name, function, *arguments): process = Process( args=arguments, name="{0}_process".format(name), target=function, ) return process if __name__ == '__main__': # Parse arguments args = parse() if args.c: args.client = HONEYPORT if args.s: args.server = HIVEPORT processes = {} main()
... update_event = Event() client = create_process("client", mfhclient.main, args, update_event) serv = create_process("server", server.main, args, update_event) if args.client is not None: client.start() if args.client is not None: serv.start() if args.updater: trigger = create_process("trigger", update.trigger, update_event) trigger.start() trigger.join() while client.is_alive() or serv.is_alive(): time.sleep(5) ... if args.updater: update.pull("origin", "master") sys.stdout.flush() ... os.execl(sys.executable, sys.executable, *sys.argv) def create_process(name, function, *arguments): process = Process( args=arguments, name="{0}_process".format(name), target=function, ) return process ... args.server = HIVEPORT processes = {} main() ...
b21750ad60b84bf87f15c3d25ffa0317091a10dc
pyoracc/test/model/test_corpus.py
pyoracc/test/model/test_corpus.py
import pytest from ...model.corpus import Corpus from ..fixtures import tiny_corpus, sample_corpus, whole_corpus slow = pytest.mark.skipif( not pytest.config.getoption("--runslow"), reason="need --runslow option to run" ) def test_tiny(): corpus = Corpus(source=tiny_corpus()) assert corpus.successes == 1 assert corpus.failures == 1 @slow def test_sample(): corpus = Corpus(source=sample_corpus()) assert corpus.successes == 36 assert corpus.failures == 3 @pytest.mark.skipif(not whole_corpus(), reason="Need to set oracc_corpus_path to point " "to the whole corpus, which is not bundled with " "pyoracc") @slow def test_whole(): corpus = Corpus(source=whole_corpus()) assert corpus.successes == 2477 assert corpus.failures == 391
import pytest from ...model.corpus import Corpus from ..fixtures import tiny_corpus, sample_corpus, whole_corpus slow = pytest.mark.skipif( not pytest.config.getoption("--runslow"), reason="need --runslow option to run" ) def test_tiny(): corpus = Corpus(source=tiny_corpus()) assert corpus.successes == 1 assert corpus.failures == 1 @slow def test_sample(): corpus = Corpus(source=sample_corpus()) assert corpus.successes == 36 assert corpus.failures == 3 @pytest.mark.skipif(not whole_corpus(), reason="Need to set oracc_corpus_path to point " "to the whole corpus, which is not bundled with " "pyoracc") @slow def test_whole(): corpus = Corpus(source=whole_corpus()) # there is a total of 2868 files in the corpus assert corpus.successes == 2477 assert corpus.failures == 391
Comment about number of tests
Comment about number of tests
Python
mit
UCL/pyoracc
import pytest from ...model.corpus import Corpus from ..fixtures import tiny_corpus, sample_corpus, whole_corpus slow = pytest.mark.skipif( not pytest.config.getoption("--runslow"), reason="need --runslow option to run" ) def test_tiny(): corpus = Corpus(source=tiny_corpus()) assert corpus.successes == 1 assert corpus.failures == 1 @slow def test_sample(): corpus = Corpus(source=sample_corpus()) assert corpus.successes == 36 assert corpus.failures == 3 @pytest.mark.skipif(not whole_corpus(), reason="Need to set oracc_corpus_path to point " "to the whole corpus, which is not bundled with " "pyoracc") @slow def test_whole(): corpus = Corpus(source=whole_corpus()) + # there is a total of 2868 files in the corpus assert corpus.successes == 2477 assert corpus.failures == 391
Comment about number of tests
## Code Before: import pytest from ...model.corpus import Corpus from ..fixtures import tiny_corpus, sample_corpus, whole_corpus slow = pytest.mark.skipif( not pytest.config.getoption("--runslow"), reason="need --runslow option to run" ) def test_tiny(): corpus = Corpus(source=tiny_corpus()) assert corpus.successes == 1 assert corpus.failures == 1 @slow def test_sample(): corpus = Corpus(source=sample_corpus()) assert corpus.successes == 36 assert corpus.failures == 3 @pytest.mark.skipif(not whole_corpus(), reason="Need to set oracc_corpus_path to point " "to the whole corpus, which is not bundled with " "pyoracc") @slow def test_whole(): corpus = Corpus(source=whole_corpus()) assert corpus.successes == 2477 assert corpus.failures == 391 ## Instruction: Comment about number of tests ## Code After: import pytest from ...model.corpus import Corpus from ..fixtures import tiny_corpus, sample_corpus, whole_corpus slow = pytest.mark.skipif( not pytest.config.getoption("--runslow"), reason="need --runslow option to run" ) def test_tiny(): corpus = Corpus(source=tiny_corpus()) assert corpus.successes == 1 assert corpus.failures == 1 @slow def test_sample(): corpus = Corpus(source=sample_corpus()) assert corpus.successes == 36 assert corpus.failures == 3 @pytest.mark.skipif(not whole_corpus(), reason="Need to set oracc_corpus_path to point " "to the whole corpus, which is not bundled with " "pyoracc") @slow def test_whole(): corpus = Corpus(source=whole_corpus()) # there is a total of 2868 files in the corpus assert corpus.successes == 2477 assert corpus.failures == 391
# ... existing code ... corpus = Corpus(source=whole_corpus()) # there is a total of 2868 files in the corpus assert corpus.successes == 2477 # ... rest of the code ...
394954fc80230e01112166db4fe133c107febead
gitautodeploy/parsers/common.py
gitautodeploy/parsers/common.py
class WebhookRequestParser(object): """Abstract parent class for git service parsers. Contains helper methods.""" def __init__(self, config): self._config = config def get_matching_repo_configs(self, urls): """Iterates over the various repo URLs provided as argument (git://, ssh:// and https:// for the repo) and compare them to any repo URL specified in the config""" configs = [] for url in urls: for repo_config in self._config['repositories']: if repo_config in configs: continue if repo_config['url'] == url: configs.append(repo_config) elif 'url_without_usernme' in repo_config and repo_config['url_without_usernme'] == url: configs.append(repo_config) return configs
class WebhookRequestParser(object): """Abstract parent class for git service parsers. Contains helper methods.""" def __init__(self, config): self._config = config def get_matching_repo_configs(self, urls): """Iterates over the various repo URLs provided as argument (git://, ssh:// and https:// for the repo) and compare them to any repo URL specified in the config""" configs = [] for url in urls: for repo_config in self._config['repositories']: if repo_config in configs: continue if repo_config.get('repo', repo_config.get('url')) == url: configs.append(repo_config) elif 'url_without_usernme' in repo_config and repo_config['url_without_usernme'] == url: configs.append(repo_config) return configs
Allow more than one GitHub repo from the same user
Allow more than one GitHub repo from the same user GitHub does not allow the same SSH key to be used for multiple repositories on the same server belonging to the same user, see: http://snipe.net/2013/04/multiple-github-deploy-keys-single-server The fix there doesn't work because the "url" field is used both to get the repo and to identify it when a push comes in. Using a local SSH name for the repo works for getting the repo but then the name in the push doesn't match. This patch adds a 'repo' option that that can be set to the name of the repo as given in the push. If 'repo' is not set the behaviour is unchanged. Example: "url": "git@repo-a-shortname/somerepo.git" "repo": "[email protected]/somerepo.git"
Python
mit
evoja/docker-Github-Gitlab-Auto-Deploy,evoja/docker-Github-Gitlab-Auto-Deploy
class WebhookRequestParser(object): """Abstract parent class for git service parsers. Contains helper methods.""" def __init__(self, config): self._config = config def get_matching_repo_configs(self, urls): """Iterates over the various repo URLs provided as argument (git://, ssh:// and https:// for the repo) and compare them to any repo URL specified in the config""" configs = [] for url in urls: for repo_config in self._config['repositories']: if repo_config in configs: continue - if repo_config['url'] == url: + if repo_config.get('repo', repo_config.get('url')) == url: configs.append(repo_config) elif 'url_without_usernme' in repo_config and repo_config['url_without_usernme'] == url: configs.append(repo_config) return configs +
Allow more than one GitHub repo from the same user
## Code Before: class WebhookRequestParser(object): """Abstract parent class for git service parsers. Contains helper methods.""" def __init__(self, config): self._config = config def get_matching_repo_configs(self, urls): """Iterates over the various repo URLs provided as argument (git://, ssh:// and https:// for the repo) and compare them to any repo URL specified in the config""" configs = [] for url in urls: for repo_config in self._config['repositories']: if repo_config in configs: continue if repo_config['url'] == url: configs.append(repo_config) elif 'url_without_usernme' in repo_config and repo_config['url_without_usernme'] == url: configs.append(repo_config) return configs ## Instruction: Allow more than one GitHub repo from the same user ## Code After: class WebhookRequestParser(object): """Abstract parent class for git service parsers. Contains helper methods.""" def __init__(self, config): self._config = config def get_matching_repo_configs(self, urls): """Iterates over the various repo URLs provided as argument (git://, ssh:// and https:// for the repo) and compare them to any repo URL specified in the config""" configs = [] for url in urls: for repo_config in self._config['repositories']: if repo_config in configs: continue if repo_config.get('repo', repo_config.get('url')) == url: configs.append(repo_config) elif 'url_without_usernme' in repo_config and repo_config['url_without_usernme'] == url: configs.append(repo_config) return configs
// ... existing code ... continue if repo_config.get('repo', repo_config.get('url')) == url: configs.append(repo_config) // ... rest of the code ...
22c7da6d3de76cf6c36b4206f204a9ee979ba5f7
strides/graphs.py
strides/graphs.py
import pandas as pd import matplotlib matplotlib.use("pdf") import matplotlib.pyplot as plt import sys import os.path figdir = "figures" df = pd.read_csv(sys.stdin, " ", header=None, index_col=0, names=[2**(i) for i in range(6)]+["rand"]) print(df) #print(df["X2"]/2**df.index) df.plot(logy=True) plt.title("run time for array access") plt.xlabel("scale") plt.ylabel("seconds") plt.savefig(os.path.join([figdir,"graph.pdf"])) plt.figure() sizes = 2**df.index print(sizes) petf = (df.T/sizes).T print( petf ) petf.plot(logy=True) plt.title("normalized running time") plt.xlabel("scale") plt.ylabel("nanoseconds per element") plt.savefig(os.path.join([figdir,"perelement.pdf"]))
import pandas as pd import matplotlib matplotlib.use("pdf") import matplotlib.pyplot as plt import sys df = pd.read_csv(sys.stdin, " ", header=None, index_col=0) print(df) print(df["X2"]/2**df.index) df.plot(logy=True) plt.savefig("graph.pdf")
Add perelement figures write figures into subdirectory
Add perelement figures write figures into subdirectory
Python
bsd-3-clause
jpfairbanks/cse6140,jpfairbanks/cse6140,jpfairbanks/cse6140
import pandas as pd import matplotlib matplotlib.use("pdf") import matplotlib.pyplot as plt import sys - import os.path - figdir = "figures" + df = pd.read_csv(sys.stdin, " ", header=None, index_col=0) + print(df) + print(df["X2"]/2**df.index) + df.plot(logy=True) + plt.savefig("graph.pdf") - df = pd.read_csv(sys.stdin, " ", header=None, index_col=0, - names=[2**(i) for i in range(6)]+["rand"]) - print(df) - #print(df["X2"]/2**df.index) - df.plot(logy=True) - plt.title("run time for array access") - plt.xlabel("scale") - plt.ylabel("seconds") - plt.savefig(os.path.join([figdir,"graph.pdf"])) - - plt.figure() - sizes = 2**df.index - print(sizes) - petf = (df.T/sizes).T - print( petf ) - petf.plot(logy=True) - plt.title("normalized running time") - plt.xlabel("scale") - plt.ylabel("nanoseconds per element") - plt.savefig(os.path.join([figdir,"perelement.pdf"])) -
Add perelement figures write figures into subdirectory
## Code Before: import pandas as pd import matplotlib matplotlib.use("pdf") import matplotlib.pyplot as plt import sys import os.path figdir = "figures" df = pd.read_csv(sys.stdin, " ", header=None, index_col=0, names=[2**(i) for i in range(6)]+["rand"]) print(df) #print(df["X2"]/2**df.index) df.plot(logy=True) plt.title("run time for array access") plt.xlabel("scale") plt.ylabel("seconds") plt.savefig(os.path.join([figdir,"graph.pdf"])) plt.figure() sizes = 2**df.index print(sizes) petf = (df.T/sizes).T print( petf ) petf.plot(logy=True) plt.title("normalized running time") plt.xlabel("scale") plt.ylabel("nanoseconds per element") plt.savefig(os.path.join([figdir,"perelement.pdf"])) ## Instruction: Add perelement figures write figures into subdirectory ## Code After: import pandas as pd import matplotlib matplotlib.use("pdf") import matplotlib.pyplot as plt import sys df = pd.read_csv(sys.stdin, " ", header=None, index_col=0) print(df) print(df["X2"]/2**df.index) df.plot(logy=True) plt.savefig("graph.pdf")
// ... existing code ... import sys df = pd.read_csv(sys.stdin, " ", header=None, index_col=0) print(df) print(df["X2"]/2**df.index) df.plot(logy=True) plt.savefig("graph.pdf") // ... rest of the code ...
0261a0f9a1dde9f9f6167e3630561219e3dca124
statsmodels/datasets/__init__.py
statsmodels/datasets/__init__.py
#__all__ = filter(lambda s:not s.startswith('_'),dir()) import anes96, cancer, committee, ccard, copper, cpunish, elnino, grunfeld, longley, \ macrodata, nile, randhie, scotland, spector, stackloss, star98, \ strikes, sunspots, fair, heart, statecrime
#__all__ = filter(lambda s:not s.startswith('_'),dir()) from . import (anes96, cancer, committee, ccard, copper, cpunish, elnino, grunfeld, longley, macrodata, nile, randhie, scotland, spector, stackloss, star98, strikes, sunspots, fair, heart, statecrime)
Switch to relative imports and fix pep-8
STY: Switch to relative imports and fix pep-8
Python
bsd-3-clause
bsipocz/statsmodels,bsipocz/statsmodels,bsipocz/statsmodels,hlin117/statsmodels,bashtage/statsmodels,nguyentu1602/statsmodels,hlin117/statsmodels,musically-ut/statsmodels,yl565/statsmodels,jstoxrocky/statsmodels,wwf5067/statsmodels,bert9bert/statsmodels,nvoron23/statsmodels,bert9bert/statsmodels,astocko/statsmodels,jseabold/statsmodels,YihaoLu/statsmodels,hainm/statsmodels,ChadFulton/statsmodels,bert9bert/statsmodels,kiyoto/statsmodels,astocko/statsmodels,DonBeo/statsmodels,DonBeo/statsmodels,alekz112/statsmodels,waynenilsen/statsmodels,phobson/statsmodels,rgommers/statsmodels,nguyentu1602/statsmodels,josef-pkt/statsmodels,gef756/statsmodels,Averroes/statsmodels,phobson/statsmodels,statsmodels/statsmodels,yl565/statsmodels,statsmodels/statsmodels,adammenges/statsmodels,wdurhamh/statsmodels,cbmoore/statsmodels,edhuckle/statsmodels,adammenges/statsmodels,jstoxrocky/statsmodels,alekz112/statsmodels,rgommers/statsmodels,wwf5067/statsmodels,waynenilsen/statsmodels,huongttlan/statsmodels,bavardage/statsmodels,yarikoptic/pystatsmodels,jstoxrocky/statsmodels,musically-ut/statsmodels,ChadFulton/statsmodels,statsmodels/statsmodels,wdurhamh/statsmodels,huongttlan/statsmodels,hainm/statsmodels,bashtage/statsmodels,bzero/statsmodels,wzbozon/statsmodels,Averroes/statsmodels,josef-pkt/statsmodels,alekz112/statsmodels,musically-ut/statsmodels,cbmoore/statsmodels,waynenilsen/statsmodels,gef756/statsmodels,wkfwkf/statsmodels,wzbozon/statsmodels,saketkc/statsmodels,josef-pkt/statsmodels,detrout/debian-statsmodels,astocko/statsmodels,wzbozon/statsmodels,yl565/statsmodels,adammenges/statsmodels,hlin117/statsmodels,detrout/debian-statsmodels,bzero/statsmodels,kiyoto/statsmodels,yl565/statsmodels,alekz112/statsmodels,bavardage/statsmodels,nvoron23/statsmodels,YihaoLu/statsmodels,bashtage/statsmodels,hainm/statsmodels,rgommers/statsmodels,YihaoLu/statsmodels,bsipocz/statsmodels,ChadFulton/statsmodels,wkfwkf/statsmodels,astocko/statsmodels,DonBeo/statsmodels,edhuckle/statsmodels,kiyoto/statsmodels,josef-pkt/statsmodels,wkfwkf/statsmodels,josef-pkt/statsmodels,yl565/statsmodels,saketkc/statsmodels,musically-ut/statsmodels,jseabold/statsmodels,bavardage/statsmodels,huongttlan/statsmodels,rgommers/statsmodels,statsmodels/statsmodels,bzero/statsmodels,nvoron23/statsmodels,statsmodels/statsmodels,DonBeo/statsmodels,ChadFulton/statsmodels,edhuckle/statsmodels,bashtage/statsmodels,wwf5067/statsmodels,wdurhamh/statsmodels,nvoron23/statsmodels,detrout/debian-statsmodels,edhuckle/statsmodels,jseabold/statsmodels,nguyentu1602/statsmodels,saketkc/statsmodels,kiyoto/statsmodels,adammenges/statsmodels,ChadFulton/statsmodels,jseabold/statsmodels,DonBeo/statsmodels,bert9bert/statsmodels,cbmoore/statsmodels,saketkc/statsmodels,hlin117/statsmodels,YihaoLu/statsmodels,bzero/statsmodels,phobson/statsmodels,nvoron23/statsmodels,Averroes/statsmodels,josef-pkt/statsmodels,bavardage/statsmodels,wkfwkf/statsmodels,wdurhamh/statsmodels,gef756/statsmodels,bzero/statsmodels,edhuckle/statsmodels,bashtage/statsmodels,detrout/debian-statsmodels,wzbozon/statsmodels,phobson/statsmodels,nguyentu1602/statsmodels,Averroes/statsmodels,gef756/statsmodels,wwf5067/statsmodels,wkfwkf/statsmodels,huongttlan/statsmodels,YihaoLu/statsmodels,phobson/statsmodels,statsmodels/statsmodels,jseabold/statsmodels,wzbozon/statsmodels,bavardage/statsmodels,waynenilsen/statsmodels,cbmoore/statsmodels,cbmoore/statsmodels,jstoxrocky/statsmodels,hainm/statsmodels,ChadFulton/statsmodels,bashtage/statsmodels,bert9bert/statsmodels,kiyoto/statsmodels,saketkc/statsmodels,yarikoptic/pystatsmodels,wdurhamh/statsmodels,gef756/statsmodels,rgommers/statsmodels,yarikoptic/pystatsmodels
#__all__ = filter(lambda s:not s.startswith('_'),dir()) - import anes96, cancer, committee, ccard, copper, cpunish, elnino, grunfeld, longley, \ + from . import (anes96, cancer, committee, ccard, copper, cpunish, elnino, - macrodata, nile, randhie, scotland, spector, stackloss, star98, \ + grunfeld, longley, macrodata, nile, randhie, scotland, spector, - strikes, sunspots, fair, heart, statecrime + stackloss, star98, strikes, sunspots, fair, heart, statecrime) -
Switch to relative imports and fix pep-8
## Code Before: #__all__ = filter(lambda s:not s.startswith('_'),dir()) import anes96, cancer, committee, ccard, copper, cpunish, elnino, grunfeld, longley, \ macrodata, nile, randhie, scotland, spector, stackloss, star98, \ strikes, sunspots, fair, heart, statecrime ## Instruction: Switch to relative imports and fix pep-8 ## Code After: #__all__ = filter(lambda s:not s.startswith('_'),dir()) from . import (anes96, cancer, committee, ccard, copper, cpunish, elnino, grunfeld, longley, macrodata, nile, randhie, scotland, spector, stackloss, star98, strikes, sunspots, fair, heart, statecrime)
... #__all__ = filter(lambda s:not s.startswith('_'),dir()) from . import (anes96, cancer, committee, ccard, copper, cpunish, elnino, grunfeld, longley, macrodata, nile, randhie, scotland, spector, stackloss, star98, strikes, sunspots, fair, heart, statecrime) ...
6319303c93af973718c5e26c4d6b1d47310ff804
install_deps.py
install_deps.py
from __future__ import (absolute_import, division, print_function, unicode_literals) import sys import fileinput import subprocess from pip.req import parse_requirements def get_requirements(*args): """Parse all requirements files given and return a list of the dependencies""" install_deps = [] try: for fpath in args: install_deps.extend([str(d.req) for d in parse_requirements(fpath)]) except: print('Error reading {} file looking for dependencies.'.format(fpath)) return install_deps if __name__ == '__main__': for line in fileinput.input(): req_filepaths = sys.argv[1:] deps = get_requirements(*req_filepaths) try: for dep_name in deps: if dep_name == 'None': continue cmd = "pip install {0}".format(dep_name) print('#', cmd) subprocess.check_call(cmd, shell=True) except: print('Error installing {}'.format(dep_name))
from __future__ import (absolute_import, division, print_function, unicode_literals) import sys import fileinput import subprocess from pip.req import parse_requirements def get_requirements(*args): """Parse all requirements files given and return a list of the dependencies""" install_deps = [] try: for fpath in args: install_deps.extend([str(d.req) for d in parse_requirements(fpath)]) except: print('Error reading {} file looking for dependencies.'.format(fpath)) return [dep for dep in install_deps if dep != 'None'] if __name__ == '__main__': for line in fileinput.input(): req_filepaths = sys.argv[1:] deps = get_requirements(*req_filepaths) try: for dep_name in deps: cmd = "pip install {0}".format(dep_name) print('#', cmd) subprocess.check_call(cmd, shell=True) except: print('Error installing {}'.format(dep_name))
Correct for None appearing in requirements list
Correct for None appearing in requirements list
Python
bsd-3-clause
Neurita/galton
from __future__ import (absolute_import, division, print_function, unicode_literals) import sys import fileinput import subprocess from pip.req import parse_requirements def get_requirements(*args): """Parse all requirements files given and return a list of the dependencies""" install_deps = [] try: for fpath in args: install_deps.extend([str(d.req) for d in parse_requirements(fpath)]) except: print('Error reading {} file looking for dependencies.'.format(fpath)) - return install_deps + return [dep for dep in install_deps if dep != 'None'] if __name__ == '__main__': for line in fileinput.input(): req_filepaths = sys.argv[1:] deps = get_requirements(*req_filepaths) try: for dep_name in deps: - if dep_name == 'None': - continue - cmd = "pip install {0}".format(dep_name) print('#', cmd) subprocess.check_call(cmd, shell=True) except: print('Error installing {}'.format(dep_name))
Correct for None appearing in requirements list
## Code Before: from __future__ import (absolute_import, division, print_function, unicode_literals) import sys import fileinput import subprocess from pip.req import parse_requirements def get_requirements(*args): """Parse all requirements files given and return a list of the dependencies""" install_deps = [] try: for fpath in args: install_deps.extend([str(d.req) for d in parse_requirements(fpath)]) except: print('Error reading {} file looking for dependencies.'.format(fpath)) return install_deps if __name__ == '__main__': for line in fileinput.input(): req_filepaths = sys.argv[1:] deps = get_requirements(*req_filepaths) try: for dep_name in deps: if dep_name == 'None': continue cmd = "pip install {0}".format(dep_name) print('#', cmd) subprocess.check_call(cmd, shell=True) except: print('Error installing {}'.format(dep_name)) ## Instruction: Correct for None appearing in requirements list ## Code After: from __future__ import (absolute_import, division, print_function, unicode_literals) import sys import fileinput import subprocess from pip.req import parse_requirements def get_requirements(*args): """Parse all requirements files given and return a list of the dependencies""" install_deps = [] try: for fpath in args: install_deps.extend([str(d.req) for d in parse_requirements(fpath)]) except: print('Error reading {} file looking for dependencies.'.format(fpath)) return [dep for dep in install_deps if dep != 'None'] if __name__ == '__main__': for line in fileinput.input(): req_filepaths = sys.argv[1:] deps = get_requirements(*req_filepaths) try: for dep_name in deps: cmd = "pip install {0}".format(dep_name) print('#', cmd) subprocess.check_call(cmd, shell=True) except: print('Error installing {}'.format(dep_name))
// ... existing code ... return [dep for dep in install_deps if dep != 'None'] // ... modified code ... for dep_name in deps: cmd = "pip install {0}".format(dep_name) // ... rest of the code ...
169d32333aa3152dcec893f2ce58c46d614aaea4
models/employees.py
models/employees.py
import datetime from openedoo.core.libs.tools import hashing_werkzeug from openedoo_project import db from .users import User class Employee(User): @classmethod def is_exist(self, username): employee = self.query.get(username=username).first() return employee @classmethod def get_public_list(self): employees = self.query.with_entities(self.username, self.fullname, self.nip) return employees @classmethod def check_records(self): employees = self.query.limit(1).all() return employees @classmethod def add(self, form={}): if not form: raise ValueError('Form is supplied with wrong data.') data = { 'username': form['username'], 'fullname': form['fullname'], 'password': hashing_werkzeug(form['password']), 'nip': form['nip'], 'created': datetime.datetime.now() } employeeData = self(data) db.session.add(employeeData) return db.session.commit()
import datetime from openedoo.core.libs.tools import hashing_werkzeug from openedoo_project import db from .users import User class Employee(User): @classmethod def is_exist(self, username): employee = self.query.get(username=username).first() return employee @classmethod def get_public_list(self): employees = self.query.with_entities(self.username, self.fullname, self.nip) return employees @classmethod def check_records(self): employees = self.query.limit(1).all() return employees @classmethod def add(self, form=None): data = { 'username': form['username'], 'fullname': form['fullname'], 'password': hashing_werkzeug(form['password']), 'nip': form['nip'], 'created': datetime.datetime.now() } employeeData = self(data) db.session.add(employeeData) return db.session.commit()
Fix Dangerous default value {} as argument, pylint.
Fix Dangerous default value {} as argument, pylint.
Python
mit
openedoo/module_employee,openedoo/module_employee,openedoo/module_employee
import datetime from openedoo.core.libs.tools import hashing_werkzeug from openedoo_project import db from .users import User class Employee(User): @classmethod def is_exist(self, username): employee = self.query.get(username=username).first() return employee @classmethod def get_public_list(self): employees = self.query.with_entities(self.username, self.fullname, self.nip) return employees @classmethod def check_records(self): employees = self.query.limit(1).all() return employees @classmethod - def add(self, form={}): + def add(self, form=None): - if not form: - raise ValueError('Form is supplied with wrong data.') - data = { 'username': form['username'], 'fullname': form['fullname'], 'password': hashing_werkzeug(form['password']), 'nip': form['nip'], 'created': datetime.datetime.now() } employeeData = self(data) db.session.add(employeeData) return db.session.commit()
Fix Dangerous default value {} as argument, pylint.
## Code Before: import datetime from openedoo.core.libs.tools import hashing_werkzeug from openedoo_project import db from .users import User class Employee(User): @classmethod def is_exist(self, username): employee = self.query.get(username=username).first() return employee @classmethod def get_public_list(self): employees = self.query.with_entities(self.username, self.fullname, self.nip) return employees @classmethod def check_records(self): employees = self.query.limit(1).all() return employees @classmethod def add(self, form={}): if not form: raise ValueError('Form is supplied with wrong data.') data = { 'username': form['username'], 'fullname': form['fullname'], 'password': hashing_werkzeug(form['password']), 'nip': form['nip'], 'created': datetime.datetime.now() } employeeData = self(data) db.session.add(employeeData) return db.session.commit() ## Instruction: Fix Dangerous default value {} as argument, pylint. ## Code After: import datetime from openedoo.core.libs.tools import hashing_werkzeug from openedoo_project import db from .users import User class Employee(User): @classmethod def is_exist(self, username): employee = self.query.get(username=username).first() return employee @classmethod def get_public_list(self): employees = self.query.with_entities(self.username, self.fullname, self.nip) return employees @classmethod def check_records(self): employees = self.query.limit(1).all() return employees @classmethod def add(self, form=None): data = { 'username': form['username'], 'fullname': form['fullname'], 'password': hashing_werkzeug(form['password']), 'nip': form['nip'], 'created': datetime.datetime.now() } employeeData = self(data) db.session.add(employeeData) return db.session.commit()
// ... existing code ... @classmethod def add(self, form=None): data = { // ... rest of the code ...
4ecd19f7a1a36a424021e42c64fb273d7591ef1f
haas/plugin_manager.py
haas/plugin_manager.py
from __future__ import absolute_import, unicode_literals from .utils import find_module_by_name class PluginManager(object): def load_plugin_class(self, class_spec): if class_spec is None: return None try: module, module_attributes = find_module_by_name(class_spec) except ImportError: return None if len(module_attributes) != 1: return None klass = getattr(module, module_attributes[0], None) if klass is None: return None return klass def load_plugin(self, class_spec): klass = self.load_plugin_class(class_spec) if klass is None: return None return klass()
from __future__ import absolute_import, unicode_literals import logging from .utils import get_module_by_name logger = logging.getLogger(__name__) class PluginError(Exception): pass class PluginManager(object): def load_plugin_class(self, class_spec): if class_spec is None or '.' not in class_spec: msg = 'Malformed plugin factory specification {0!r}'.format( class_spec) logger.error(msg) raise PluginError(msg) module_name, factory_name = class_spec.rsplit('.', 1) try: module = get_module_by_name(module_name) except ImportError: msg = 'Unable to import {0!r}'.format(class_spec) logger.exception(msg) raise PluginError(msg) try: klass = getattr(module, factory_name) except AttributeError: msg = 'Module %r has no attribute {0!r}'.format( module.__name__, factory_name) logger.error(msg) raise PluginError(msg) return klass def load_plugin(self, class_spec): if class_spec is None: return None klass = self.load_plugin_class(class_spec) return klass()
Add logging and raise exceptions when loading plugin factories
Add logging and raise exceptions when loading plugin factories
Python
bsd-3-clause
sjagoe/haas,itziakos/haas,sjagoe/haas,scalative/haas,itziakos/haas,scalative/haas
from __future__ import absolute_import, unicode_literals + import logging + - from .utils import find_module_by_name + from .utils import get_module_by_name + + logger = logging.getLogger(__name__) + + + class PluginError(Exception): + + pass class PluginManager(object): def load_plugin_class(self, class_spec): - if class_spec is None: - return None + if class_spec is None or '.' not in class_spec: + msg = 'Malformed plugin factory specification {0!r}'.format( + class_spec) + logger.error(msg) + raise PluginError(msg) + module_name, factory_name = class_spec.rsplit('.', 1) try: - module, module_attributes = find_module_by_name(class_spec) + module = get_module_by_name(module_name) except ImportError: - return None - if len(module_attributes) != 1: - return None - klass = getattr(module, module_attributes[0], None) - if klass is None: - return None + msg = 'Unable to import {0!r}'.format(class_spec) + logger.exception(msg) + raise PluginError(msg) + try: + klass = getattr(module, factory_name) + except AttributeError: + msg = 'Module %r has no attribute {0!r}'.format( + module.__name__, factory_name) + logger.error(msg) + raise PluginError(msg) return klass def load_plugin(self, class_spec): + if class_spec is None: + return None klass = self.load_plugin_class(class_spec) - if klass is None: - return None return klass()
Add logging and raise exceptions when loading plugin factories
## Code Before: from __future__ import absolute_import, unicode_literals from .utils import find_module_by_name class PluginManager(object): def load_plugin_class(self, class_spec): if class_spec is None: return None try: module, module_attributes = find_module_by_name(class_spec) except ImportError: return None if len(module_attributes) != 1: return None klass = getattr(module, module_attributes[0], None) if klass is None: return None return klass def load_plugin(self, class_spec): klass = self.load_plugin_class(class_spec) if klass is None: return None return klass() ## Instruction: Add logging and raise exceptions when loading plugin factories ## Code After: from __future__ import absolute_import, unicode_literals import logging from .utils import get_module_by_name logger = logging.getLogger(__name__) class PluginError(Exception): pass class PluginManager(object): def load_plugin_class(self, class_spec): if class_spec is None or '.' not in class_spec: msg = 'Malformed plugin factory specification {0!r}'.format( class_spec) logger.error(msg) raise PluginError(msg) module_name, factory_name = class_spec.rsplit('.', 1) try: module = get_module_by_name(module_name) except ImportError: msg = 'Unable to import {0!r}'.format(class_spec) logger.exception(msg) raise PluginError(msg) try: klass = getattr(module, factory_name) except AttributeError: msg = 'Module %r has no attribute {0!r}'.format( module.__name__, factory_name) logger.error(msg) raise PluginError(msg) return klass def load_plugin(self, class_spec): if class_spec is None: return None klass = self.load_plugin_class(class_spec) return klass()
# ... existing code ... import logging from .utils import get_module_by_name logger = logging.getLogger(__name__) class PluginError(Exception): pass # ... modified code ... def load_plugin_class(self, class_spec): if class_spec is None or '.' not in class_spec: msg = 'Malformed plugin factory specification {0!r}'.format( class_spec) logger.error(msg) raise PluginError(msg) module_name, factory_name = class_spec.rsplit('.', 1) try: module = get_module_by_name(module_name) except ImportError: msg = 'Unable to import {0!r}'.format(class_spec) logger.exception(msg) raise PluginError(msg) try: klass = getattr(module, factory_name) except AttributeError: msg = 'Module %r has no attribute {0!r}'.format( module.__name__, factory_name) logger.error(msg) raise PluginError(msg) return klass ... def load_plugin(self, class_spec): if class_spec is None: return None klass = self.load_plugin_class(class_spec) return klass() # ... rest of the code ...
4bf01c350744e8cbf00750ec85d825f22e06dd29
linter.py
linter.py
from SublimeLinter.lint import Linter class Shellcheck(Linter): """Provides an interface to shellcheck.""" syntax = 'shell-unix-generic' cmd = 'shellcheck --format gcc -' regex = ( r'^.+?:(?P<line>\d+):(?P<col>\d+): ' r'(?:(?P<error>error)|(?P<warning>(warning|note))): ' r'(?P<message>.+)$' ) defaults = { '--exclude=,': '' } inline_overrides = 'exclude' comment_re = r'\s*#'
from SublimeLinter.lint import Linter class Shellcheck(Linter): """Provides an interface to shellcheck.""" syntax = ('shell-unix-generic', 'bash') cmd = 'shellcheck --format gcc -' regex = ( r'^.+?:(?P<line>\d+):(?P<col>\d+): ' r'(?:(?P<error>error)|(?P<warning>(warning|note))): ' r'(?P<message>.+)$' ) defaults = { '--exclude=,': '' } inline_overrides = 'exclude' comment_re = r'\s*#'
Handle new sublime syntax: bash
Handle new sublime syntax: bash
Python
mit
SublimeLinter/SublimeLinter-shellcheck
from SublimeLinter.lint import Linter class Shellcheck(Linter): """Provides an interface to shellcheck.""" - syntax = 'shell-unix-generic' + syntax = ('shell-unix-generic', 'bash') cmd = 'shellcheck --format gcc -' regex = ( r'^.+?:(?P<line>\d+):(?P<col>\d+): ' r'(?:(?P<error>error)|(?P<warning>(warning|note))): ' r'(?P<message>.+)$' ) defaults = { '--exclude=,': '' } inline_overrides = 'exclude' comment_re = r'\s*#'
Handle new sublime syntax: bash
## Code Before: from SublimeLinter.lint import Linter class Shellcheck(Linter): """Provides an interface to shellcheck.""" syntax = 'shell-unix-generic' cmd = 'shellcheck --format gcc -' regex = ( r'^.+?:(?P<line>\d+):(?P<col>\d+): ' r'(?:(?P<error>error)|(?P<warning>(warning|note))): ' r'(?P<message>.+)$' ) defaults = { '--exclude=,': '' } inline_overrides = 'exclude' comment_re = r'\s*#' ## Instruction: Handle new sublime syntax: bash ## Code After: from SublimeLinter.lint import Linter class Shellcheck(Linter): """Provides an interface to shellcheck.""" syntax = ('shell-unix-generic', 'bash') cmd = 'shellcheck --format gcc -' regex = ( r'^.+?:(?P<line>\d+):(?P<col>\d+): ' r'(?:(?P<error>error)|(?P<warning>(warning|note))): ' r'(?P<message>.+)$' ) defaults = { '--exclude=,': '' } inline_overrides = 'exclude' comment_re = r'\s*#'
... syntax = ('shell-unix-generic', 'bash') cmd = 'shellcheck --format gcc -' ...
1ae797e18286fd781797689a567f9d23ab3179d1
modules/tools.py
modules/tools.py
inf = infinity = float('inf') class Timer: def __init__(self, duration, *callbacks): self.duration = duration self.callbacks = list(callbacks) self.elapsed = 0 self.expired = False self.paused = False def register(self, callback): self.callbacks.append(callback) def unregister(self, callback): self.callbacks.remove(callback) def pause(self): self.paused = True def unpause(self): self.pause = False def update(self, time): if self.expired: return if self.elapsed > self.duration: return self.elapsed += time if self.elapsed > self.duration: self.expired = True for callback in self.callbacks: callback() def has_expired(self): return self.expired
inf = infinity = float('inf') class Timer: def __init__(self, duration, *callbacks): self.duration = duration self.callbacks = list(callbacks) self.elapsed = 0 self.expired = False self.paused = False def update(self, time): if self.expired: return if self.elapsed > self.duration: return self.elapsed += time if self.elapsed > self.duration: self.expired = True for callback in self.callbacks: callback() def restart(self): self.expired = False self.elapsed = 0 def pause(self): self.paused = True def unpause(self): self.pause = False def register(self, callback): self.callbacks.append(callback) def unregister(self, callback): self.callbacks.remove(callback) def has_expired(self): return self.expired
Add a restart() method to Timer.
Add a restart() method to Timer.
Python
mit
kxgames/kxg
inf = infinity = float('inf') class Timer: def __init__(self, duration, *callbacks): self.duration = duration self.callbacks = list(callbacks) self.elapsed = 0 self.expired = False self.paused = False - - def register(self, callback): - self.callbacks.append(callback) - - def unregister(self, callback): - self.callbacks.remove(callback) - - def pause(self): - self.paused = True - - def unpause(self): - self.pause = False def update(self, time): if self.expired: return if self.elapsed > self.duration: return self.elapsed += time if self.elapsed > self.duration: self.expired = True for callback in self.callbacks: callback() + def restart(self): + self.expired = False + self.elapsed = 0 + + def pause(self): + self.paused = True + + def unpause(self): + self.pause = False + + def register(self, callback): + self.callbacks.append(callback) + + def unregister(self, callback): + self.callbacks.remove(callback) + def has_expired(self): return self.expired
Add a restart() method to Timer.
## Code Before: inf = infinity = float('inf') class Timer: def __init__(self, duration, *callbacks): self.duration = duration self.callbacks = list(callbacks) self.elapsed = 0 self.expired = False self.paused = False def register(self, callback): self.callbacks.append(callback) def unregister(self, callback): self.callbacks.remove(callback) def pause(self): self.paused = True def unpause(self): self.pause = False def update(self, time): if self.expired: return if self.elapsed > self.duration: return self.elapsed += time if self.elapsed > self.duration: self.expired = True for callback in self.callbacks: callback() def has_expired(self): return self.expired ## Instruction: Add a restart() method to Timer. ## Code After: inf = infinity = float('inf') class Timer: def __init__(self, duration, *callbacks): self.duration = duration self.callbacks = list(callbacks) self.elapsed = 0 self.expired = False self.paused = False def update(self, time): if self.expired: return if self.elapsed > self.duration: return self.elapsed += time if self.elapsed > self.duration: self.expired = True for callback in self.callbacks: callback() def restart(self): self.expired = False self.elapsed = 0 def pause(self): self.paused = True def unpause(self): self.pause = False def register(self, callback): self.callbacks.append(callback) def unregister(self, callback): self.callbacks.remove(callback) def has_expired(self): return self.expired
# ... existing code ... self.paused = False # ... modified code ... def restart(self): self.expired = False self.elapsed = 0 def pause(self): self.paused = True def unpause(self): self.pause = False def register(self, callback): self.callbacks.append(callback) def unregister(self, callback): self.callbacks.remove(callback) def has_expired(self): # ... rest of the code ...
65fcfbfae9ef1a68d324aea932f983f7edd00cdf
mopidy/__init__.py
mopidy/__init__.py
import logging from mopidy import settings as raw_settings logger = logging.getLogger('mopidy') def get_version(): return u'0.1.dev' def get_mpd_protocol_version(): return u'0.16.0' def get_class(name): module_name = name[:name.rindex('.')] class_name = name[name.rindex('.') + 1:] logger.info('Loading: %s from %s', class_name, module_name) module = __import__(module_name, globals(), locals(), [class_name], -1) class_object = getattr(module, class_name) return class_object class SettingsError(Exception): pass class Settings(object): def __getattr__(self, attr): if not hasattr(raw_settings, attr): raise SettingsError(u'Setting "%s" is not set.' % attr) value = getattr(raw_settings, attr) if type(value) != bool and not value: raise SettingsError(u'Setting "%s" is empty.' % attr) return value settings = Settings()
import logging from multiprocessing.reduction import reduce_connection import pickle from mopidy import settings as raw_settings logger = logging.getLogger('mopidy') def get_version(): return u'0.1.dev' def get_mpd_protocol_version(): return u'0.16.0' def get_class(name): module_name = name[:name.rindex('.')] class_name = name[name.rindex('.') + 1:] logger.info('Loading: %s from %s', class_name, module_name) module = __import__(module_name, globals(), locals(), [class_name], -1) class_object = getattr(module, class_name) return class_object def pickle_connection(connection): return pickle.dumps(reduce_connection(connection)) def unpickle_connection(pickled_connection): # From http://stackoverflow.com/questions/1446004 unpickled = pickle.loads(pickled_connection) func = unpickled[0] args = unpickled[1] return func(*args) class SettingsError(Exception): pass class Settings(object): def __getattr__(self, attr): if not hasattr(raw_settings, attr): raise SettingsError(u'Setting "%s" is not set.' % attr) value = getattr(raw_settings, attr) if type(value) != bool and not value: raise SettingsError(u'Setting "%s" is empty.' % attr) return value settings = Settings()
Add util functions for pickling and unpickling multiprocessing.Connection
Add util functions for pickling and unpickling multiprocessing.Connection
Python
apache-2.0
SuperStarPL/mopidy,pacificIT/mopidy,swak/mopidy,hkariti/mopidy,dbrgn/mopidy,jmarsik/mopidy,diandiankan/mopidy,jmarsik/mopidy,glogiotatidis/mopidy,quartz55/mopidy,ali/mopidy,pacificIT/mopidy,adamcik/mopidy,rawdlite/mopidy,swak/mopidy,dbrgn/mopidy,jodal/mopidy,hkariti/mopidy,priestd09/mopidy,dbrgn/mopidy,jmarsik/mopidy,quartz55/mopidy,liamw9534/mopidy,mokieyue/mopidy,mokieyue/mopidy,tkem/mopidy,jcass77/mopidy,woutervanwijk/mopidy,dbrgn/mopidy,ali/mopidy,SuperStarPL/mopidy,woutervanwijk/mopidy,ali/mopidy,swak/mopidy,diandiankan/mopidy,ZenithDK/mopidy,abarisain/mopidy,kingosticks/mopidy,SuperStarPL/mopidy,quartz55/mopidy,bacontext/mopidy,hkariti/mopidy,vrs01/mopidy,ZenithDK/mopidy,vrs01/mopidy,glogiotatidis/mopidy,abarisain/mopidy,jodal/mopidy,adamcik/mopidy,rawdlite/mopidy,vrs01/mopidy,adamcik/mopidy,jcass77/mopidy,pacificIT/mopidy,glogiotatidis/mopidy,mokieyue/mopidy,rawdlite/mopidy,tkem/mopidy,jcass77/mopidy,jmarsik/mopidy,mopidy/mopidy,priestd09/mopidy,ZenithDK/mopidy,ali/mopidy,kingosticks/mopidy,tkem/mopidy,bencevans/mopidy,priestd09/mopidy,swak/mopidy,mopidy/mopidy,bacontext/mopidy,bencevans/mopidy,diandiankan/mopidy,mopidy/mopidy,pacificIT/mopidy,liamw9534/mopidy,SuperStarPL/mopidy,tkem/mopidy,vrs01/mopidy,bacontext/mopidy,bencevans/mopidy,quartz55/mopidy,bencevans/mopidy,diandiankan/mopidy,bacontext/mopidy,mokieyue/mopidy,hkariti/mopidy,glogiotatidis/mopidy,rawdlite/mopidy,ZenithDK/mopidy,jodal/mopidy,kingosticks/mopidy
import logging + from multiprocessing.reduction import reduce_connection + import pickle from mopidy import settings as raw_settings logger = logging.getLogger('mopidy') def get_version(): return u'0.1.dev' def get_mpd_protocol_version(): return u'0.16.0' def get_class(name): module_name = name[:name.rindex('.')] class_name = name[name.rindex('.') + 1:] logger.info('Loading: %s from %s', class_name, module_name) module = __import__(module_name, globals(), locals(), [class_name], -1) class_object = getattr(module, class_name) return class_object + def pickle_connection(connection): + return pickle.dumps(reduce_connection(connection)) + + def unpickle_connection(pickled_connection): + # From http://stackoverflow.com/questions/1446004 + unpickled = pickle.loads(pickled_connection) + func = unpickled[0] + args = unpickled[1] + return func(*args) + class SettingsError(Exception): pass class Settings(object): def __getattr__(self, attr): if not hasattr(raw_settings, attr): raise SettingsError(u'Setting "%s" is not set.' % attr) value = getattr(raw_settings, attr) if type(value) != bool and not value: raise SettingsError(u'Setting "%s" is empty.' % attr) return value settings = Settings()
Add util functions for pickling and unpickling multiprocessing.Connection
## Code Before: import logging from mopidy import settings as raw_settings logger = logging.getLogger('mopidy') def get_version(): return u'0.1.dev' def get_mpd_protocol_version(): return u'0.16.0' def get_class(name): module_name = name[:name.rindex('.')] class_name = name[name.rindex('.') + 1:] logger.info('Loading: %s from %s', class_name, module_name) module = __import__(module_name, globals(), locals(), [class_name], -1) class_object = getattr(module, class_name) return class_object class SettingsError(Exception): pass class Settings(object): def __getattr__(self, attr): if not hasattr(raw_settings, attr): raise SettingsError(u'Setting "%s" is not set.' % attr) value = getattr(raw_settings, attr) if type(value) != bool and not value: raise SettingsError(u'Setting "%s" is empty.' % attr) return value settings = Settings() ## Instruction: Add util functions for pickling and unpickling multiprocessing.Connection ## Code After: import logging from multiprocessing.reduction import reduce_connection import pickle from mopidy import settings as raw_settings logger = logging.getLogger('mopidy') def get_version(): return u'0.1.dev' def get_mpd_protocol_version(): return u'0.16.0' def get_class(name): module_name = name[:name.rindex('.')] class_name = name[name.rindex('.') + 1:] logger.info('Loading: %s from %s', class_name, module_name) module = __import__(module_name, globals(), locals(), [class_name], -1) class_object = getattr(module, class_name) return class_object def pickle_connection(connection): return pickle.dumps(reduce_connection(connection)) def unpickle_connection(pickled_connection): # From http://stackoverflow.com/questions/1446004 unpickled = pickle.loads(pickled_connection) func = unpickled[0] args = unpickled[1] return func(*args) class SettingsError(Exception): pass class Settings(object): def __getattr__(self, attr): if not hasattr(raw_settings, attr): raise SettingsError(u'Setting "%s" is not set.' % attr) value = getattr(raw_settings, attr) if type(value) != bool and not value: raise SettingsError(u'Setting "%s" is empty.' % attr) return value settings = Settings()
... import logging from multiprocessing.reduction import reduce_connection import pickle ... def pickle_connection(connection): return pickle.dumps(reduce_connection(connection)) def unpickle_connection(pickled_connection): # From http://stackoverflow.com/questions/1446004 unpickled = pickle.loads(pickled_connection) func = unpickled[0] args = unpickled[1] return func(*args) class SettingsError(Exception): ...
dd89173cc177f7130eca426eb4fa5737ec59c91d
test/vpp_mac.py
test/vpp_mac.py
from util import mactobinary class VppMacAddress(): def __init__(self, addr): self.address = addr def encode(self): return { 'bytes': self.bytes } @property def bytes(self): return mactobinary(self.address) @property def address(self): return self.addr.address def __str__(self): return self.address def __eq__(self, other): if isinstance(other, self.__class__): return self.address == other.addres elif hasattr(other, "bytes"): # vl_api_mac_addres_t return self.bytes == other.bytes else: raise Exception("Comparing VppMacAddress:%s" "with unknown type: %s" % (self, other)) return False
from util import mactobinary class VppMacAddress(): def __init__(self, addr): self.address = addr def encode(self): return { 'bytes': self.bytes } @property def bytes(self): return mactobinary(self.address) @property def address(self): return self.address @address.setter def address(self, value): self.address = value def __str__(self): return self.address def __eq__(self, other): if isinstance(other, self.__class__): return self.address == other.address elif hasattr(other, "bytes"): # vl_api_mac_addres_t return self.bytes == other.bytes else: raise TypeError("Comparing VppMacAddress:%s" "with unknown type: %s" % (self, other)) return False
Fix L2BD arp termination Test Case
Fix L2BD arp termination Test Case ============================================================================== L2BD arp termination Test Case ============================================================================== 12:02:21,850 Couldn't stat : /tmp/vpp-unittest-TestL2bdArpTerm-_h44qo/stats.sock L2BD arp term - add 5 hosts, verify arp responses OK L2BD arp term - delete 3 hosts, verify arp responses OK L2BD arp term - recreate BD1, readd 3 hosts, verify arp responses OK L2BD arp term - 2 IP4 addrs per host OK L2BD arp term - create and update 10 IP4-mac pairs OK L2BD arp/ND term - hosts with both ip4/ip6 OK L2BD ND term - Add and Del hosts, verify ND replies OK L2BD ND term - Add and update IP+mac, verify ND replies OK L2BD arp term - send garps, verify arp event reports OK L2BD arp term - send duplicate garps, verify suppression OK L2BD arp term - disable ip4 arp events,send garps, verify no events OK L2BD ND term - send NS packets verify reports OK L2BD ND term - send duplicate ns, verify suppression OK L2BD ND term - disable ip4 arp events,send ns, verify no events OK ============================================================================== TEST RESULTS: Scheduled tests: 14 Executed tests: 14 Passed tests: 14 ============================================================================== Test run was successful Change-Id: I6bb1ced11b88080ffaa845d22b0bc471c4f91683 Signed-off-by: Paul Vinciguerra <[email protected]>
Python
apache-2.0
chrisy/vpp,vpp-dev/vpp,FDio/vpp,FDio/vpp,FDio/vpp,FDio/vpp,chrisy/vpp,FDio/vpp,chrisy/vpp,vpp-dev/vpp,chrisy/vpp,vpp-dev/vpp,vpp-dev/vpp,vpp-dev/vpp,FDio/vpp,chrisy/vpp,chrisy/vpp,chrisy/vpp,vpp-dev/vpp,vpp-dev/vpp,FDio/vpp,chrisy/vpp,FDio/vpp
from util import mactobinary class VppMacAddress(): def __init__(self, addr): self.address = addr def encode(self): return { 'bytes': self.bytes } @property def bytes(self): return mactobinary(self.address) @property def address(self): - return self.addr.address + return self.address + + @address.setter + def address(self, value): + self.address = value def __str__(self): return self.address def __eq__(self, other): if isinstance(other, self.__class__): - return self.address == other.addres + return self.address == other.address elif hasattr(other, "bytes"): # vl_api_mac_addres_t return self.bytes == other.bytes else: - raise Exception("Comparing VppMacAddress:%s" + raise TypeError("Comparing VppMacAddress:%s" "with unknown type: %s" % (self, other)) return False
Fix L2BD arp termination Test Case
## Code Before: from util import mactobinary class VppMacAddress(): def __init__(self, addr): self.address = addr def encode(self): return { 'bytes': self.bytes } @property def bytes(self): return mactobinary(self.address) @property def address(self): return self.addr.address def __str__(self): return self.address def __eq__(self, other): if isinstance(other, self.__class__): return self.address == other.addres elif hasattr(other, "bytes"): # vl_api_mac_addres_t return self.bytes == other.bytes else: raise Exception("Comparing VppMacAddress:%s" "with unknown type: %s" % (self, other)) return False ## Instruction: Fix L2BD arp termination Test Case ## Code After: from util import mactobinary class VppMacAddress(): def __init__(self, addr): self.address = addr def encode(self): return { 'bytes': self.bytes } @property def bytes(self): return mactobinary(self.address) @property def address(self): return self.address @address.setter def address(self, value): self.address = value def __str__(self): return self.address def __eq__(self, other): if isinstance(other, self.__class__): return self.address == other.address elif hasattr(other, "bytes"): # vl_api_mac_addres_t return self.bytes == other.bytes else: raise TypeError("Comparing VppMacAddress:%s" "with unknown type: %s" % (self, other)) return False
// ... existing code ... def address(self): return self.address @address.setter def address(self, value): self.address = value // ... modified code ... if isinstance(other, self.__class__): return self.address == other.address elif hasattr(other, "bytes"): ... else: raise TypeError("Comparing VppMacAddress:%s" "with unknown type: %s" % // ... rest of the code ...
de9e8ab1a91e2a0e69971f9c23377f97e717b048
app/__init__.py
app/__init__.py
from app.main import bundle_app # noqa # NOTE: uncomment out while genrating migration # app = bundle_app({'MIGRATION': True})
import os from app.main import bundle_app # noqa # NOTE: uncomment out while genrating migration # app = bundle_app({'MIGRATION': True}) application = bundle_app({ 'CLI_OR_DEPLOY': True, 'GUNICORN': 'gunicorn' in os.environ.get('SERVER_SOFTWARE', '')}) # noqa
Add additional application for gunicorn.
Add additional application for gunicorn.
Python
mpl-2.0
mrf345/FQM,mrf345/FQM,mrf345/FQM,mrf345/FQM
+ import os from app.main import bundle_app # noqa # NOTE: uncomment out while genrating migration # app = bundle_app({'MIGRATION': True}) + application = bundle_app({ + 'CLI_OR_DEPLOY': True, + 'GUNICORN': 'gunicorn' in os.environ.get('SERVER_SOFTWARE', '')}) # noqa +
Add additional application for gunicorn.
## Code Before: from app.main import bundle_app # noqa # NOTE: uncomment out while genrating migration # app = bundle_app({'MIGRATION': True}) ## Instruction: Add additional application for gunicorn. ## Code After: import os from app.main import bundle_app # noqa # NOTE: uncomment out while genrating migration # app = bundle_app({'MIGRATION': True}) application = bundle_app({ 'CLI_OR_DEPLOY': True, 'GUNICORN': 'gunicorn' in os.environ.get('SERVER_SOFTWARE', '')}) # noqa
# ... existing code ... import os from app.main import bundle_app # noqa # ... modified code ... # app = bundle_app({'MIGRATION': True}) application = bundle_app({ 'CLI_OR_DEPLOY': True, 'GUNICORN': 'gunicorn' in os.environ.get('SERVER_SOFTWARE', '')}) # noqa # ... rest of the code ...
7f8455c9687e8c7750fe1cfcbfdf4fd720888012
iis/__init__.py
iis/__init__.py
import logging.config from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from flask_mail import Mail from flask_user import UserManager, SQLAlchemyAdapter from flask_bootstrap import Bootstrap def create_app(config: object) -> Flask: """Create the flask app. Can be called from testing contexts""" app = Flask(__name__) app.config.from_envvar('IIS_FLASK_SETTINGS') app.config.from_object(config) # Call app.logger to prevent it from clobbering configuration app.logger logging.config.dictConfig(app.config['LOGGING']) app.logger.info("App configured.") return app app = create_app(None) # Set up SQLAlchemy and Migrate db = SQLAlchemy(app) # type: SQLAlchemy migrate = Migrate(app, db) # Load Flask-Mail mail = Mail(app) # Set up bootstrap Bootstrap(app) # Configure user model for Flask-User from iis.models import User # noqa: E402 db_adapter = SQLAlchemyAdapter(db, User) user_manager = UserManager(db_adapter, app) from iis import views, models # noqa: E402, F401
import logging.config from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from flask_mail import Mail from flask_user import UserManager, SQLAlchemyAdapter from flask_bootstrap import Bootstrap import iis.jobs def create_app(config: object) -> Flask: """Create the flask app. Can be called from testing contexts""" app = Flask(__name__) app.config.from_envvar("IIS_FLASK_SETTINGS") app.config.from_object(config) # Register blueprints app.register_blueprint(iis.jobs.jobs, url_prefix="/jobs") # Call app.logger to prevent it from clobbering configuration app.logger logging.config.dictConfig(app.config["LOGGING"]) app.logger.info("App configured.") return app app = create_app(None) # Set up SQLAlchemy and Migrate db = SQLAlchemy(app) # type: SQLAlchemy migrate = Migrate(app, db) # Load Flask-Mail mail = Mail(app) # Set up bootstrap Bootstrap(app) # Configure user model for Flask-User from iis.models import User # noqa: E402 db_adapter = SQLAlchemyAdapter(db, User) user_manager = UserManager(db_adapter, app) from iis import views, models # noqa: E402, F401
Use '"' for string delimeter
Use '"' for string delimeter
Python
agpl-3.0
interactomix/iis,interactomix/iis
import logging.config from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from flask_mail import Mail from flask_user import UserManager, SQLAlchemyAdapter from flask_bootstrap import Bootstrap + import iis.jobs + def create_app(config: object) -> Flask: """Create the flask app. Can be called from testing contexts""" app = Flask(__name__) - app.config.from_envvar('IIS_FLASK_SETTINGS') + app.config.from_envvar("IIS_FLASK_SETTINGS") app.config.from_object(config) + + # Register blueprints + app.register_blueprint(iis.jobs.jobs, url_prefix="/jobs") # Call app.logger to prevent it from clobbering configuration app.logger - logging.config.dictConfig(app.config['LOGGING']) + logging.config.dictConfig(app.config["LOGGING"]) app.logger.info("App configured.") return app app = create_app(None) # Set up SQLAlchemy and Migrate db = SQLAlchemy(app) # type: SQLAlchemy migrate = Migrate(app, db) # Load Flask-Mail mail = Mail(app) # Set up bootstrap Bootstrap(app) # Configure user model for Flask-User from iis.models import User # noqa: E402 db_adapter = SQLAlchemyAdapter(db, User) user_manager = UserManager(db_adapter, app) from iis import views, models # noqa: E402, F401
Use '"' for string delimeter
## Code Before: import logging.config from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from flask_mail import Mail from flask_user import UserManager, SQLAlchemyAdapter from flask_bootstrap import Bootstrap def create_app(config: object) -> Flask: """Create the flask app. Can be called from testing contexts""" app = Flask(__name__) app.config.from_envvar('IIS_FLASK_SETTINGS') app.config.from_object(config) # Call app.logger to prevent it from clobbering configuration app.logger logging.config.dictConfig(app.config['LOGGING']) app.logger.info("App configured.") return app app = create_app(None) # Set up SQLAlchemy and Migrate db = SQLAlchemy(app) # type: SQLAlchemy migrate = Migrate(app, db) # Load Flask-Mail mail = Mail(app) # Set up bootstrap Bootstrap(app) # Configure user model for Flask-User from iis.models import User # noqa: E402 db_adapter = SQLAlchemyAdapter(db, User) user_manager = UserManager(db_adapter, app) from iis import views, models # noqa: E402, F401 ## Instruction: Use '"' for string delimeter ## Code After: import logging.config from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from flask_mail import Mail from flask_user import UserManager, SQLAlchemyAdapter from flask_bootstrap import Bootstrap import iis.jobs def create_app(config: object) -> Flask: """Create the flask app. Can be called from testing contexts""" app = Flask(__name__) app.config.from_envvar("IIS_FLASK_SETTINGS") app.config.from_object(config) # Register blueprints app.register_blueprint(iis.jobs.jobs, url_prefix="/jobs") # Call app.logger to prevent it from clobbering configuration app.logger logging.config.dictConfig(app.config["LOGGING"]) app.logger.info("App configured.") return app app = create_app(None) # Set up SQLAlchemy and Migrate db = SQLAlchemy(app) # type: SQLAlchemy migrate = Migrate(app, db) # Load Flask-Mail mail = Mail(app) # Set up bootstrap Bootstrap(app) # Configure user model for Flask-User from iis.models import User # noqa: E402 db_adapter = SQLAlchemyAdapter(db, User) user_manager = UserManager(db_adapter, app) from iis import views, models # noqa: E402, F401
... import iis.jobs ... app = Flask(__name__) app.config.from_envvar("IIS_FLASK_SETTINGS") app.config.from_object(config) # Register blueprints app.register_blueprint(iis.jobs.jobs, url_prefix="/jobs") ... app.logger logging.config.dictConfig(app.config["LOGGING"]) app.logger.info("App configured.") ...
e8c1ba2c63a1ea66aa2c08e606ac0614e6854565
interrupt.py
interrupt.py
import signal import sys from threading import Event def GetInterruptEvent(): e = Event() def signal_handler(signal, frame): print('You pressed Ctrl+C!') e.set() signal.signal(signal.SIGINT, signal_handler) return e
import signal import sys from threading import Event def GetInterruptEvent(): e = Event() def signal_handler(signal, frame): print('You pressed Ctrl+C!') e.set() signal.signal(signal.SIGINT, signal_handler) signal.signal(signal.SIGTERM, signal_handler) return e
Handle sigterm as well as sigint.
Handle sigterm as well as sigint.
Python
mit
rickbassham/videoencode,rickbassham/videoencode
import signal import sys from threading import Event def GetInterruptEvent(): e = Event() def signal_handler(signal, frame): print('You pressed Ctrl+C!') e.set() signal.signal(signal.SIGINT, signal_handler) + signal.signal(signal.SIGTERM, signal_handler) return e
Handle sigterm as well as sigint.
## Code Before: import signal import sys from threading import Event def GetInterruptEvent(): e = Event() def signal_handler(signal, frame): print('You pressed Ctrl+C!') e.set() signal.signal(signal.SIGINT, signal_handler) return e ## Instruction: Handle sigterm as well as sigint. ## Code After: import signal import sys from threading import Event def GetInterruptEvent(): e = Event() def signal_handler(signal, frame): print('You pressed Ctrl+C!') e.set() signal.signal(signal.SIGINT, signal_handler) signal.signal(signal.SIGTERM, signal_handler) return e
// ... existing code ... signal.signal(signal.SIGINT, signal_handler) signal.signal(signal.SIGTERM, signal_handler) // ... rest of the code ...
d89715196ba79da02a997688414dfa283bee5aeb
profiles/tests/test_views.py
profiles/tests/test_views.py
from django.core.urlresolvers import reverse from django.test import TestCase from django.test.client import RequestFactory from utils.factories import UserFactory from profiles.views import ProfileView class ProfileViewTests(TestCase): def setUp(self): request_factory = RequestFactory() request = request_factory.get(reverse('profile')) request.user = UserFactory.create() self.response = ProfileView.as_view()(request) def test_profile_view_200(self): self.assertEqual(self.response.status_code, 200) def test_profile_view_renders(self): self.response.render()
from django.core.urlresolvers import reverse from django.test import TestCase from django.test.client import RequestFactory from utils.factories import UserFactory from profiles.views import ( ProfileView, ReviewUserView, ) class ProfileViewTests(TestCase): def setUp(self): request_factory = RequestFactory() request = request_factory.get(reverse('profile')) request.user = UserFactory.create() self.response = ProfileView.as_view()(request) def test_profile_view_200(self): self.assertEqual(self.response.status_code, 200) def test_profile_view_renders(self): self.response.render() class ReviewUserViewTests(TestCase): def setUp(self): request_factory = RequestFactory() self.request = request_factory.get('/admin/dashboard/') def test_review_user_view_200(self): user = UserFactory.create() user.is_staff = True self.request.user = user response = ReviewUserView.as_view()(self.request) self.assertEqual(response.status_code, 200) def test_review_user_view_200(self): user = UserFactory.create() user.is_staff = True self.request.user = user response = ReviewUserView.as_view()(self.request) response.render() def test_review_user_view_not_staff(self): user = UserFactory.create() self.request.user = user response = ReviewUserView.as_view()(self.request) self.assertEqual(response.status_code, 302)
Add tests for user review view
Add tests for user review view
Python
mit
phildini/logtacts,phildini/logtacts,phildini/logtacts,phildini/logtacts,phildini/logtacts
from django.core.urlresolvers import reverse from django.test import TestCase from django.test.client import RequestFactory from utils.factories import UserFactory - from profiles.views import ProfileView + from profiles.views import ( + ProfileView, + ReviewUserView, + ) class ProfileViewTests(TestCase): def setUp(self): request_factory = RequestFactory() request = request_factory.get(reverse('profile')) request.user = UserFactory.create() self.response = ProfileView.as_view()(request) def test_profile_view_200(self): self.assertEqual(self.response.status_code, 200) def test_profile_view_renders(self): self.response.render() + + class ReviewUserViewTests(TestCase): + + def setUp(self): + request_factory = RequestFactory() + self.request = request_factory.get('/admin/dashboard/') + + def test_review_user_view_200(self): + user = UserFactory.create() + user.is_staff = True + self.request.user = user + response = ReviewUserView.as_view()(self.request) + self.assertEqual(response.status_code, 200) + + def test_review_user_view_200(self): + user = UserFactory.create() + user.is_staff = True + self.request.user = user + response = ReviewUserView.as_view()(self.request) + response.render() + + def test_review_user_view_not_staff(self): + user = UserFactory.create() + self.request.user = user + response = ReviewUserView.as_view()(self.request) + self.assertEqual(response.status_code, 302) +
Add tests for user review view
## Code Before: from django.core.urlresolvers import reverse from django.test import TestCase from django.test.client import RequestFactory from utils.factories import UserFactory from profiles.views import ProfileView class ProfileViewTests(TestCase): def setUp(self): request_factory = RequestFactory() request = request_factory.get(reverse('profile')) request.user = UserFactory.create() self.response = ProfileView.as_view()(request) def test_profile_view_200(self): self.assertEqual(self.response.status_code, 200) def test_profile_view_renders(self): self.response.render() ## Instruction: Add tests for user review view ## Code After: from django.core.urlresolvers import reverse from django.test import TestCase from django.test.client import RequestFactory from utils.factories import UserFactory from profiles.views import ( ProfileView, ReviewUserView, ) class ProfileViewTests(TestCase): def setUp(self): request_factory = RequestFactory() request = request_factory.get(reverse('profile')) request.user = UserFactory.create() self.response = ProfileView.as_view()(request) def test_profile_view_200(self): self.assertEqual(self.response.status_code, 200) def test_profile_view_renders(self): self.response.render() class ReviewUserViewTests(TestCase): def setUp(self): request_factory = RequestFactory() self.request = request_factory.get('/admin/dashboard/') def test_review_user_view_200(self): user = UserFactory.create() user.is_staff = True self.request.user = user response = ReviewUserView.as_view()(self.request) self.assertEqual(response.status_code, 200) def test_review_user_view_200(self): user = UserFactory.create() user.is_staff = True self.request.user = user response = ReviewUserView.as_view()(self.request) response.render() def test_review_user_view_not_staff(self): user = UserFactory.create() self.request.user = user response = ReviewUserView.as_view()(self.request) self.assertEqual(response.status_code, 302)
// ... existing code ... from profiles.views import ( ProfileView, ReviewUserView, ) // ... modified code ... self.response.render() class ReviewUserViewTests(TestCase): def setUp(self): request_factory = RequestFactory() self.request = request_factory.get('/admin/dashboard/') def test_review_user_view_200(self): user = UserFactory.create() user.is_staff = True self.request.user = user response = ReviewUserView.as_view()(self.request) self.assertEqual(response.status_code, 200) def test_review_user_view_200(self): user = UserFactory.create() user.is_staff = True self.request.user = user response = ReviewUserView.as_view()(self.request) response.render() def test_review_user_view_not_staff(self): user = UserFactory.create() self.request.user = user response = ReviewUserView.as_view()(self.request) self.assertEqual(response.status_code, 302) // ... rest of the code ...
dcdfe91570e185df19daef49be9a368276e20483
src/core/migrations/0039_fix_reviewer_url.py
src/core/migrations/0039_fix_reviewer_url.py
from __future__ import unicode_literals import re from django.db import migrations REGEX = re.compile("({%\ ?journal_url 'do_review' review_assignment.id\ ?%})") OUTPUT = "{{ review_url }}" def replace_template(apps, schema_editor): SettingValueTranslation = apps.get_model('core', 'SettingValueTranslation') settings = SettingValueTranslation.objects.all() for setting in settings: setting.value = re.sub(REGEX, OUTPUT, setting.value) setting.save() class Migration(migrations.Migration): dependencies = [ ('core', '0038_xslt_1-3-8'), ] operations = [ migrations.RunPython(replace_template, reverse_code=migrations.RunPython.noop) ]
from __future__ import unicode_literals import re from django.db import migrations REGEX = re.compile("({%\ ?journal_url 'do_review' review_assignment.id\ ?%})") OUTPUT = "{{ review_url }}" def replace_template(apps, schema_editor): SettingValueTranslation = apps.get_model('core', 'SettingValueTranslation') settings = SettingValueTranslation.objects.all() for setting in settings: if isinstance(setting.value, str): setting.value = re.sub(REGEX, OUTPUT, setting.value) setting.save() class Migration(migrations.Migration): dependencies = [ ('core', '0038_xslt_1-3-8'), ] operations = [ migrations.RunPython(replace_template, reverse_code=migrations.RunPython.noop) ]
Handle migrating non-string values (i.e.: NULL)
Handle migrating non-string values (i.e.: NULL)
Python
agpl-3.0
BirkbeckCTP/janeway,BirkbeckCTP/janeway,BirkbeckCTP/janeway,BirkbeckCTP/janeway
from __future__ import unicode_literals import re from django.db import migrations REGEX = re.compile("({%\ ?journal_url 'do_review' review_assignment.id\ ?%})") OUTPUT = "{{ review_url }}" def replace_template(apps, schema_editor): SettingValueTranslation = apps.get_model('core', 'SettingValueTranslation') settings = SettingValueTranslation.objects.all() for setting in settings: + if isinstance(setting.value, str): - setting.value = re.sub(REGEX, OUTPUT, setting.value) + setting.value = re.sub(REGEX, OUTPUT, setting.value) - setting.save() + setting.save() class Migration(migrations.Migration): dependencies = [ ('core', '0038_xslt_1-3-8'), ] operations = [ migrations.RunPython(replace_template, reverse_code=migrations.RunPython.noop) ]
Handle migrating non-string values (i.e.: NULL)
## Code Before: from __future__ import unicode_literals import re from django.db import migrations REGEX = re.compile("({%\ ?journal_url 'do_review' review_assignment.id\ ?%})") OUTPUT = "{{ review_url }}" def replace_template(apps, schema_editor): SettingValueTranslation = apps.get_model('core', 'SettingValueTranslation') settings = SettingValueTranslation.objects.all() for setting in settings: setting.value = re.sub(REGEX, OUTPUT, setting.value) setting.save() class Migration(migrations.Migration): dependencies = [ ('core', '0038_xslt_1-3-8'), ] operations = [ migrations.RunPython(replace_template, reverse_code=migrations.RunPython.noop) ] ## Instruction: Handle migrating non-string values (i.e.: NULL) ## Code After: from __future__ import unicode_literals import re from django.db import migrations REGEX = re.compile("({%\ ?journal_url 'do_review' review_assignment.id\ ?%})") OUTPUT = "{{ review_url }}" def replace_template(apps, schema_editor): SettingValueTranslation = apps.get_model('core', 'SettingValueTranslation') settings = SettingValueTranslation.objects.all() for setting in settings: if isinstance(setting.value, str): setting.value = re.sub(REGEX, OUTPUT, setting.value) setting.save() class Migration(migrations.Migration): dependencies = [ ('core', '0038_xslt_1-3-8'), ] operations = [ migrations.RunPython(replace_template, reverse_code=migrations.RunPython.noop) ]
# ... existing code ... for setting in settings: if isinstance(setting.value, str): setting.value = re.sub(REGEX, OUTPUT, setting.value) setting.save() # ... rest of the code ...
6477768e3040ed43fb10072730b84c29bef1e949
continuate/__init__.py
continuate/__init__.py
import importlib __all__ = ["linalg", "single_parameter"] for m in __all__: importlib.import_module("continuate." + m)
import importlib import os.path as op from glob import glob __all__ = [op.basename(f)[:-3] for f in glob(op.join(op.dirname(__file__), "*.py")) if op.basename(f) != "__init__.py"] for m in __all__: importlib.import_module("continuate." + m)
Change manual listing of submodules to automatic
Change manual listing of submodules to automatic
Python
mit
termoshtt/continuate
import importlib + import os.path as op + from glob import glob - __all__ = ["linalg", "single_parameter"] + __all__ = [op.basename(f)[:-3] + for f in glob(op.join(op.dirname(__file__), "*.py")) + if op.basename(f) != "__init__.py"] for m in __all__: importlib.import_module("continuate." + m)
Change manual listing of submodules to automatic
## Code Before: import importlib __all__ = ["linalg", "single_parameter"] for m in __all__: importlib.import_module("continuate." + m) ## Instruction: Change manual listing of submodules to automatic ## Code After: import importlib import os.path as op from glob import glob __all__ = [op.basename(f)[:-3] for f in glob(op.join(op.dirname(__file__), "*.py")) if op.basename(f) != "__init__.py"] for m in __all__: importlib.import_module("continuate." + m)
# ... existing code ... import importlib import os.path as op from glob import glob __all__ = [op.basename(f)[:-3] for f in glob(op.join(op.dirname(__file__), "*.py")) if op.basename(f) != "__init__.py"] # ... rest of the code ...
ddf2075228a8c250cf75ec85914801262cb73177
zerver/migrations/0032_verify_all_medium_avatar_images.py
zerver/migrations/0032_verify_all_medium_avatar_images.py
from __future__ import unicode_literals from django.db import migrations from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor from django.db.migrations.state import StateApps from zerver.lib.upload import upload_backend def verify_medium_avatar_image(apps, schema_editor): # type: (StateApps, DatabaseSchemaEditor) -> None user_profile_model = apps.get_model('zerver', 'UserProfile') for user_profile in user_profile_model.objects.filter(avatar_source=u"U"): upload_backend.ensure_medium_avatar_image(user_profile) class Migration(migrations.Migration): dependencies = [ ('zerver', '0031_remove_system_avatar_source'), ] operations = [ migrations.RunPython(verify_medium_avatar_image) ]
from __future__ import unicode_literals from django.conf import settings from django.db import migrations from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor from django.db.migrations.state import StateApps from mock import patch from zerver.lib.utils import make_safe_digest from zerver.lib.upload import upload_backend from zerver.models import UserProfile from typing import Text import hashlib # We hackishly patch this function in order to revert it to the state # it had when this migration was first written. This is a balance # between copying in a historical version of hundreds of lines of code # from zerver.lib.upload (which would pretty annoying, but would be a # pain) and just using the current version, which doesn't work # since we rearranged the avatars in Zulip 1.6. def patched_user_avatar_path(user_profile): # type: (UserProfile) -> Text email = user_profile.email user_key = email.lower() + settings.AVATAR_SALT return make_safe_digest(user_key, hashlib.sha1) @patch('zerver.lib.upload.user_avatar_path', patched_user_avatar_path) def verify_medium_avatar_image(apps, schema_editor): # type: (StateApps, DatabaseSchemaEditor) -> None user_profile_model = apps.get_model('zerver', 'UserProfile') for user_profile in user_profile_model.objects.filter(avatar_source=u"U"): upload_backend.ensure_medium_avatar_image(user_profile) class Migration(migrations.Migration): dependencies = [ ('zerver', '0031_remove_system_avatar_source'), ] operations = [ migrations.RunPython(verify_medium_avatar_image) ]
Make migration 0032 use an old version of user_avatar_path.
Make migration 0032 use an old version of user_avatar_path. This fixes upgrading from very old Zulip servers (e.g. 1.4.3) all the way to current. Fixes: #6516.
Python
apache-2.0
hackerkid/zulip,kou/zulip,amanharitsh123/zulip,brockwhittaker/zulip,showell/zulip,hackerkid/zulip,rishig/zulip,verma-varsha/zulip,synicalsyntax/zulip,zulip/zulip,amanharitsh123/zulip,showell/zulip,punchagan/zulip,amanharitsh123/zulip,punchagan/zulip,timabbott/zulip,rht/zulip,tommyip/zulip,eeshangarg/zulip,Galexrt/zulip,eeshangarg/zulip,rishig/zulip,rishig/zulip,Galexrt/zulip,dhcrzf/zulip,rht/zulip,shubhamdhama/zulip,rht/zulip,tommyip/zulip,mahim97/zulip,kou/zulip,kou/zulip,timabbott/zulip,zulip/zulip,brainwane/zulip,verma-varsha/zulip,verma-varsha/zulip,punchagan/zulip,brainwane/zulip,zulip/zulip,eeshangarg/zulip,timabbott/zulip,synicalsyntax/zulip,brockwhittaker/zulip,brockwhittaker/zulip,brainwane/zulip,showell/zulip,brainwane/zulip,brainwane/zulip,rishig/zulip,tommyip/zulip,Galexrt/zulip,tommyip/zulip,synicalsyntax/zulip,zulip/zulip,jackrzhang/zulip,eeshangarg/zulip,andersk/zulip,kou/zulip,punchagan/zulip,rht/zulip,kou/zulip,andersk/zulip,kou/zulip,timabbott/zulip,jackrzhang/zulip,synicalsyntax/zulip,eeshangarg/zulip,brockwhittaker/zulip,tommyip/zulip,brainwane/zulip,dhcrzf/zulip,dhcrzf/zulip,rishig/zulip,showell/zulip,showell/zulip,andersk/zulip,hackerkid/zulip,brockwhittaker/zulip,andersk/zulip,showell/zulip,timabbott/zulip,dhcrzf/zulip,mahim97/zulip,jackrzhang/zulip,andersk/zulip,hackerkid/zulip,jackrzhang/zulip,jackrzhang/zulip,amanharitsh123/zulip,shubhamdhama/zulip,amanharitsh123/zulip,mahim97/zulip,kou/zulip,tommyip/zulip,dhcrzf/zulip,shubhamdhama/zulip,rht/zulip,rht/zulip,eeshangarg/zulip,shubhamdhama/zulip,jackrzhang/zulip,shubhamdhama/zulip,zulip/zulip,punchagan/zulip,rishig/zulip,shubhamdhama/zulip,hackerkid/zulip,shubhamdhama/zulip,dhcrzf/zulip,timabbott/zulip,rishig/zulip,punchagan/zulip,zulip/zulip,verma-varsha/zulip,showell/zulip,Galexrt/zulip,mahim97/zulip,Galexrt/zulip,verma-varsha/zulip,punchagan/zulip,hackerkid/zulip,jackrzhang/zulip,Galexrt/zulip,brainwane/zulip,hackerkid/zulip,synicalsyntax/zulip,eeshangarg/zulip,zulip/zulip,dhcrzf/zulip,andersk/zulip,brockwhittaker/zulip,mahim97/zulip,amanharitsh123/zulip,timabbott/zulip,synicalsyntax/zulip,rht/zulip,tommyip/zulip,synicalsyntax/zulip,verma-varsha/zulip,mahim97/zulip,Galexrt/zulip,andersk/zulip
from __future__ import unicode_literals + from django.conf import settings from django.db import migrations from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor from django.db.migrations.state import StateApps + from mock import patch + from zerver.lib.utils import make_safe_digest from zerver.lib.upload import upload_backend + from zerver.models import UserProfile + from typing import Text + import hashlib + # We hackishly patch this function in order to revert it to the state + # it had when this migration was first written. This is a balance + # between copying in a historical version of hundreds of lines of code + # from zerver.lib.upload (which would pretty annoying, but would be a + # pain) and just using the current version, which doesn't work + # since we rearranged the avatars in Zulip 1.6. + def patched_user_avatar_path(user_profile): + # type: (UserProfile) -> Text + email = user_profile.email + user_key = email.lower() + settings.AVATAR_SALT + return make_safe_digest(user_key, hashlib.sha1) + @patch('zerver.lib.upload.user_avatar_path', patched_user_avatar_path) def verify_medium_avatar_image(apps, schema_editor): # type: (StateApps, DatabaseSchemaEditor) -> None user_profile_model = apps.get_model('zerver', 'UserProfile') for user_profile in user_profile_model.objects.filter(avatar_source=u"U"): upload_backend.ensure_medium_avatar_image(user_profile) class Migration(migrations.Migration): dependencies = [ ('zerver', '0031_remove_system_avatar_source'), ] operations = [ migrations.RunPython(verify_medium_avatar_image) ]
Make migration 0032 use an old version of user_avatar_path.
## Code Before: from __future__ import unicode_literals from django.db import migrations from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor from django.db.migrations.state import StateApps from zerver.lib.upload import upload_backend def verify_medium_avatar_image(apps, schema_editor): # type: (StateApps, DatabaseSchemaEditor) -> None user_profile_model = apps.get_model('zerver', 'UserProfile') for user_profile in user_profile_model.objects.filter(avatar_source=u"U"): upload_backend.ensure_medium_avatar_image(user_profile) class Migration(migrations.Migration): dependencies = [ ('zerver', '0031_remove_system_avatar_source'), ] operations = [ migrations.RunPython(verify_medium_avatar_image) ] ## Instruction: Make migration 0032 use an old version of user_avatar_path. ## Code After: from __future__ import unicode_literals from django.conf import settings from django.db import migrations from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor from django.db.migrations.state import StateApps from mock import patch from zerver.lib.utils import make_safe_digest from zerver.lib.upload import upload_backend from zerver.models import UserProfile from typing import Text import hashlib # We hackishly patch this function in order to revert it to the state # it had when this migration was first written. This is a balance # between copying in a historical version of hundreds of lines of code # from zerver.lib.upload (which would pretty annoying, but would be a # pain) and just using the current version, which doesn't work # since we rearranged the avatars in Zulip 1.6. def patched_user_avatar_path(user_profile): # type: (UserProfile) -> Text email = user_profile.email user_key = email.lower() + settings.AVATAR_SALT return make_safe_digest(user_key, hashlib.sha1) @patch('zerver.lib.upload.user_avatar_path', patched_user_avatar_path) def verify_medium_avatar_image(apps, schema_editor): # type: (StateApps, DatabaseSchemaEditor) -> None user_profile_model = apps.get_model('zerver', 'UserProfile') for user_profile in user_profile_model.objects.filter(avatar_source=u"U"): upload_backend.ensure_medium_avatar_image(user_profile) class Migration(migrations.Migration): dependencies = [ ('zerver', '0031_remove_system_avatar_source'), ] operations = [ migrations.RunPython(verify_medium_avatar_image) ]
# ... existing code ... from django.conf import settings from django.db import migrations # ... modified code ... from mock import patch from zerver.lib.utils import make_safe_digest from zerver.lib.upload import upload_backend from zerver.models import UserProfile from typing import Text import hashlib # We hackishly patch this function in order to revert it to the state # it had when this migration was first written. This is a balance # between copying in a historical version of hundreds of lines of code # from zerver.lib.upload (which would pretty annoying, but would be a # pain) and just using the current version, which doesn't work # since we rearranged the avatars in Zulip 1.6. def patched_user_avatar_path(user_profile): # type: (UserProfile) -> Text email = user_profile.email user_key = email.lower() + settings.AVATAR_SALT return make_safe_digest(user_key, hashlib.sha1) @patch('zerver.lib.upload.user_avatar_path', patched_user_avatar_path) def verify_medium_avatar_image(apps, schema_editor): # ... rest of the code ...
166e0980fc20b507763395297e8a67c7dcb3a3da
examples/neural_network_inference/onnx_converter/small_example.py
examples/neural_network_inference/onnx_converter/small_example.py
import torch import torch.nn as nn import torch.nn.functional as F from onnx_coreml import convert # Step 0 - (a) Define ML Model class small_model(nn.Module): def __init__(self): super(small_model, self).__init__() self.fc1 = nn.Linear(768, 256) self.fc2 = nn.Linear(256, 10) def forward(self, x): y = F.relu(self.fc1(x)) y = F.softmax(self.fc2(y)) return y # Step 0 - (b) Create model or Load from dist model = small_model() dummy_input = torch.randn(768) # Step 1 - PyTorch to ONNX model torch.onnx.export(model, dummy_input, './small_model.onnx') # Step 2 - ONNX to CoreML model mlmodel = convert(model='./small_model.onnx', target_ios='13') # Save converted CoreML model mlmodel.save('small_model.mlmodel')
import torch import torch.nn as nn import torch.nn.functional as F from onnx_coreml import convert # Step 0 - (a) Define ML Model class small_model(nn.Module): def __init__(self): super(small_model, self).__init__() self.fc1 = nn.Linear(768, 256) self.fc2 = nn.Linear(256, 10) def forward(self, x): y = F.relu(self.fc1(x)) y = F.softmax(self.fc2(y)) return y # Step 0 - (b) Create model or Load from dist model = small_model() dummy_input = torch.randn(768) # Step 1 - PyTorch to ONNX model torch.onnx.export(model, dummy_input, './small_model.onnx') # Step 2 - ONNX to CoreML model mlmodel = convert(model='./small_model.onnx', minimum_ios_deployment_target='13') # Save converted CoreML model mlmodel.save('small_model.mlmodel')
Update the example with latest interface
Update the example with latest interface Update the example with the latest interface of the function "convert"
Python
bsd-3-clause
apple/coremltools,apple/coremltools,apple/coremltools,apple/coremltools
import torch import torch.nn as nn import torch.nn.functional as F from onnx_coreml import convert # Step 0 - (a) Define ML Model class small_model(nn.Module): def __init__(self): super(small_model, self).__init__() self.fc1 = nn.Linear(768, 256) self.fc2 = nn.Linear(256, 10) def forward(self, x): y = F.relu(self.fc1(x)) y = F.softmax(self.fc2(y)) return y # Step 0 - (b) Create model or Load from dist model = small_model() dummy_input = torch.randn(768) # Step 1 - PyTorch to ONNX model torch.onnx.export(model, dummy_input, './small_model.onnx') # Step 2 - ONNX to CoreML model - mlmodel = convert(model='./small_model.onnx', target_ios='13') + mlmodel = convert(model='./small_model.onnx', minimum_ios_deployment_target='13') # Save converted CoreML model mlmodel.save('small_model.mlmodel')
Update the example with latest interface
## Code Before: import torch import torch.nn as nn import torch.nn.functional as F from onnx_coreml import convert # Step 0 - (a) Define ML Model class small_model(nn.Module): def __init__(self): super(small_model, self).__init__() self.fc1 = nn.Linear(768, 256) self.fc2 = nn.Linear(256, 10) def forward(self, x): y = F.relu(self.fc1(x)) y = F.softmax(self.fc2(y)) return y # Step 0 - (b) Create model or Load from dist model = small_model() dummy_input = torch.randn(768) # Step 1 - PyTorch to ONNX model torch.onnx.export(model, dummy_input, './small_model.onnx') # Step 2 - ONNX to CoreML model mlmodel = convert(model='./small_model.onnx', target_ios='13') # Save converted CoreML model mlmodel.save('small_model.mlmodel') ## Instruction: Update the example with latest interface ## Code After: import torch import torch.nn as nn import torch.nn.functional as F from onnx_coreml import convert # Step 0 - (a) Define ML Model class small_model(nn.Module): def __init__(self): super(small_model, self).__init__() self.fc1 = nn.Linear(768, 256) self.fc2 = nn.Linear(256, 10) def forward(self, x): y = F.relu(self.fc1(x)) y = F.softmax(self.fc2(y)) return y # Step 0 - (b) Create model or Load from dist model = small_model() dummy_input = torch.randn(768) # Step 1 - PyTorch to ONNX model torch.onnx.export(model, dummy_input, './small_model.onnx') # Step 2 - ONNX to CoreML model mlmodel = convert(model='./small_model.onnx', minimum_ios_deployment_target='13') # Save converted CoreML model mlmodel.save('small_model.mlmodel')
... # Step 2 - ONNX to CoreML model mlmodel = convert(model='./small_model.onnx', minimum_ios_deployment_target='13') # Save converted CoreML model ...
eed276146fe06e5d8191462cc7ef81a65c4bbdbb
pdf_generator/styles.py
pdf_generator/styles.py
from __future__ import absolute_import from reportlab.platypus import ( Paragraph as BaseParagraph, Image as BaseImage, Spacer, ) from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet styles = getSampleStyleSheet() snormal = ParagraphStyle('normal') def Paragraph(text, style=snormal, **kw): if isinstance(style, basestring): style = styles[style] if kw: style = ParagraphStyle('style', parent=style, **kw) return BaseParagraph(text, style) def HSpacer(width): return Spacer(0, width) def Image(path, width=None, height=None, ratio=None): if width and ratio: height = width / ratio elif height and ratio: width = height * ratio return BaseImage(path, width, height)
from __future__ import absolute_import from reportlab.platypus import ( Paragraph as BaseParagraph, Image as BaseImage, Spacer, ) from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet styles = getSampleStyleSheet() snormal = ParagraphStyle('normal') def Paragraph(text, style=snormal, **kw): if isinstance(style, basestring): style = styles[style] if kw: style = ParagraphStyle('style', parent=style, **kw) return BaseParagraph(text, style) def bold(string, *args, **kw): """ Return string as a :class:`Paragraph` in bold """ return Paragraph(u'<b>{}</b>'.format(string), *args, **kw) def italic(string, *args, **kw): """ Return string as a :class:`Paragraph` in italic """ return Paragraph(u'<i>{}</i>'.format(string), *args, **kw) def HSpacer(width): return Spacer(0, width) def Image(path, width=None, height=None, ratio=None): if width and ratio: height = width / ratio elif height and ratio: width = height * ratio return BaseImage(path, width, height)
Add bold and italic helpers
Add bold and italic helpers
Python
mit
cecedille1/PDF_generator
from __future__ import absolute_import from reportlab.platypus import ( Paragraph as BaseParagraph, Image as BaseImage, Spacer, ) from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet styles = getSampleStyleSheet() snormal = ParagraphStyle('normal') def Paragraph(text, style=snormal, **kw): if isinstance(style, basestring): style = styles[style] if kw: style = ParagraphStyle('style', parent=style, **kw) return BaseParagraph(text, style) + def bold(string, *args, **kw): + """ + Return string as a :class:`Paragraph` in bold + """ + return Paragraph(u'<b>{}</b>'.format(string), *args, **kw) + + + def italic(string, *args, **kw): + """ + Return string as a :class:`Paragraph` in italic + """ + return Paragraph(u'<i>{}</i>'.format(string), *args, **kw) + + def HSpacer(width): return Spacer(0, width) def Image(path, width=None, height=None, ratio=None): if width and ratio: height = width / ratio elif height and ratio: width = height * ratio return BaseImage(path, width, height)
Add bold and italic helpers
## Code Before: from __future__ import absolute_import from reportlab.platypus import ( Paragraph as BaseParagraph, Image as BaseImage, Spacer, ) from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet styles = getSampleStyleSheet() snormal = ParagraphStyle('normal') def Paragraph(text, style=snormal, **kw): if isinstance(style, basestring): style = styles[style] if kw: style = ParagraphStyle('style', parent=style, **kw) return BaseParagraph(text, style) def HSpacer(width): return Spacer(0, width) def Image(path, width=None, height=None, ratio=None): if width and ratio: height = width / ratio elif height and ratio: width = height * ratio return BaseImage(path, width, height) ## Instruction: Add bold and italic helpers ## Code After: from __future__ import absolute_import from reportlab.platypus import ( Paragraph as BaseParagraph, Image as BaseImage, Spacer, ) from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet styles = getSampleStyleSheet() snormal = ParagraphStyle('normal') def Paragraph(text, style=snormal, **kw): if isinstance(style, basestring): style = styles[style] if kw: style = ParagraphStyle('style', parent=style, **kw) return BaseParagraph(text, style) def bold(string, *args, **kw): """ Return string as a :class:`Paragraph` in bold """ return Paragraph(u'<b>{}</b>'.format(string), *args, **kw) def italic(string, *args, **kw): """ Return string as a :class:`Paragraph` in italic """ return Paragraph(u'<i>{}</i>'.format(string), *args, **kw) def HSpacer(width): return Spacer(0, width) def Image(path, width=None, height=None, ratio=None): if width and ratio: height = width / ratio elif height and ratio: width = height * ratio return BaseImage(path, width, height)
... def bold(string, *args, **kw): """ Return string as a :class:`Paragraph` in bold """ return Paragraph(u'<b>{}</b>'.format(string), *args, **kw) def italic(string, *args, **kw): """ Return string as a :class:`Paragraph` in italic """ return Paragraph(u'<i>{}</i>'.format(string), *args, **kw) def HSpacer(width): ...
0c0f56dba4b9f08f4cb443f2668cdee51fe80c32
chapter02/fahrenheitToCelsius.py
chapter02/fahrenheitToCelsius.py
F = input("Gimme Fahrenheit: ") print (F-32) * 5 / 9 print (F-32) / 1.8000
fahrenheit = input("Gimme Fahrenheit: ") print (fahrenheit-32) * 5 / 9 print (fahrenheit-32) / 1.8000
Change variable name to fahrenheit
Change variable name to fahrenheit
Python
apache-2.0
MindCookin/python-exercises
- F = input("Gimme Fahrenheit: ") + fahrenheit = input("Gimme Fahrenheit: ") - print (F-32) * 5 / 9 + print (fahrenheit-32) * 5 / 9 - print (F-32) / 1.8000 + print (fahrenheit-32) / 1.8000
Change variable name to fahrenheit
## Code Before: F = input("Gimme Fahrenheit: ") print (F-32) * 5 / 9 print (F-32) / 1.8000 ## Instruction: Change variable name to fahrenheit ## Code After: fahrenheit = input("Gimme Fahrenheit: ") print (fahrenheit-32) * 5 / 9 print (fahrenheit-32) / 1.8000
// ... existing code ... fahrenheit = input("Gimme Fahrenheit: ") print (fahrenheit-32) * 5 / 9 print (fahrenheit-32) / 1.8000 // ... rest of the code ...
1f74b7ea4fdbcae6166477e56d1a6ccc81f6a5c8
valohai_cli/exceptions.py
valohai_cli/exceptions.py
import click from click import ClickException class APIError(ClickException): def __init__(self, response): super(APIError, self).__init__(response.text) self.response = response self.request = response.request def show(self, file=None): click.secho('Error: %s' % self.format_message(), file=file, err=True, fg='red') class ConfigurationError(RuntimeError): pass class NoProject(ClickException): pass
import click from click import ClickException class APIError(ClickException): def __init__(self, response): super(APIError, self).__init__(response.text) self.response = response self.request = response.request def show(self, file=None): click.secho('Error: %s' % self.format_message(), file=file, err=True, fg='red') class ConfigurationError(ClickException, RuntimeError): pass class NoProject(ClickException): pass
Make ConfigurationError also a ClickException
Make ConfigurationError also a ClickException
Python
mit
valohai/valohai-cli
import click from click import ClickException class APIError(ClickException): def __init__(self, response): super(APIError, self).__init__(response.text) self.response = response self.request = response.request def show(self, file=None): click.secho('Error: %s' % self.format_message(), file=file, err=True, fg='red') - class ConfigurationError(RuntimeError): + class ConfigurationError(ClickException, RuntimeError): pass class NoProject(ClickException): pass
Make ConfigurationError also a ClickException
## Code Before: import click from click import ClickException class APIError(ClickException): def __init__(self, response): super(APIError, self).__init__(response.text) self.response = response self.request = response.request def show(self, file=None): click.secho('Error: %s' % self.format_message(), file=file, err=True, fg='red') class ConfigurationError(RuntimeError): pass class NoProject(ClickException): pass ## Instruction: Make ConfigurationError also a ClickException ## Code After: import click from click import ClickException class APIError(ClickException): def __init__(self, response): super(APIError, self).__init__(response.text) self.response = response self.request = response.request def show(self, file=None): click.secho('Error: %s' % self.format_message(), file=file, err=True, fg='red') class ConfigurationError(ClickException, RuntimeError): pass class NoProject(ClickException): pass
... class ConfigurationError(ClickException, RuntimeError): pass ...
32508dea4ef00fb54919c0260b7ba2902835faf5
prepareupload.py
prepareupload.py
import sys import olrcdb import os # Globals COUNT = 0 class FileParser(object): '''Object used to parse through a directory for all it's files. Collects the paths of all the files and stores a record of these in a new table in the database. The Schema of the database is: NewTable(path, uploaded=false) ''' def __init__(self, directory, table_name): self.directory = directory self.table_name = table_name def prepare_upload(connect, directory, table_name): '''Given a database connection, directory and table_name, -Create the table in the database -populate the table with (path, uploaded=false) where each path is a file in the given directory.''' global COUNT for filename in os.listdir(directory): file_path = os.path.join(directory, filename) # Add file name to the list. if os.path.isfile(file_path): connect.insert_path(file_path, table_name) COUNT += 1 else: prepare_upload(connect, file_path, table_name) if __name__ == "__main__": # Check for proper parameters if len(sys.argv) != 3: sys.stderr.write( 'Usage: python prepareupload.py path-to-drive table-name\n' ) sys.exit(1) connect = olrcdb.DatabaseConnection() connect.create_table(sys.argv[2]) prepare_upload(connect, sys.argv[1], sys.argv[2])
import sys import olrcdb import os # Globals COUNT = 0 class FileParser(object): '''Object used to parse through a directory for all it's files. Collects the paths of all the files and stores a record of these in a new table in the database. The Schema of the database is: NewTable(path, uploaded=false) ''' def __init__(self, directory, table_name): self.directory = directory self.table_name = table_name def prepare_upload(connect, directory, table_name): '''Given a database connection, directory and table_name, -Create the table in the database -populate the table with (path, uploaded=false) where each path is a file in the given directory.''' global COUNT for filename in os.listdir(directory): file_path = os.path.join(directory, filename) # Add file name to the list. if os.path.isfile(file_path): connect.insert_path(file_path, table_name) COUNT += 1 sys.stdout.flush() sys.stdout.write("\r{0} parsed. \n".format(COUNT)) else: prepare_upload(connect, file_path, table_name) if __name__ == "__main__": # Check for proper parameters if len(sys.argv) != 3: sys.stderr.write( 'Usage: python prepareupload.py path-to-drive table-name\n' ) sys.exit(1) connect = olrcdb.DatabaseConnection() connect.create_table(sys.argv[2]) prepare_upload(connect, sys.argv[1], sys.argv[2])
Print messages for prepare upload.
Print messages for prepare upload.
Python
bsd-3-clause
OLRC/SwiftBulkUploader,cudevmaxwell/SwiftBulkUploader
import sys import olrcdb import os # Globals COUNT = 0 class FileParser(object): '''Object used to parse through a directory for all it's files. Collects the paths of all the files and stores a record of these in a new table in the database. The Schema of the database is: NewTable(path, uploaded=false) ''' def __init__(self, directory, table_name): self.directory = directory self.table_name = table_name def prepare_upload(connect, directory, table_name): '''Given a database connection, directory and table_name, -Create the table in the database -populate the table with (path, uploaded=false) where each path is a file in the given directory.''' global COUNT for filename in os.listdir(directory): file_path = os.path.join(directory, filename) # Add file name to the list. if os.path.isfile(file_path): connect.insert_path(file_path, table_name) COUNT += 1 + + sys.stdout.flush() + sys.stdout.write("\r{0} parsed. \n".format(COUNT)) else: prepare_upload(connect, file_path, table_name) if __name__ == "__main__": # Check for proper parameters if len(sys.argv) != 3: sys.stderr.write( 'Usage: python prepareupload.py path-to-drive table-name\n' ) sys.exit(1) connect = olrcdb.DatabaseConnection() connect.create_table(sys.argv[2]) prepare_upload(connect, sys.argv[1], sys.argv[2])
Print messages for prepare upload.
## Code Before: import sys import olrcdb import os # Globals COUNT = 0 class FileParser(object): '''Object used to parse through a directory for all it's files. Collects the paths of all the files and stores a record of these in a new table in the database. The Schema of the database is: NewTable(path, uploaded=false) ''' def __init__(self, directory, table_name): self.directory = directory self.table_name = table_name def prepare_upload(connect, directory, table_name): '''Given a database connection, directory and table_name, -Create the table in the database -populate the table with (path, uploaded=false) where each path is a file in the given directory.''' global COUNT for filename in os.listdir(directory): file_path = os.path.join(directory, filename) # Add file name to the list. if os.path.isfile(file_path): connect.insert_path(file_path, table_name) COUNT += 1 else: prepare_upload(connect, file_path, table_name) if __name__ == "__main__": # Check for proper parameters if len(sys.argv) != 3: sys.stderr.write( 'Usage: python prepareupload.py path-to-drive table-name\n' ) sys.exit(1) connect = olrcdb.DatabaseConnection() connect.create_table(sys.argv[2]) prepare_upload(connect, sys.argv[1], sys.argv[2]) ## Instruction: Print messages for prepare upload. ## Code After: import sys import olrcdb import os # Globals COUNT = 0 class FileParser(object): '''Object used to parse through a directory for all it's files. Collects the paths of all the files and stores a record of these in a new table in the database. The Schema of the database is: NewTable(path, uploaded=false) ''' def __init__(self, directory, table_name): self.directory = directory self.table_name = table_name def prepare_upload(connect, directory, table_name): '''Given a database connection, directory and table_name, -Create the table in the database -populate the table with (path, uploaded=false) where each path is a file in the given directory.''' global COUNT for filename in os.listdir(directory): file_path = os.path.join(directory, filename) # Add file name to the list. if os.path.isfile(file_path): connect.insert_path(file_path, table_name) COUNT += 1 sys.stdout.flush() sys.stdout.write("\r{0} parsed. \n".format(COUNT)) else: prepare_upload(connect, file_path, table_name) if __name__ == "__main__": # Check for proper parameters if len(sys.argv) != 3: sys.stderr.write( 'Usage: python prepareupload.py path-to-drive table-name\n' ) sys.exit(1) connect = olrcdb.DatabaseConnection() connect.create_table(sys.argv[2]) prepare_upload(connect, sys.argv[1], sys.argv[2])
// ... existing code ... COUNT += 1 sys.stdout.flush() sys.stdout.write("\r{0} parsed. \n".format(COUNT)) else: // ... rest of the code ...
b1c8ce6ac2658264a97983b185ebef31c0952b33
depot/tests.py
depot/tests.py
from django.test import TestCase from .models import Depot class DepotTestCase(TestCase): def test_str(self): depot = Depot(1, "My depot") self.assertEqual(depot.__str__(), "Depot My depot")
from django.test import TestCase from .models import Depot, Item class DepotTestCase(TestCase): def test_str(self): depot = Depot(1, "My depot") self.assertEqual(depot.__str__(), "Depot My depot") class ItemTestCase(TestCase): def test_str(self): depot = Depot(2, "My depot") item = Item(1, "My item", 5, 2, depot, "My shelf") self.assertEqual(item.__str__(), "5 unit(s) of My item (visib.: 2) in My shelf")
Add test case for Item __str__ function
Add test case for Item __str__ function
Python
agpl-3.0
verleihtool/verleihtool,verleihtool/verleihtool,verleihtool/verleihtool,verleihtool/verleihtool
from django.test import TestCase - from .models import Depot + from .models import Depot, Item class DepotTestCase(TestCase): def test_str(self): depot = Depot(1, "My depot") self.assertEqual(depot.__str__(), "Depot My depot") + class ItemTestCase(TestCase): + + def test_str(self): + depot = Depot(2, "My depot") + item = Item(1, "My item", 5, 2, depot, "My shelf") + self.assertEqual(item.__str__(), "5 unit(s) of My item (visib.: 2) in My shelf") +
Add test case for Item __str__ function
## Code Before: from django.test import TestCase from .models import Depot class DepotTestCase(TestCase): def test_str(self): depot = Depot(1, "My depot") self.assertEqual(depot.__str__(), "Depot My depot") ## Instruction: Add test case for Item __str__ function ## Code After: from django.test import TestCase from .models import Depot, Item class DepotTestCase(TestCase): def test_str(self): depot = Depot(1, "My depot") self.assertEqual(depot.__str__(), "Depot My depot") class ItemTestCase(TestCase): def test_str(self): depot = Depot(2, "My depot") item = Item(1, "My item", 5, 2, depot, "My shelf") self.assertEqual(item.__str__(), "5 unit(s) of My item (visib.: 2) in My shelf")
... from django.test import TestCase from .models import Depot, Item ... self.assertEqual(depot.__str__(), "Depot My depot") class ItemTestCase(TestCase): def test_str(self): depot = Depot(2, "My depot") item = Item(1, "My item", 5, 2, depot, "My shelf") self.assertEqual(item.__str__(), "5 unit(s) of My item (visib.: 2) in My shelf") ...
27a944d5fc74972a90e8dd69879ebc27c4412b99
test/python_api/default-constructor/sb_frame.py
test/python_api/default-constructor/sb_frame.py
import sys import lldb def fuzz_obj(obj): obj.GetFrameID() obj.GetPC() obj.SetPC(0xffffffff) obj.GetSP() obj.GetFP() obj.GetPCAddress() obj.GetSymbolContext(0) obj.GetModule() obj.GetCompileUnit() obj.GetFunction() obj.GetSymbol() obj.GetBlock() obj.GetFunctionName() obj.IsInlined() obj.EvaluateExpression("x + y") obj.EvaluateExpression("x + y", lldb.eDynamicCanRunTarget) obj.GetFrameBlock() obj.GetLineEntry() obj.GetThread() obj.Disassemble() obj.GetVariables(True, True, True, True) obj.GetVariables(True, True, True, False, lldb.eDynamicCanRunTarget) obj.GetRegisters() obj.FindVariable("my_var") obj.FindVariable("my_var", lldb.eDynamicCanRunTarget) obj.GetDescription(lldb.SBStream()) obj.Clear()
import sys import lldb def fuzz_obj(obj): obj.GetFrameID() obj.GetPC() obj.SetPC(0xffffffff) obj.GetSP() obj.GetFP() obj.GetPCAddress() obj.GetSymbolContext(0) obj.GetModule() obj.GetCompileUnit() obj.GetFunction() obj.GetSymbol() obj.GetBlock() obj.GetFunctionName() obj.IsInlined() obj.EvaluateExpression("x + y") obj.EvaluateExpression("x + y", lldb.eDynamicCanRunTarget) obj.GetFrameBlock() obj.GetLineEntry() obj.GetThread() obj.Disassemble() obj.GetVariables(True, True, True, True) obj.GetVariables(True, True, True, False, lldb.eDynamicCanRunTarget) obj.GetRegisters() obj.FindVariable("my_var") obj.FindVariable("my_var", lldb.eDynamicCanRunTarget) obj.FindValue("your_var", lldb.eValueTypeVariableGlobal) obj.FindValue("your_var", lldb.eValueTypeVariableStatic, lldb.eDynamicCanRunTarget) obj.WatchValue("global_var", lldb.eValueTypeVariableGlobal, lldb.LLDB_WATCH_TYPE_READ) obj.GetDescription(lldb.SBStream()) obj.Clear()
Add FindValue() and WatchValue() fuzz calls to the mix.
Add FindValue() and WatchValue() fuzz calls to the mix. git-svn-id: b33bab8abb5b18c12ee100cd7761ab452d00b2b0@140439 91177308-0d34-0410-b5e6-96231b3b80d8
Python
apache-2.0
apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,llvm-mirror/lldb,llvm-mirror/lldb,apple/swift-lldb,llvm-mirror/lldb
import sys import lldb def fuzz_obj(obj): obj.GetFrameID() obj.GetPC() obj.SetPC(0xffffffff) obj.GetSP() obj.GetFP() obj.GetPCAddress() obj.GetSymbolContext(0) obj.GetModule() obj.GetCompileUnit() obj.GetFunction() obj.GetSymbol() obj.GetBlock() obj.GetFunctionName() obj.IsInlined() obj.EvaluateExpression("x + y") obj.EvaluateExpression("x + y", lldb.eDynamicCanRunTarget) obj.GetFrameBlock() obj.GetLineEntry() obj.GetThread() obj.Disassemble() obj.GetVariables(True, True, True, True) obj.GetVariables(True, True, True, False, lldb.eDynamicCanRunTarget) obj.GetRegisters() obj.FindVariable("my_var") obj.FindVariable("my_var", lldb.eDynamicCanRunTarget) + obj.FindValue("your_var", lldb.eValueTypeVariableGlobal) + obj.FindValue("your_var", lldb.eValueTypeVariableStatic, lldb.eDynamicCanRunTarget) + obj.WatchValue("global_var", lldb.eValueTypeVariableGlobal, lldb.LLDB_WATCH_TYPE_READ) obj.GetDescription(lldb.SBStream()) obj.Clear()
Add FindValue() and WatchValue() fuzz calls to the mix.
## Code Before: import sys import lldb def fuzz_obj(obj): obj.GetFrameID() obj.GetPC() obj.SetPC(0xffffffff) obj.GetSP() obj.GetFP() obj.GetPCAddress() obj.GetSymbolContext(0) obj.GetModule() obj.GetCompileUnit() obj.GetFunction() obj.GetSymbol() obj.GetBlock() obj.GetFunctionName() obj.IsInlined() obj.EvaluateExpression("x + y") obj.EvaluateExpression("x + y", lldb.eDynamicCanRunTarget) obj.GetFrameBlock() obj.GetLineEntry() obj.GetThread() obj.Disassemble() obj.GetVariables(True, True, True, True) obj.GetVariables(True, True, True, False, lldb.eDynamicCanRunTarget) obj.GetRegisters() obj.FindVariable("my_var") obj.FindVariable("my_var", lldb.eDynamicCanRunTarget) obj.GetDescription(lldb.SBStream()) obj.Clear() ## Instruction: Add FindValue() and WatchValue() fuzz calls to the mix. ## Code After: import sys import lldb def fuzz_obj(obj): obj.GetFrameID() obj.GetPC() obj.SetPC(0xffffffff) obj.GetSP() obj.GetFP() obj.GetPCAddress() obj.GetSymbolContext(0) obj.GetModule() obj.GetCompileUnit() obj.GetFunction() obj.GetSymbol() obj.GetBlock() obj.GetFunctionName() obj.IsInlined() obj.EvaluateExpression("x + y") obj.EvaluateExpression("x + y", lldb.eDynamicCanRunTarget) obj.GetFrameBlock() obj.GetLineEntry() obj.GetThread() obj.Disassemble() obj.GetVariables(True, True, True, True) obj.GetVariables(True, True, True, False, lldb.eDynamicCanRunTarget) obj.GetRegisters() obj.FindVariable("my_var") obj.FindVariable("my_var", lldb.eDynamicCanRunTarget) obj.FindValue("your_var", lldb.eValueTypeVariableGlobal) obj.FindValue("your_var", lldb.eValueTypeVariableStatic, lldb.eDynamicCanRunTarget) obj.WatchValue("global_var", lldb.eValueTypeVariableGlobal, lldb.LLDB_WATCH_TYPE_READ) obj.GetDescription(lldb.SBStream()) obj.Clear()
# ... existing code ... obj.FindVariable("my_var", lldb.eDynamicCanRunTarget) obj.FindValue("your_var", lldb.eValueTypeVariableGlobal) obj.FindValue("your_var", lldb.eValueTypeVariableStatic, lldb.eDynamicCanRunTarget) obj.WatchValue("global_var", lldb.eValueTypeVariableGlobal, lldb.LLDB_WATCH_TYPE_READ) obj.GetDescription(lldb.SBStream()) # ... rest of the code ...
1cda977eff5a2edaa0de82882ef2e7d1611329b7
tests/test_protocol.py
tests/test_protocol.py
import pytest class TestProtocol: @pytest.mark.asyncio def test_server_hello(self, ws_client_factory, get_unencrypted_packet): """ The server must send a valid `server-hello` on connection. """ client = yield from ws_client_factory() receiver, message = yield from get_unencrypted_packet(client) assert receiver == 0x00 assert message['type'] == 'server-hello' assert len(message['key']) == 32 assert len(message['my-cookie']) == 16 yield from client.close()
import asyncio import pytest import saltyrtc class TestProtocol: @pytest.mark.asyncio def test_no_subprotocols(self, ws_client_factory): """ The server must drop the client after the connection has been established with a close code of *1002*. """ client = yield from ws_client_factory(subprotocols=None) yield from asyncio.sleep(0.05) assert not client.open assert client.close_code == saltyrtc.CloseCode.sub_protocol_error @pytest.mark.asyncio def test_invalid_subprotocols(self, ws_client_factory): """ The server must drop the client after the connection has been established with a close code of *1002*. """ client = yield from ws_client_factory(subprotocols=['kittie-protocol-3000']) yield from asyncio.sleep(0.05) assert not client.open assert client.close_code == saltyrtc.CloseCode.sub_protocol_error @pytest.mark.asyncio def test_server_hello(self, ws_client_factory, get_unencrypted_packet): """ The server must send a valid `server-hello` on connection. """ client = yield from ws_client_factory() receiver, message = yield from get_unencrypted_packet(client) assert receiver == 0x00 assert message['type'] == 'server-hello' assert len(message['key']) == 32 assert len(message['my-cookie']) == 16 yield from client.close()
Add tests for invalid and no provided sub-protocols
Add tests for invalid and no provided sub-protocols
Python
mit
saltyrtc/saltyrtc-server-python,saltyrtc/saltyrtc-server-python
+ import asyncio + import pytest + + import saltyrtc class TestProtocol: + @pytest.mark.asyncio + def test_no_subprotocols(self, ws_client_factory): + """ + The server must drop the client after the connection has been + established with a close code of *1002*. + """ + client = yield from ws_client_factory(subprotocols=None) + yield from asyncio.sleep(0.05) + assert not client.open + assert client.close_code == saltyrtc.CloseCode.sub_protocol_error + + @pytest.mark.asyncio + def test_invalid_subprotocols(self, ws_client_factory): + """ + The server must drop the client after the connection has been + established with a close code of *1002*. + """ + client = yield from ws_client_factory(subprotocols=['kittie-protocol-3000']) + yield from asyncio.sleep(0.05) + assert not client.open + assert client.close_code == saltyrtc.CloseCode.sub_protocol_error + @pytest.mark.asyncio def test_server_hello(self, ws_client_factory, get_unencrypted_packet): """ The server must send a valid `server-hello` on connection. """ client = yield from ws_client_factory() receiver, message = yield from get_unencrypted_packet(client) assert receiver == 0x00 assert message['type'] == 'server-hello' assert len(message['key']) == 32 assert len(message['my-cookie']) == 16 yield from client.close()
Add tests for invalid and no provided sub-protocols
## Code Before: import pytest class TestProtocol: @pytest.mark.asyncio def test_server_hello(self, ws_client_factory, get_unencrypted_packet): """ The server must send a valid `server-hello` on connection. """ client = yield from ws_client_factory() receiver, message = yield from get_unencrypted_packet(client) assert receiver == 0x00 assert message['type'] == 'server-hello' assert len(message['key']) == 32 assert len(message['my-cookie']) == 16 yield from client.close() ## Instruction: Add tests for invalid and no provided sub-protocols ## Code After: import asyncio import pytest import saltyrtc class TestProtocol: @pytest.mark.asyncio def test_no_subprotocols(self, ws_client_factory): """ The server must drop the client after the connection has been established with a close code of *1002*. """ client = yield from ws_client_factory(subprotocols=None) yield from asyncio.sleep(0.05) assert not client.open assert client.close_code == saltyrtc.CloseCode.sub_protocol_error @pytest.mark.asyncio def test_invalid_subprotocols(self, ws_client_factory): """ The server must drop the client after the connection has been established with a close code of *1002*. """ client = yield from ws_client_factory(subprotocols=['kittie-protocol-3000']) yield from asyncio.sleep(0.05) assert not client.open assert client.close_code == saltyrtc.CloseCode.sub_protocol_error @pytest.mark.asyncio def test_server_hello(self, ws_client_factory, get_unencrypted_packet): """ The server must send a valid `server-hello` on connection. """ client = yield from ws_client_factory() receiver, message = yield from get_unencrypted_packet(client) assert receiver == 0x00 assert message['type'] == 'server-hello' assert len(message['key']) == 32 assert len(message['my-cookie']) == 16 yield from client.close()
# ... existing code ... import asyncio import pytest import saltyrtc # ... modified code ... class TestProtocol: @pytest.mark.asyncio def test_no_subprotocols(self, ws_client_factory): """ The server must drop the client after the connection has been established with a close code of *1002*. """ client = yield from ws_client_factory(subprotocols=None) yield from asyncio.sleep(0.05) assert not client.open assert client.close_code == saltyrtc.CloseCode.sub_protocol_error @pytest.mark.asyncio def test_invalid_subprotocols(self, ws_client_factory): """ The server must drop the client after the connection has been established with a close code of *1002*. """ client = yield from ws_client_factory(subprotocols=['kittie-protocol-3000']) yield from asyncio.sleep(0.05) assert not client.open assert client.close_code == saltyrtc.CloseCode.sub_protocol_error @pytest.mark.asyncio # ... rest of the code ...
c080865fdb36da2718774ddff436325d947be323
test/test_fit_allocator.py
test/test_fit_allocator.py
from support import lib,ffi from qcgc_test import QCGCTest class FitAllocatorTest(QCGCTest): def test_macro_consistency(self): self.assertEqual(2**lib.QCGC_LARGE_FREE_LIST_FIRST_EXP, lib.qcgc_small_free_lists + 1) last_exp = lib.QCGC_LARGE_FREE_LIST_FIRST_EXP + lib.qcgc_large_free_lists - 1 self.assertLess(2**last_exp, 2**lib.QCGC_ARENA_SIZE_EXP) self.assertEqual(2**(last_exp + 1), 2**lib.QCGC_ARENA_SIZE_EXP) def test_small_free_list_index(self): for i in range(1, lib.qcgc_small_free_lists + 1): self.assertTrue(lib.is_small(i)) self.assertEqual(lib.small_index(i), i - 1); def test_large_free_list_index(self): index = -1; for i in range(2**lib.QCGC_LARGE_FREE_LIST_FIRST_EXP, 2**lib.QCGC_ARENA_SIZE_EXP): if (i & (i - 1) == 0): # Check for power of two index = index + 1 self.assertFalse(lib.is_small(i)) self.assertEqual(index, lib.large_index(i));
from support import lib,ffi from qcgc_test import QCGCTest class FitAllocatorTest(QCGCTest): def test_macro_consistency(self): self.assertEqual(2**lib.QCGC_LARGE_FREE_LIST_FIRST_EXP, lib.qcgc_small_free_lists + 1) last_exp = lib.QCGC_LARGE_FREE_LIST_FIRST_EXP + lib.qcgc_large_free_lists - 1 self.assertLess(2**last_exp, 2**lib.QCGC_ARENA_SIZE_EXP) self.assertEqual(2**(last_exp + 1), 2**lib.QCGC_ARENA_SIZE_EXP) def test_small_free_list_index(self): for i in range(1, lib.qcgc_small_free_lists + 1): self.assertTrue(lib.is_small(i)) self.assertEqual(lib.small_index(i), i - 1); self.assertTrue(lib.small_index_to_cells(i - 1), i); def test_large_free_list_index(self): index = -1; for i in range(2**lib.QCGC_LARGE_FREE_LIST_FIRST_EXP, 2**lib.QCGC_ARENA_SIZE_EXP): if (i & (i - 1) == 0): # Check for power of two index = index + 1 self.assertFalse(lib.is_small(i)) self.assertEqual(index, lib.large_index(i));
Add test for index to cells
Add test for index to cells
Python
mit
ntruessel/qcgc,ntruessel/qcgc,ntruessel/qcgc
from support import lib,ffi from qcgc_test import QCGCTest class FitAllocatorTest(QCGCTest): def test_macro_consistency(self): self.assertEqual(2**lib.QCGC_LARGE_FREE_LIST_FIRST_EXP, lib.qcgc_small_free_lists + 1) last_exp = lib.QCGC_LARGE_FREE_LIST_FIRST_EXP + lib.qcgc_large_free_lists - 1 self.assertLess(2**last_exp, 2**lib.QCGC_ARENA_SIZE_EXP) self.assertEqual(2**(last_exp + 1), 2**lib.QCGC_ARENA_SIZE_EXP) def test_small_free_list_index(self): for i in range(1, lib.qcgc_small_free_lists + 1): self.assertTrue(lib.is_small(i)) self.assertEqual(lib.small_index(i), i - 1); + self.assertTrue(lib.small_index_to_cells(i - 1), i); def test_large_free_list_index(self): index = -1; for i in range(2**lib.QCGC_LARGE_FREE_LIST_FIRST_EXP, 2**lib.QCGC_ARENA_SIZE_EXP): if (i & (i - 1) == 0): # Check for power of two index = index + 1 self.assertFalse(lib.is_small(i)) self.assertEqual(index, lib.large_index(i));
Add test for index to cells
## Code Before: from support import lib,ffi from qcgc_test import QCGCTest class FitAllocatorTest(QCGCTest): def test_macro_consistency(self): self.assertEqual(2**lib.QCGC_LARGE_FREE_LIST_FIRST_EXP, lib.qcgc_small_free_lists + 1) last_exp = lib.QCGC_LARGE_FREE_LIST_FIRST_EXP + lib.qcgc_large_free_lists - 1 self.assertLess(2**last_exp, 2**lib.QCGC_ARENA_SIZE_EXP) self.assertEqual(2**(last_exp + 1), 2**lib.QCGC_ARENA_SIZE_EXP) def test_small_free_list_index(self): for i in range(1, lib.qcgc_small_free_lists + 1): self.assertTrue(lib.is_small(i)) self.assertEqual(lib.small_index(i), i - 1); def test_large_free_list_index(self): index = -1; for i in range(2**lib.QCGC_LARGE_FREE_LIST_FIRST_EXP, 2**lib.QCGC_ARENA_SIZE_EXP): if (i & (i - 1) == 0): # Check for power of two index = index + 1 self.assertFalse(lib.is_small(i)) self.assertEqual(index, lib.large_index(i)); ## Instruction: Add test for index to cells ## Code After: from support import lib,ffi from qcgc_test import QCGCTest class FitAllocatorTest(QCGCTest): def test_macro_consistency(self): self.assertEqual(2**lib.QCGC_LARGE_FREE_LIST_FIRST_EXP, lib.qcgc_small_free_lists + 1) last_exp = lib.QCGC_LARGE_FREE_LIST_FIRST_EXP + lib.qcgc_large_free_lists - 1 self.assertLess(2**last_exp, 2**lib.QCGC_ARENA_SIZE_EXP) self.assertEqual(2**(last_exp + 1), 2**lib.QCGC_ARENA_SIZE_EXP) def test_small_free_list_index(self): for i in range(1, lib.qcgc_small_free_lists + 1): self.assertTrue(lib.is_small(i)) self.assertEqual(lib.small_index(i), i - 1); self.assertTrue(lib.small_index_to_cells(i - 1), i); def test_large_free_list_index(self): index = -1; for i in range(2**lib.QCGC_LARGE_FREE_LIST_FIRST_EXP, 2**lib.QCGC_ARENA_SIZE_EXP): if (i & (i - 1) == 0): # Check for power of two index = index + 1 self.assertFalse(lib.is_small(i)) self.assertEqual(index, lib.large_index(i));
# ... existing code ... self.assertEqual(lib.small_index(i), i - 1); self.assertTrue(lib.small_index_to_cells(i - 1), i); # ... rest of the code ...
1af3111e4f2422c1d6484c237700013386d4638d
minutes/forms.py
minutes/forms.py
from django.forms import ModelForm, Textarea, ChoiceField from django.urls import reverse_lazy from .models import Meeting, Folder MD_INPUT = { 'class': 'markdown-input', 'data-endpoint': reverse_lazy('utilities:preview_safe') } def sorted_folders(): return sorted([(x.pk, str(x)) for x in Folder.objects.all()], key=lambda x: x[1]) class MeetingForm(ModelForm): folder = ChoiceField(choices=sorted_folders) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) class Meta: model = Meeting fields = ['name', 'folder', 'title', 'body', 'date'] widgets = { 'body': Textarea(attrs=MD_INPUT), } def clean_folder(self): return Folder.objects.get(pk=self.cleaned_data['folder'])
from django.forms import ModelForm, Textarea, ChoiceField from django.utils.functional import lazy from .models import Meeting, Folder MD_INPUT = { 'class': 'markdown-input' } def sorted_folders(): return sorted([(x.pk, str(x)) for x in Folder.objects.all()], key=lambda x: x[1]) class MeetingForm(ModelForm): folder = ChoiceField(choices=sorted_folders) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) class Meta: model = Meeting fields = ['name', 'folder', 'title', 'body', 'date'] widgets = { 'body': Textarea(attrs=MD_INPUT), } def clean_folder(self): return Folder.objects.get(pk=self.cleaned_data['folder'])
Revert "Allow admin preview in minutes as well"
Revert "Allow admin preview in minutes as well" This reverts commit f4806655
Python
isc
ashbc/tgrsite,ashbc/tgrsite,ashbc/tgrsite
from django.forms import ModelForm, Textarea, ChoiceField - from django.urls import reverse_lazy + from django.utils.functional import lazy from .models import Meeting, Folder MD_INPUT = { - 'class': 'markdown-input', + 'class': 'markdown-input' - 'data-endpoint': reverse_lazy('utilities:preview_safe') } def sorted_folders(): return sorted([(x.pk, str(x)) for x in Folder.objects.all()], key=lambda x: x[1]) class MeetingForm(ModelForm): folder = ChoiceField(choices=sorted_folders) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) class Meta: model = Meeting fields = ['name', 'folder', 'title', 'body', 'date'] widgets = { 'body': Textarea(attrs=MD_INPUT), } def clean_folder(self): return Folder.objects.get(pk=self.cleaned_data['folder'])
Revert "Allow admin preview in minutes as well"
## Code Before: from django.forms import ModelForm, Textarea, ChoiceField from django.urls import reverse_lazy from .models import Meeting, Folder MD_INPUT = { 'class': 'markdown-input', 'data-endpoint': reverse_lazy('utilities:preview_safe') } def sorted_folders(): return sorted([(x.pk, str(x)) for x in Folder.objects.all()], key=lambda x: x[1]) class MeetingForm(ModelForm): folder = ChoiceField(choices=sorted_folders) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) class Meta: model = Meeting fields = ['name', 'folder', 'title', 'body', 'date'] widgets = { 'body': Textarea(attrs=MD_INPUT), } def clean_folder(self): return Folder.objects.get(pk=self.cleaned_data['folder']) ## Instruction: Revert "Allow admin preview in minutes as well" ## Code After: from django.forms import ModelForm, Textarea, ChoiceField from django.utils.functional import lazy from .models import Meeting, Folder MD_INPUT = { 'class': 'markdown-input' } def sorted_folders(): return sorted([(x.pk, str(x)) for x in Folder.objects.all()], key=lambda x: x[1]) class MeetingForm(ModelForm): folder = ChoiceField(choices=sorted_folders) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) class Meta: model = Meeting fields = ['name', 'folder', 'title', 'body', 'date'] widgets = { 'body': Textarea(attrs=MD_INPUT), } def clean_folder(self): return Folder.objects.get(pk=self.cleaned_data['folder'])
... from django.forms import ModelForm, Textarea, ChoiceField from django.utils.functional import lazy ... MD_INPUT = { 'class': 'markdown-input' } ...
e27f04e9c8d5d74afdd9cd7d6990cad5ff6f6cb5
api/v330/docking_event/serializers.py
api/v330/docking_event/serializers.py
from api.v330.common.serializers import * class SpacecraftFlightSerializerForDockingEvent(serializers.HyperlinkedModelSerializer): spacecraft = SpacecraftSerializer(read_only=True, many=False) class Meta: model = SpacecraftFlight fields = ('id', 'url', 'destination', 'splashdown', 'spacecraft') class DockingEventSerializer(serializers.HyperlinkedModelSerializer): flight_vehicle = SpacecraftFlightSerializerForDockingEvent(read_only=True) docking_location = serializers.StringRelatedField(many=False, read_only=True) class Meta: model = DockingEvent fields = ('id', 'url', 'docking', 'departure', 'flight_vehicle', 'docking_location') class DockingEventDetailedSerializer(serializers.HyperlinkedModelSerializer): flight_vehicle = SpacecraftFlightSerializerForDockingEvent(read_only=True, many=False) docking_location = serializers.StringRelatedField(many=False, read_only=True) class Meta: model = DockingEvent fields = ('id', 'url', 'docking', 'departure', 'flight_vehicle', 'docking_location')
from api.v330.common.serializers import * class SpacecraftFlightSerializerForDockingEvent(serializers.HyperlinkedModelSerializer): spacecraft = SpacecraftSerializer(read_only=True, many=False) class Meta: model = SpacecraftFlight fields = ('id', 'url', 'destination', 'splashdown', 'spacecraft') class SpaceStationSerializerForDockingEvent(serializers.HyperlinkedModelSerializer): class Meta: model = SpaceStation fields = ('id', 'url', 'name', 'image_url') class DockingEventSerializer(serializers.HyperlinkedModelSerializer): flight_vehicle = SpacecraftFlightSerializerForDockingEvent(read_only=True) docking_location = serializers.StringRelatedField(many=False, read_only=True) class Meta: model = DockingEvent fields = ('id', 'url', 'docking', 'departure', 'flight_vehicle', 'docking_location') class DockingEventDetailedSerializer(serializers.HyperlinkedModelSerializer): flight_vehicle = SpacecraftFlightSerializerForDockingEvent(read_only=True, many=False) docking_location = serializers.StringRelatedField(many=False, read_only=True) space_station = SpaceStationSerializerForDockingEvent(many=False, read_only=True) class Meta: model = DockingEvent fields = ('id', 'url', 'docking', 'departure', 'flight_vehicle', 'docking_location', 'space_station')
Add space_station field to detailed docking event
Add space_station field to detailed docking event
Python
apache-2.0
ItsCalebJones/SpaceLaunchNow-Server,ItsCalebJones/SpaceLaunchNow-Server,ItsCalebJones/SpaceLaunchNow-Server
from api.v330.common.serializers import * class SpacecraftFlightSerializerForDockingEvent(serializers.HyperlinkedModelSerializer): spacecraft = SpacecraftSerializer(read_only=True, many=False) class Meta: model = SpacecraftFlight fields = ('id', 'url', 'destination', 'splashdown', 'spacecraft') + + + class SpaceStationSerializerForDockingEvent(serializers.HyperlinkedModelSerializer): + class Meta: + model = SpaceStation + fields = ('id', 'url', 'name', 'image_url') class DockingEventSerializer(serializers.HyperlinkedModelSerializer): flight_vehicle = SpacecraftFlightSerializerForDockingEvent(read_only=True) docking_location = serializers.StringRelatedField(many=False, read_only=True) class Meta: model = DockingEvent fields = ('id', 'url', 'docking', 'departure', 'flight_vehicle', 'docking_location') class DockingEventDetailedSerializer(serializers.HyperlinkedModelSerializer): flight_vehicle = SpacecraftFlightSerializerForDockingEvent(read_only=True, many=False) docking_location = serializers.StringRelatedField(many=False, read_only=True) + space_station = SpaceStationSerializerForDockingEvent(many=False, read_only=True) class Meta: model = DockingEvent - fields = ('id', 'url', 'docking', 'departure', 'flight_vehicle', 'docking_location') + fields = ('id', 'url', 'docking', 'departure', 'flight_vehicle', 'docking_location', 'space_station')
Add space_station field to detailed docking event
## Code Before: from api.v330.common.serializers import * class SpacecraftFlightSerializerForDockingEvent(serializers.HyperlinkedModelSerializer): spacecraft = SpacecraftSerializer(read_only=True, many=False) class Meta: model = SpacecraftFlight fields = ('id', 'url', 'destination', 'splashdown', 'spacecraft') class DockingEventSerializer(serializers.HyperlinkedModelSerializer): flight_vehicle = SpacecraftFlightSerializerForDockingEvent(read_only=True) docking_location = serializers.StringRelatedField(many=False, read_only=True) class Meta: model = DockingEvent fields = ('id', 'url', 'docking', 'departure', 'flight_vehicle', 'docking_location') class DockingEventDetailedSerializer(serializers.HyperlinkedModelSerializer): flight_vehicle = SpacecraftFlightSerializerForDockingEvent(read_only=True, many=False) docking_location = serializers.StringRelatedField(many=False, read_only=True) class Meta: model = DockingEvent fields = ('id', 'url', 'docking', 'departure', 'flight_vehicle', 'docking_location') ## Instruction: Add space_station field to detailed docking event ## Code After: from api.v330.common.serializers import * class SpacecraftFlightSerializerForDockingEvent(serializers.HyperlinkedModelSerializer): spacecraft = SpacecraftSerializer(read_only=True, many=False) class Meta: model = SpacecraftFlight fields = ('id', 'url', 'destination', 'splashdown', 'spacecraft') class SpaceStationSerializerForDockingEvent(serializers.HyperlinkedModelSerializer): class Meta: model = SpaceStation fields = ('id', 'url', 'name', 'image_url') class DockingEventSerializer(serializers.HyperlinkedModelSerializer): flight_vehicle = SpacecraftFlightSerializerForDockingEvent(read_only=True) docking_location = serializers.StringRelatedField(many=False, read_only=True) class Meta: model = DockingEvent fields = ('id', 'url', 'docking', 'departure', 'flight_vehicle', 'docking_location') class DockingEventDetailedSerializer(serializers.HyperlinkedModelSerializer): flight_vehicle = SpacecraftFlightSerializerForDockingEvent(read_only=True, many=False) docking_location = serializers.StringRelatedField(many=False, read_only=True) space_station = SpaceStationSerializerForDockingEvent(many=False, read_only=True) class Meta: model = DockingEvent fields = ('id', 'url', 'docking', 'departure', 'flight_vehicle', 'docking_location', 'space_station')
// ... existing code ... fields = ('id', 'url', 'destination', 'splashdown', 'spacecraft') class SpaceStationSerializerForDockingEvent(serializers.HyperlinkedModelSerializer): class Meta: model = SpaceStation fields = ('id', 'url', 'name', 'image_url') // ... modified code ... docking_location = serializers.StringRelatedField(many=False, read_only=True) space_station = SpaceStationSerializerForDockingEvent(many=False, read_only=True) ... model = DockingEvent fields = ('id', 'url', 'docking', 'departure', 'flight_vehicle', 'docking_location', 'space_station') // ... rest of the code ...
7873996d49ad32984465086623a3f6537eae11af
nbgrader/preprocessors/headerfooter.py
nbgrader/preprocessors/headerfooter.py
from IPython.nbconvert.preprocessors import Preprocessor from IPython.nbformat.current import read as read_nb from IPython.utils.traitlets import Unicode class IncludeHeaderFooter(Preprocessor): """A preprocessor for adding header and/or footer cells to a notebook.""" header = Unicode("", config=True, help="Path to header notebook") footer = Unicode("", config=True, help="Path to footer notebook") def preprocess(self, nb, resources): """Concatenates the cells from the header and footer notebooks to the given cells. """ new_cells = [] # header if self.header != "": with open(self.header, 'r') as fh: header_nb = read_nb(fh, 'ipynb') new_cells.extend(header_nb.worksheets[0].cells) # body new_cells.extend(nb.worksheets[0].cells) # footer if self.footer != "": with open(self.footer, 'r') as fh: footer_nb = read_nb(fh, 'ipynb') new_cells.extend(footer_nb.worksheets[0].cells) nb.worksheets[0].cells = new_cells super(IncludeHeaderFooter, self).preprocess(nb, resources) return nb, resources def preprocess_cell(self, cell, resources, cell_index): return cell, resources
from IPython.nbconvert.preprocessors import Preprocessor from IPython.nbformat.current import read as read_nb from IPython.utils.traitlets import Unicode class IncludeHeaderFooter(Preprocessor): """A preprocessor for adding header and/or footer cells to a notebook.""" header = Unicode("", config=True, help="Path to header notebook") footer = Unicode("", config=True, help="Path to footer notebook") def preprocess(self, nb, resources): """Concatenates the cells from the header and footer notebooks to the given cells. """ new_cells = [] # header if self.header: with open(self.header, 'r') as fh: header_nb = read_nb(fh, 'ipynb') new_cells.extend(header_nb.worksheets[0].cells) # body new_cells.extend(nb.worksheets[0].cells) # footer if self.footer: with open(self.footer, 'r') as fh: footer_nb = read_nb(fh, 'ipynb') new_cells.extend(footer_nb.worksheets[0].cells) nb.worksheets[0].cells = new_cells super(IncludeHeaderFooter, self).preprocess(nb, resources) return nb, resources def preprocess_cell(self, cell, resources, cell_index): return cell, resources
Fix if statements checking if header/footer exist
Fix if statements checking if header/footer exist
Python
bsd-3-clause
jhamrick/nbgrader,jupyter/nbgrader,jupyter/nbgrader,jhamrick/nbgrader,EdwardJKim/nbgrader,ellisonbg/nbgrader,EdwardJKim/nbgrader,jupyter/nbgrader,jupyter/nbgrader,EdwardJKim/nbgrader,ellisonbg/nbgrader,MatKallada/nbgrader,ellisonbg/nbgrader,modulexcite/nbgrader,jhamrick/nbgrader,EdwardJKim/nbgrader,jdfreder/nbgrader,jdfreder/nbgrader,jupyter/nbgrader,alope107/nbgrader,MatKallada/nbgrader,modulexcite/nbgrader,dementrock/nbgrader,jhamrick/nbgrader,ellisonbg/nbgrader,alope107/nbgrader,dementrock/nbgrader
from IPython.nbconvert.preprocessors import Preprocessor from IPython.nbformat.current import read as read_nb from IPython.utils.traitlets import Unicode class IncludeHeaderFooter(Preprocessor): """A preprocessor for adding header and/or footer cells to a notebook.""" header = Unicode("", config=True, help="Path to header notebook") footer = Unicode("", config=True, help="Path to footer notebook") def preprocess(self, nb, resources): """Concatenates the cells from the header and footer notebooks to the given cells. """ new_cells = [] # header - if self.header != "": + if self.header: with open(self.header, 'r') as fh: header_nb = read_nb(fh, 'ipynb') new_cells.extend(header_nb.worksheets[0].cells) # body new_cells.extend(nb.worksheets[0].cells) # footer - if self.footer != "": + if self.footer: with open(self.footer, 'r') as fh: footer_nb = read_nb(fh, 'ipynb') new_cells.extend(footer_nb.worksheets[0].cells) nb.worksheets[0].cells = new_cells super(IncludeHeaderFooter, self).preprocess(nb, resources) return nb, resources def preprocess_cell(self, cell, resources, cell_index): return cell, resources
Fix if statements checking if header/footer exist
## Code Before: from IPython.nbconvert.preprocessors import Preprocessor from IPython.nbformat.current import read as read_nb from IPython.utils.traitlets import Unicode class IncludeHeaderFooter(Preprocessor): """A preprocessor for adding header and/or footer cells to a notebook.""" header = Unicode("", config=True, help="Path to header notebook") footer = Unicode("", config=True, help="Path to footer notebook") def preprocess(self, nb, resources): """Concatenates the cells from the header and footer notebooks to the given cells. """ new_cells = [] # header if self.header != "": with open(self.header, 'r') as fh: header_nb = read_nb(fh, 'ipynb') new_cells.extend(header_nb.worksheets[0].cells) # body new_cells.extend(nb.worksheets[0].cells) # footer if self.footer != "": with open(self.footer, 'r') as fh: footer_nb = read_nb(fh, 'ipynb') new_cells.extend(footer_nb.worksheets[0].cells) nb.worksheets[0].cells = new_cells super(IncludeHeaderFooter, self).preprocess(nb, resources) return nb, resources def preprocess_cell(self, cell, resources, cell_index): return cell, resources ## Instruction: Fix if statements checking if header/footer exist ## Code After: from IPython.nbconvert.preprocessors import Preprocessor from IPython.nbformat.current import read as read_nb from IPython.utils.traitlets import Unicode class IncludeHeaderFooter(Preprocessor): """A preprocessor for adding header and/or footer cells to a notebook.""" header = Unicode("", config=True, help="Path to header notebook") footer = Unicode("", config=True, help="Path to footer notebook") def preprocess(self, nb, resources): """Concatenates the cells from the header and footer notebooks to the given cells. """ new_cells = [] # header if self.header: with open(self.header, 'r') as fh: header_nb = read_nb(fh, 'ipynb') new_cells.extend(header_nb.worksheets[0].cells) # body new_cells.extend(nb.worksheets[0].cells) # footer if self.footer: with open(self.footer, 'r') as fh: footer_nb = read_nb(fh, 'ipynb') new_cells.extend(footer_nb.worksheets[0].cells) nb.worksheets[0].cells = new_cells super(IncludeHeaderFooter, self).preprocess(nb, resources) return nb, resources def preprocess_cell(self, cell, resources, cell_index): return cell, resources
// ... existing code ... # header if self.header: with open(self.header, 'r') as fh: // ... modified code ... # footer if self.footer: with open(self.footer, 'r') as fh: // ... rest of the code ...
58d131e8aceb1adbbcdce2e1d4a86f5fb4615196
Lib/xml/__init__.py
Lib/xml/__init__.py
if __name__ == "xml": try: import _xmlplus except ImportError: pass else: import sys sys.modules[__name__] = _xmlplus
try: import _xmlplus except ImportError: pass else: import sys sys.modules[__name__] = _xmlplus
Remove the outer test for __name__; not necessary.
Remove the outer test for __name__; not necessary.
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
+ try: - if __name__ == "xml": - try: - import _xmlplus + import _xmlplus - except ImportError: + except ImportError: - pass + pass - else: + else: - import sys + import sys - sys.modules[__name__] = _xmlplus + sys.modules[__name__] = _xmlplus
Remove the outer test for __name__; not necessary.
## Code Before: if __name__ == "xml": try: import _xmlplus except ImportError: pass else: import sys sys.modules[__name__] = _xmlplus ## Instruction: Remove the outer test for __name__; not necessary. ## Code After: try: import _xmlplus except ImportError: pass else: import sys sys.modules[__name__] = _xmlplus
... try: import _xmlplus except ImportError: pass else: import sys sys.modules[__name__] = _xmlplus ...
7e11e57ee4f9fc1dc3c967c9b2d26038a7727f72
wqflask/wqflask/database.py
wqflask/wqflask/database.py
import os import sys from string import Template from typing import Tuple from urllib.parse import urlparse import importlib import MySQLdb from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.ext.declarative import declarative_base def read_from_pyfile(pyfile, setting): orig_sys_path = sys.path[:] sys.path.insert(0, os.path.dirname(pyfile)) module = importlib.import_module(os.path.basename(pyfile).strip(".py")) sys.path = orig_sys_path[:] return module.__dict__.get(setting) def sql_uri(): """Read the SQL_URI from the environment or settings file.""" return os.environ.get( "SQL_URI", read_from_pyfile( os.environ.get( "GN2_SETTINGS", os.path.abspath("../etc/default_settings.py")), "SQL_URI")) def parse_db_url(sql_uri: str) -> Tuple: """ Parse SQL_URI env variable from an sql URI e.g. 'mysql://user:pass@host_name/db_name' """ parsed_db = urlparse(sql_uri) return ( parsed_db.hostname, parsed_db.username, parsed_db.password, parsed_db.path[1:], parsed_db.port) def database_connection(): """Returns a database connection""" host, user, passwd, db_name, port = parse_db_url(sql_uri()) return MySQLdb.connect( db=db_name, user=user, passwd=passwd, host=host, port=port)
import os import sys from string import Template from typing import Tuple from urllib.parse import urlparse import importlib import MySQLdb def sql_uri(): """Read the SQL_URI from the environment or settings file.""" return os.environ.get( "SQL_URI", read_from_pyfile( os.environ.get( "GN2_SETTINGS", os.path.abspath("../etc/default_settings.py")), "SQL_URI")) def parse_db_url(sql_uri: str) -> Tuple: """ Parse SQL_URI env variable from an sql URI e.g. 'mysql://user:pass@host_name/db_name' """ parsed_db = urlparse(sql_uri) return ( parsed_db.hostname, parsed_db.username, parsed_db.password, parsed_db.path[1:], parsed_db.port) def database_connection(): """Returns a database connection""" host, user, passwd, db_name, port = parse_db_url(sql_uri()) return MySQLdb.connect( db=db_name, user=user, passwd=passwd, host=host, port=port)
Delete unused function and imports.
Delete unused function and imports. * wqflask/wqflask/database.py: Remove unused sqlalchemy imports. (read_from_pyfile): Delete it.
Python
agpl-3.0
genenetwork/genenetwork2,genenetwork/genenetwork2,genenetwork/genenetwork2,genenetwork/genenetwork2
import os import sys from string import Template from typing import Tuple from urllib.parse import urlparse import importlib import MySQLdb - from sqlalchemy import create_engine - from sqlalchemy.orm import scoped_session, sessionmaker - from sqlalchemy.ext.declarative import declarative_base - - def read_from_pyfile(pyfile, setting): - orig_sys_path = sys.path[:] - sys.path.insert(0, os.path.dirname(pyfile)) - module = importlib.import_module(os.path.basename(pyfile).strip(".py")) - sys.path = orig_sys_path[:] - return module.__dict__.get(setting) def sql_uri(): """Read the SQL_URI from the environment or settings file.""" return os.environ.get( "SQL_URI", read_from_pyfile( os.environ.get( "GN2_SETTINGS", os.path.abspath("../etc/default_settings.py")), "SQL_URI")) def parse_db_url(sql_uri: str) -> Tuple: """ Parse SQL_URI env variable from an sql URI e.g. 'mysql://user:pass@host_name/db_name' """ parsed_db = urlparse(sql_uri) return ( parsed_db.hostname, parsed_db.username, parsed_db.password, parsed_db.path[1:], parsed_db.port) def database_connection(): """Returns a database connection""" host, user, passwd, db_name, port = parse_db_url(sql_uri()) return MySQLdb.connect( db=db_name, user=user, passwd=passwd, host=host, port=port)
Delete unused function and imports.
## Code Before: import os import sys from string import Template from typing import Tuple from urllib.parse import urlparse import importlib import MySQLdb from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.ext.declarative import declarative_base def read_from_pyfile(pyfile, setting): orig_sys_path = sys.path[:] sys.path.insert(0, os.path.dirname(pyfile)) module = importlib.import_module(os.path.basename(pyfile).strip(".py")) sys.path = orig_sys_path[:] return module.__dict__.get(setting) def sql_uri(): """Read the SQL_URI from the environment or settings file.""" return os.environ.get( "SQL_URI", read_from_pyfile( os.environ.get( "GN2_SETTINGS", os.path.abspath("../etc/default_settings.py")), "SQL_URI")) def parse_db_url(sql_uri: str) -> Tuple: """ Parse SQL_URI env variable from an sql URI e.g. 'mysql://user:pass@host_name/db_name' """ parsed_db = urlparse(sql_uri) return ( parsed_db.hostname, parsed_db.username, parsed_db.password, parsed_db.path[1:], parsed_db.port) def database_connection(): """Returns a database connection""" host, user, passwd, db_name, port = parse_db_url(sql_uri()) return MySQLdb.connect( db=db_name, user=user, passwd=passwd, host=host, port=port) ## Instruction: Delete unused function and imports. ## Code After: import os import sys from string import Template from typing import Tuple from urllib.parse import urlparse import importlib import MySQLdb def sql_uri(): """Read the SQL_URI from the environment or settings file.""" return os.environ.get( "SQL_URI", read_from_pyfile( os.environ.get( "GN2_SETTINGS", os.path.abspath("../etc/default_settings.py")), "SQL_URI")) def parse_db_url(sql_uri: str) -> Tuple: """ Parse SQL_URI env variable from an sql URI e.g. 'mysql://user:pass@host_name/db_name' """ parsed_db = urlparse(sql_uri) return ( parsed_db.hostname, parsed_db.username, parsed_db.password, parsed_db.path[1:], parsed_db.port) def database_connection(): """Returns a database connection""" host, user, passwd, db_name, port = parse_db_url(sql_uri()) return MySQLdb.connect( db=db_name, user=user, passwd=passwd, host=host, port=port)
# ... existing code ... # ... rest of the code ...
8a0953345279c40e3b3cf63a748e8ca7b3ad0199
test_urlconf.py
test_urlconf.py
from django.conf.urls import patterns, url, include from django.contrib import admin admin.autodiscover() urlpatterns = patterns( '', url(r'^admin/', include(admin.site.urls)), )
from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', include(admin.site.urls)), ]
Test urls - list of urls instead of patterns()
Test urls - list of urls instead of patterns()
Python
isc
yprez/django-logentry-admin,yprez/django-logentry-admin
- from django.conf.urls import patterns, url, include + from django.conf.urls import url, include from django.contrib import admin - admin.autodiscover() + urlpatterns = [ + url(r'^admin/', include(admin.site.urls)), + ] - - urlpatterns = patterns( - '', - url(r'^admin/', include(admin.site.urls)), - ) -
Test urls - list of urls instead of patterns()
## Code Before: from django.conf.urls import patterns, url, include from django.contrib import admin admin.autodiscover() urlpatterns = patterns( '', url(r'^admin/', include(admin.site.urls)), ) ## Instruction: Test urls - list of urls instead of patterns() ## Code After: from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', include(admin.site.urls)), ]
// ... existing code ... from django.conf.urls import url, include from django.contrib import admin // ... modified code ... urlpatterns = [ url(r'^admin/', include(admin.site.urls)), ] // ... rest of the code ...
47530321c413976241e0d4e314f2a8e1532f38c9
hackarena/utilities.py
hackarena/utilities.py
class Utilities(object): def get_session_string(self, original_session_string): session_attributes = original_session_string.split(' ') return session_attributes[0] + ' ' + session_attributes[1] def get_session_middle_part(self, original_session_string): return original_session_string.split(' ')[1] def generate_random_name(self, original_session_string): # Should get improved return self.get_session_middle_part(original_session_string)
class Utilities(object): @classmethod def get_session_string(cls, original_session_string): session_attributes = original_session_string.split(' ') return session_attributes[0] + ' ' + session_attributes[1] @classmethod def get_session_middle_part(cls, original_session_string): return original_session_string.split(' ')[1]
Fix classmethods on utility class
Fix classmethods on utility class
Python
mit
verekia/hackarena,verekia/hackarena,verekia/hackarena,verekia/hackarena
class Utilities(object): + + @classmethod - def get_session_string(self, original_session_string): + def get_session_string(cls, original_session_string): session_attributes = original_session_string.split(' ') return session_attributes[0] + ' ' + session_attributes[1] + @classmethod - def get_session_middle_part(self, original_session_string): + def get_session_middle_part(cls, original_session_string): return original_session_string.split(' ')[1] - def generate_random_name(self, original_session_string): - # Should get improved - return self.get_session_middle_part(original_session_string) -
Fix classmethods on utility class
## Code Before: class Utilities(object): def get_session_string(self, original_session_string): session_attributes = original_session_string.split(' ') return session_attributes[0] + ' ' + session_attributes[1] def get_session_middle_part(self, original_session_string): return original_session_string.split(' ')[1] def generate_random_name(self, original_session_string): # Should get improved return self.get_session_middle_part(original_session_string) ## Instruction: Fix classmethods on utility class ## Code After: class Utilities(object): @classmethod def get_session_string(cls, original_session_string): session_attributes = original_session_string.split(' ') return session_attributes[0] + ' ' + session_attributes[1] @classmethod def get_session_middle_part(cls, original_session_string): return original_session_string.split(' ')[1]
# ... existing code ... class Utilities(object): @classmethod def get_session_string(cls, original_session_string): session_attributes = original_session_string.split(' ') # ... modified code ... @classmethod def get_session_middle_part(cls, original_session_string): return original_session_string.split(' ')[1] # ... rest of the code ...
273c7b89f02469ef1a6c53b6287412cd48881428
matador/commands/deployment/deployment.py
matador/commands/deployment/deployment.py
import logging import subprocess import re def substitute_keywords(text, repo_folder, commit): substitutions = { 'version': commit, 'date': subprocess.check_output( ['git', '-C', repo_folder, 'show', '-s', '--format=%ci', commit], stderr=subprocess.STDOUT), } new_text = None for line in text: for key, value in substitutions.items(): rexp = '%s:.*' % key line = re.sub(rexp, '%s: %s' % (key, value), line) new_text += line return new_text class DeploymentCommand(object): def __init__(self, *args): self._logger = logging.getLogger(__name__) self.args = args self._execute() def _execute(self): raise NotImplementedError
import logging import subprocess import re def substitute_keywords(text, repo_folder, commit): substitutions = { 'version': commit, 'date': subprocess.check_output( ['git', '-C', repo_folder, 'show', '-s', '--format=%ci', commit], stderr=subprocess.STDOUT), } new_text = '' for line in text.splitlines(keepends=True): for key, value in substitutions.items(): rexp = '%s:.*' % key line = re.sub(rexp, '%s: %s' % (key, value), line) new_text += line return new_text class DeploymentCommand(object): def __init__(self, *args): self._logger = logging.getLogger(__name__) self.args = args self._execute() def _execute(self): raise NotImplementedError
Add splitlines method to substitute_keywords
Add splitlines method to substitute_keywords
Python
mit
Empiria/matador
import logging import subprocess import re def substitute_keywords(text, repo_folder, commit): substitutions = { 'version': commit, 'date': subprocess.check_output( ['git', '-C', repo_folder, 'show', '-s', '--format=%ci', commit], stderr=subprocess.STDOUT), } - new_text = None + new_text = '' - for line in text: + for line in text.splitlines(keepends=True): for key, value in substitutions.items(): rexp = '%s:.*' % key line = re.sub(rexp, '%s: %s' % (key, value), line) new_text += line return new_text class DeploymentCommand(object): def __init__(self, *args): self._logger = logging.getLogger(__name__) self.args = args self._execute() def _execute(self): raise NotImplementedError
Add splitlines method to substitute_keywords
## Code Before: import logging import subprocess import re def substitute_keywords(text, repo_folder, commit): substitutions = { 'version': commit, 'date': subprocess.check_output( ['git', '-C', repo_folder, 'show', '-s', '--format=%ci', commit], stderr=subprocess.STDOUT), } new_text = None for line in text: for key, value in substitutions.items(): rexp = '%s:.*' % key line = re.sub(rexp, '%s: %s' % (key, value), line) new_text += line return new_text class DeploymentCommand(object): def __init__(self, *args): self._logger = logging.getLogger(__name__) self.args = args self._execute() def _execute(self): raise NotImplementedError ## Instruction: Add splitlines method to substitute_keywords ## Code After: import logging import subprocess import re def substitute_keywords(text, repo_folder, commit): substitutions = { 'version': commit, 'date': subprocess.check_output( ['git', '-C', repo_folder, 'show', '-s', '--format=%ci', commit], stderr=subprocess.STDOUT), } new_text = '' for line in text.splitlines(keepends=True): for key, value in substitutions.items(): rexp = '%s:.*' % key line = re.sub(rexp, '%s: %s' % (key, value), line) new_text += line return new_text class DeploymentCommand(object): def __init__(self, *args): self._logger = logging.getLogger(__name__) self.args = args self._execute() def _execute(self): raise NotImplementedError
// ... existing code ... } new_text = '' for line in text.splitlines(keepends=True): for key, value in substitutions.items(): // ... rest of the code ...
5a43c61c0688e2837492e7f034a0dd2c157c6e4d
hypatia/__init__.py
hypatia/__init__.py
__author__ = "Lillian Lemmer" __copyright__ = "Copyright 2015 Lillian Lemmer" __credits__ = ["Lillian Lemmer"] __license__ = "MIT" __maintainer__ = __author__ __site__ = "http://lillian-lemmer.github.io/hypatia/" __email__ = "[email protected]" __status__ = "Development" __version__ = "0.2.8" __contributors__ = [ "Lillian Lemmer", "Brian Houston Morrow", "Eric James Michael Ritz" ]
__author__ = "Lillian Lemmer" __copyright__ = "Copyright 2015 Lillian Lemmer" __credits__ = ["Lillian Lemmer"] __license__ = "MIT" __maintainer__ = __author__ __site__ = "http://lillian-lemmer.github.io/hypatia/" __email__ = "[email protected]" __status__ = "Development" class Version: """A represntation of Hypatia's current version. This class contains integer fields for the major, minor, and patch version numbers, respectively. This is useful for comparison within code if it becomes necessary to have code behave differently based on the version, e.g. for backwards compatibility. The class also supports str() which converts an instance into a human-readable string, e.g. '0.2.8'. Public Properties: * major * minor * patch """ def __init__(self, major, minor, patch): self.major = major self.minor = minor self.patch = patch def __str__(self): return "%d.%d.%d" % (self.major, self.minor, self.patch) # str(__version__) will produce a string like "0.2.8" __version__ = Version(0, 2, 8) __contributors__ = [ "Lillian Lemmer", "Brian Houston Morrow", "Eric James Michael Ritz" ]
Add a class for representing the current version
[Feature] Add a class for representing the current version This patch implements the `Version` class inside of the `__init__.py` file alongside the rest of Hypatia's meta-data. The class has public integer properties representing the major, minor, and patch portions of the version number. This makes it possible for other code in the engine to support or deprecate features based on the version by comparing their numeric values, e.g. if Version.major < 3: # Report some error about a deprecated feature. The `Version` class also implements `__str__()` so that it is possible to convert `__version__` into a string, e.g. for `print()`, for the purpose of output, e.g. print(__version__) # "0.2.8" Signed-off-by: Eric James Michael Ritz <[email protected]>
Python
mit
lillian-lemmer/hypatia,hypatia-software-org/hypatia-engine,brechin/hypatia,lillian-lemmer/hypatia,hypatia-software-org/hypatia-engine,Applemann/hypatia,Applemann/hypatia,brechin/hypatia
__author__ = "Lillian Lemmer" __copyright__ = "Copyright 2015 Lillian Lemmer" __credits__ = ["Lillian Lemmer"] __license__ = "MIT" __maintainer__ = __author__ __site__ = "http://lillian-lemmer.github.io/hypatia/" __email__ = "[email protected]" __status__ = "Development" - __version__ = "0.2.8" + + + + class Version: + """A represntation of Hypatia's current version. + + This class contains integer fields for the major, minor, and patch + version numbers, respectively. This is useful for comparison + within code if it becomes necessary to have code behave + differently based on the version, e.g. for backwards + compatibility. The class also supports str() which converts an + instance into a human-readable string, e.g. '0.2.8'. + + Public Properties: + + * major + * minor + * patch + + """ + def __init__(self, major, minor, patch): + self.major = major + self.minor = minor + self.patch = patch + + def __str__(self): + return "%d.%d.%d" % (self.major, self.minor, self.patch) + + + # str(__version__) will produce a string like "0.2.8" + __version__ = Version(0, 2, 8) + + __contributors__ = [ "Lillian Lemmer", "Brian Houston Morrow", "Eric James Michael Ritz" ]
Add a class for representing the current version
## Code Before: __author__ = "Lillian Lemmer" __copyright__ = "Copyright 2015 Lillian Lemmer" __credits__ = ["Lillian Lemmer"] __license__ = "MIT" __maintainer__ = __author__ __site__ = "http://lillian-lemmer.github.io/hypatia/" __email__ = "[email protected]" __status__ = "Development" __version__ = "0.2.8" __contributors__ = [ "Lillian Lemmer", "Brian Houston Morrow", "Eric James Michael Ritz" ] ## Instruction: Add a class for representing the current version ## Code After: __author__ = "Lillian Lemmer" __copyright__ = "Copyright 2015 Lillian Lemmer" __credits__ = ["Lillian Lemmer"] __license__ = "MIT" __maintainer__ = __author__ __site__ = "http://lillian-lemmer.github.io/hypatia/" __email__ = "[email protected]" __status__ = "Development" class Version: """A represntation of Hypatia's current version. This class contains integer fields for the major, minor, and patch version numbers, respectively. This is useful for comparison within code if it becomes necessary to have code behave differently based on the version, e.g. for backwards compatibility. The class also supports str() which converts an instance into a human-readable string, e.g. '0.2.8'. Public Properties: * major * minor * patch """ def __init__(self, major, minor, patch): self.major = major self.minor = minor self.patch = patch def __str__(self): return "%d.%d.%d" % (self.major, self.minor, self.patch) # str(__version__) will produce a string like "0.2.8" __version__ = Version(0, 2, 8) __contributors__ = [ "Lillian Lemmer", "Brian Houston Morrow", "Eric James Michael Ritz" ]
// ... existing code ... __status__ = "Development" class Version: """A represntation of Hypatia's current version. This class contains integer fields for the major, minor, and patch version numbers, respectively. This is useful for comparison within code if it becomes necessary to have code behave differently based on the version, e.g. for backwards compatibility. The class also supports str() which converts an instance into a human-readable string, e.g. '0.2.8'. Public Properties: * major * minor * patch """ def __init__(self, major, minor, patch): self.major = major self.minor = minor self.patch = patch def __str__(self): return "%d.%d.%d" % (self.major, self.minor, self.patch) # str(__version__) will produce a string like "0.2.8" __version__ = Version(0, 2, 8) // ... rest of the code ...
e05ea934335eac29c0b2f164eab600008546324c
recurring_contract/migrations/1.2/post-migration.py
recurring_contract/migrations/1.2/post-migration.py
import sys def migrate(cr, version): reload(sys) sys.setdefaultencoding('UTF8') if not version: return delay_dict = {'annual': 12, 'biannual': 6, 'fourmonthly': 4, 'quarterly': 3, 'bimonthly': 2, 'monthly': 1} cr.execute( ''' SELECT id, advance_billing FROM recurring_contract_group ''' ) contract_groups = cr.fetchall() for contract_group in contract_groups: delay = delay_dict[contract_group[1]] or 1 cr.execute( ''' UPDATE recurring_contract_group SET recurring_value = {0}, advance_billing_months = {0} WHERE id = {1} '''.format(delay, contract_group[0]) )
import sys def migrate(cr, version): reload(sys) sys.setdefaultencoding('UTF8') if not version: return delay_dict = {'annual': 12, 'biannual': 6, 'fourmonthly': 4, 'quarterly': 3, 'bimonthly': 2, 'monthly': 1} cr.execute( ''' SELECT id, advance_billing FROM recurring_contract_group ''' ) contract_groups = cr.fetchall() for contract_group in contract_groups: delay = delay_dict[contract_group[1]] or 1 cr.execute( ''' UPDATE recurring_contract_group SET advance_billing_months = {0} WHERE id = {1} '''.format(delay, contract_group[0]) )
Remove wrong migration of contracts.
Remove wrong migration of contracts.
Python
agpl-3.0
CompassionCH/compassion-accounting,ndtran/compassion-accounting,ndtran/compassion-accounting,ecino/compassion-accounting,ecino/compassion-accounting,CompassionCH/compassion-accounting,ndtran/compassion-accounting
import sys def migrate(cr, version): reload(sys) sys.setdefaultencoding('UTF8') if not version: return delay_dict = {'annual': 12, 'biannual': 6, 'fourmonthly': 4, 'quarterly': 3, 'bimonthly': 2, 'monthly': 1} cr.execute( ''' SELECT id, advance_billing FROM recurring_contract_group ''' ) contract_groups = cr.fetchall() for contract_group in contract_groups: delay = delay_dict[contract_group[1]] or 1 cr.execute( ''' UPDATE recurring_contract_group - SET recurring_value = {0}, advance_billing_months = {0} + SET advance_billing_months = {0} WHERE id = {1} '''.format(delay, contract_group[0]) )
Remove wrong migration of contracts.
## Code Before: import sys def migrate(cr, version): reload(sys) sys.setdefaultencoding('UTF8') if not version: return delay_dict = {'annual': 12, 'biannual': 6, 'fourmonthly': 4, 'quarterly': 3, 'bimonthly': 2, 'monthly': 1} cr.execute( ''' SELECT id, advance_billing FROM recurring_contract_group ''' ) contract_groups = cr.fetchall() for contract_group in contract_groups: delay = delay_dict[contract_group[1]] or 1 cr.execute( ''' UPDATE recurring_contract_group SET recurring_value = {0}, advance_billing_months = {0} WHERE id = {1} '''.format(delay, contract_group[0]) ) ## Instruction: Remove wrong migration of contracts. ## Code After: import sys def migrate(cr, version): reload(sys) sys.setdefaultencoding('UTF8') if not version: return delay_dict = {'annual': 12, 'biannual': 6, 'fourmonthly': 4, 'quarterly': 3, 'bimonthly': 2, 'monthly': 1} cr.execute( ''' SELECT id, advance_billing FROM recurring_contract_group ''' ) contract_groups = cr.fetchall() for contract_group in contract_groups: delay = delay_dict[contract_group[1]] or 1 cr.execute( ''' UPDATE recurring_contract_group SET advance_billing_months = {0} WHERE id = {1} '''.format(delay, contract_group[0]) )
... UPDATE recurring_contract_group SET advance_billing_months = {0} WHERE id = {1} ...
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 = csv.reader(open('balanced/refund/refunds.completed.csv')) note = 'refund of advance payment; see https://medium.com/gratipay-blog/charging-in-arrears-18cacf779bee' for ts, id, amount, username, route_id, status_code, content in inp: if status_code != '201': continue amount = '-' + amount[:-2] + '.' + amount[-2:] print('posting {} back for {}'.format(amount, username)) route = ExchangeRoute.from_id(route_id) rp = route.participant participant = Participant.from_id(rp) if type(rp) is long else rp # Such a hack. :( route.set_attributes(participant=participant) record_exchange(db, route, amount, 0, participant, 'pending', note)
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 db = wireup.db(wireup.env()) inp = csv.reader(open('refunds.completed.csv')) note = 'refund of advance payment; see https://medium.com/gratipay-blog/18cacf779bee' total = N = 0 for ts, id, amount, username, route_id, success, ref in inp: print('posting {} back for {}'.format(amount, username)) assert success == 'True' total += D(amount) N += 1 amount = D('-' + amount) route = ExchangeRoute.from_id(route_id) # Such a hack. :( rp = route.participant participant = Participant.from_id(rp) if type(rp) is long else rp route.set_attributes(participant=participant) exchange_id = record_exchange(db, route, amount, 0, participant, 'pending', note) db.run("update exchanges set ref=%s where id=%s", (ref, exchange_id)) print('posted {} back for {}'.format(total, N))
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 record_exchange db = wireup.db(wireup.env()) - inp = csv.reader(open('balanced/refund/refunds.completed.csv')) + inp = csv.reader(open('refunds.completed.csv')) - note = 'refund of advance payment; see https://medium.com/gratipay-blog/charging-in-arrears-18cacf779bee' + note = 'refund of advance payment; see https://medium.com/gratipay-blog/18cacf779bee' + total = N = 0 - for ts, id, amount, username, route_id, status_code, content in inp: + for ts, id, amount, username, route_id, success, ref in inp: - if status_code != '201': continue - amount = '-' + amount[:-2] + '.' + amount[-2:] print('posting {} back for {}'.format(amount, username)) + assert success == 'True' + total += D(amount) + N += 1 + + amount = D('-' + amount) route = ExchangeRoute.from_id(route_id) + + # Such a hack. :( rp = route.participant - participant = Participant.from_id(rp) if type(rp) is long else rp # Such a hack. :( + participant = Participant.from_id(rp) if type(rp) is long else rp route.set_attributes(participant=participant) - record_exchange(db, route, amount, 0, participant, 'pending', note) + exchange_id = record_exchange(db, route, amount, 0, participant, 'pending', note) + db.run("update exchanges set ref=%s where id=%s", (ref, exchange_id)) + + print('posted {} back for {}'.format(total, N)) +
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(wireup.env()) inp = csv.reader(open('balanced/refund/refunds.completed.csv')) note = 'refund of advance payment; see https://medium.com/gratipay-blog/charging-in-arrears-18cacf779bee' for ts, id, amount, username, route_id, status_code, content in inp: if status_code != '201': continue amount = '-' + amount[:-2] + '.' + amount[-2:] print('posting {} back for {}'.format(amount, username)) route = ExchangeRoute.from_id(route_id) rp = route.participant participant = Participant.from_id(rp) if type(rp) is long else rp # Such a hack. :( route.set_attributes(participant=participant) record_exchange(db, route, amount, 0, participant, 'pending', note) ## Instruction: Update post-back script for Braintree ## Code After: 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 db = wireup.db(wireup.env()) inp = csv.reader(open('refunds.completed.csv')) note = 'refund of advance payment; see https://medium.com/gratipay-blog/18cacf779bee' total = N = 0 for ts, id, amount, username, route_id, success, ref in inp: print('posting {} back for {}'.format(amount, username)) assert success == 'True' total += D(amount) N += 1 amount = D('-' + amount) route = ExchangeRoute.from_id(route_id) # Such a hack. :( rp = route.participant participant = Participant.from_id(rp) if type(rp) is long else rp route.set_attributes(participant=participant) exchange_id = record_exchange(db, route, amount, 0, participant, 'pending', note) db.run("update exchanges set ref=%s where id=%s", (ref, exchange_id)) print('posted {} back for {}'.format(total, N))
# ... existing code ... import csv from decimal import Decimal as D from gratipay import wireup # ... modified code ... db = wireup.db(wireup.env()) inp = csv.reader(open('refunds.completed.csv')) note = 'refund of advance payment; see https://medium.com/gratipay-blog/18cacf779bee' total = N = 0 for ts, id, amount, username, route_id, success, ref in inp: print('posting {} back for {}'.format(amount, username)) assert success == 'True' total += D(amount) N += 1 amount = D('-' + amount) route = ExchangeRoute.from_id(route_id) # Such a hack. :( rp = route.participant participant = Participant.from_id(rp) if type(rp) is long else rp route.set_attributes(participant=participant) exchange_id = record_exchange(db, route, amount, 0, participant, 'pending', note) db.run("update exchanges set ref=%s where id=%s", (ref, exchange_id)) print('posted {} back for {}'.format(total, N)) # ... rest of the code ...
c90d7ae2a407f626342786101eed4159dfbfe730
infra/bots/assets/go_deps/create.py
infra/bots/assets/go_deps/create.py
"""Create the asset.""" import argparse import os import subprocess def create_asset(target_dir): """Create the asset.""" env = {} env.update(os.environ) env['GOPATH'] = target_dir subprocess.check_call( ['go', 'get', '-u', '-t', 'go.skia.org/infra/...'], env=env) def main(): parser = argparse.ArgumentParser() parser.add_argument('--target_dir', '-t', required=True) args = parser.parse_args() create_asset(args.target_dir) if __name__ == '__main__': main()
"""Create the asset.""" import argparse import os import subprocess def create_asset(target_dir): """Create the asset.""" env = {} env.update(os.environ) env['GOPATH'] = target_dir subprocess.check_call( ['go', 'get', '-u', '-t', 'go.skia.org/infra/...'], env=env) # There's a broken symlink which causes a lot of problems. Create the dir it # points to. missing_dir = os.path.join(target_dir, 'src', 'go.chromium.org', 'luci', 'web', 'inc', 'bower_components') os.mkdir(missing_dir) def main(): parser = argparse.ArgumentParser() parser.add_argument('--target_dir', '-t', required=True) args = parser.parse_args() create_asset(args.target_dir) if __name__ == '__main__': main()
Add missing symlink target in go_deps asset
[infra] Add missing symlink target in go_deps asset Bug: skia: Change-Id: Ic806bddcdc1130e9b96158c19dbff9e16900020c Reviewed-on: https://skia-review.googlesource.com/157565 Reviewed-by: Ravi Mistry <[email protected]> Commit-Queue: Eric Boren <[email protected]>
Python
bsd-3-clause
HalCanary/skia-hc,aosp-mirror/platform_external_skia,rubenvb/skia,HalCanary/skia-hc,google/skia,rubenvb/skia,aosp-mirror/platform_external_skia,Hikari-no-Tenshi/android_external_skia,rubenvb/skia,google/skia,rubenvb/skia,HalCanary/skia-hc,aosp-mirror/platform_external_skia,google/skia,HalCanary/skia-hc,google/skia,aosp-mirror/platform_external_skia,rubenvb/skia,rubenvb/skia,HalCanary/skia-hc,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia,google/skia,google/skia,google/skia,Hikari-no-Tenshi/android_external_skia,aosp-mirror/platform_external_skia,google/skia,google/skia,rubenvb/skia,HalCanary/skia-hc,Hikari-no-Tenshi/android_external_skia,Hikari-no-Tenshi/android_external_skia,Hikari-no-Tenshi/android_external_skia,HalCanary/skia-hc,HalCanary/skia-hc,rubenvb/skia,HalCanary/skia-hc,Hikari-no-Tenshi/android_external_skia,google/skia,HalCanary/skia-hc,Hikari-no-Tenshi/android_external_skia,rubenvb/skia,aosp-mirror/platform_external_skia,rubenvb/skia,aosp-mirror/platform_external_skia,Hikari-no-Tenshi/android_external_skia
"""Create the asset.""" import argparse import os import subprocess def create_asset(target_dir): """Create the asset.""" env = {} env.update(os.environ) env['GOPATH'] = target_dir subprocess.check_call( ['go', 'get', '-u', '-t', 'go.skia.org/infra/...'], env=env) + # There's a broken symlink which causes a lot of problems. Create the dir it + # points to. + missing_dir = os.path.join(target_dir, 'src', 'go.chromium.org', 'luci', + 'web', 'inc', 'bower_components') + os.mkdir(missing_dir) def main(): parser = argparse.ArgumentParser() parser.add_argument('--target_dir', '-t', required=True) args = parser.parse_args() create_asset(args.target_dir) if __name__ == '__main__': main()
Add missing symlink target in go_deps asset
## Code Before: """Create the asset.""" import argparse import os import subprocess def create_asset(target_dir): """Create the asset.""" env = {} env.update(os.environ) env['GOPATH'] = target_dir subprocess.check_call( ['go', 'get', '-u', '-t', 'go.skia.org/infra/...'], env=env) def main(): parser = argparse.ArgumentParser() parser.add_argument('--target_dir', '-t', required=True) args = parser.parse_args() create_asset(args.target_dir) if __name__ == '__main__': main() ## Instruction: Add missing symlink target in go_deps asset ## Code After: """Create the asset.""" import argparse import os import subprocess def create_asset(target_dir): """Create the asset.""" env = {} env.update(os.environ) env['GOPATH'] = target_dir subprocess.check_call( ['go', 'get', '-u', '-t', 'go.skia.org/infra/...'], env=env) # There's a broken symlink which causes a lot of problems. Create the dir it # points to. missing_dir = os.path.join(target_dir, 'src', 'go.chromium.org', 'luci', 'web', 'inc', 'bower_components') os.mkdir(missing_dir) def main(): parser = argparse.ArgumentParser() parser.add_argument('--target_dir', '-t', required=True) args = parser.parse_args() create_asset(args.target_dir) if __name__ == '__main__': main()
# ... existing code ... env=env) # There's a broken symlink which causes a lot of problems. Create the dir it # points to. missing_dir = os.path.join(target_dir, 'src', 'go.chromium.org', 'luci', 'web', 'inc', 'bower_components') os.mkdir(missing_dir) # ... rest of the code ...
ceebd0b345fe7221577bfcfe18632267897871e8
test/helpers/xnat_test_helper.py
test/helpers/xnat_test_helper.py
import os, re from base64 import b64encode as encode from qipipe.staging import airc_collection as airc from qipipe.staging.staging_helper import SUBJECT_FMT from qipipe.helpers import xnat_helper import logging logger = logging.getLogger(__name__) def generate_subject_name(name): """ Makes a subject name that is unique to the given test name. @param name: the test name @return: the test subject name """ return 'Test_' + encode(name).strip('=') def get_subjects(collection, source, pattern=None): """ Infers the XNAT subject names from the given source directory. The source directory contains subject subdirectories. The match pattern matches on the subdirectories and captures the subject number. The subject name is the collection name followed by the subject number, e.g. C{Breast004}. @param collection: the AIRC collection name @param source: the input parent directory @param pattern: the subject directory name match pattern (default L{airc.AIRCCollection.subject_pattern}) @return: the subject name => directory dictionary """ airc_coll = airc.collection_with_name(collection) pat = pattern or airc_coll.subject_pattern sbj_dir_dict = {} with xnat_helper.connection() as xnat: for d in os.listdir(source): match = re.match(pat, d) if match: # The XNAT subject name. subject = SUBJECT_FMT % (collection, int(match.group(1))) # The subject source directory. sbj_dir_dict[subject] = os.path.join(source, d) logger.debug("Discovered XNAT test subject %s subdirectory: %s" % (subject, d)) return sbj_dir_dict def delete_subjects(*subject_names): """ Deletes the given XNAT subjects, if they exist. @param subject_names: the XNAT subject names """ with xnat_helper.connection() as xnat: for sbj_lbl in subject_names: sbj = xnat.get_subject('QIN', sbj_lbl) if sbj.exists(): sbj.delete() logger.debug("Deleted the XNAT test subject %s." % sbj_lbl)
import os, re from base64 import b64encode as encode from qipipe.staging import airc_collection as airc from qipipe.staging.staging_helper import SUBJECT_FMT from qipipe.helpers import xnat_helper import logging logger = logging.getLogger(__name__) def generate_subject_name(name): """ Makes a subject name that is unique to the given test name. @param name: the test name @return: the test subject name """ return 'Test_' + encode(name).strip('=')
Move get_subjects and delete_subjects to qipipe helpers.
Move get_subjects and delete_subjects to qipipe helpers.
Python
bsd-2-clause
ohsu-qin/qipipe
import os, re from base64 import b64encode as encode from qipipe.staging import airc_collection as airc from qipipe.staging.staging_helper import SUBJECT_FMT from qipipe.helpers import xnat_helper import logging logger = logging.getLogger(__name__) def generate_subject_name(name): """ Makes a subject name that is unique to the given test name. @param name: the test name @return: the test subject name """ return 'Test_' + encode(name).strip('=') - def get_subjects(collection, source, pattern=None): - """ - Infers the XNAT subject names from the given source directory. - The source directory contains subject subdirectories. - The match pattern matches on the subdirectories and captures the - subject number. The subject name is the collection name followed - by the subject number, e.g. C{Breast004}. - - @param collection: the AIRC collection name - @param source: the input parent directory - @param pattern: the subject directory name match pattern - (default L{airc.AIRCCollection.subject_pattern}) - @return: the subject name => directory dictionary - """ - airc_coll = airc.collection_with_name(collection) - pat = pattern or airc_coll.subject_pattern - sbj_dir_dict = {} - with xnat_helper.connection() as xnat: - for d in os.listdir(source): - match = re.match(pat, d) - if match: - # The XNAT subject name. - subject = SUBJECT_FMT % (collection, int(match.group(1))) - # The subject source directory. - sbj_dir_dict[subject] = os.path.join(source, d) - logger.debug("Discovered XNAT test subject %s subdirectory: %s" % (subject, d)) - - return sbj_dir_dict - - def delete_subjects(*subject_names): - """ - Deletes the given XNAT subjects, if they exist. - - @param subject_names: the XNAT subject names - """ - with xnat_helper.connection() as xnat: - for sbj_lbl in subject_names: - sbj = xnat.get_subject('QIN', sbj_lbl) - if sbj.exists(): - sbj.delete() - logger.debug("Deleted the XNAT test subject %s." % sbj_lbl) -
Move get_subjects and delete_subjects to qipipe helpers.
## Code Before: import os, re from base64 import b64encode as encode from qipipe.staging import airc_collection as airc from qipipe.staging.staging_helper import SUBJECT_FMT from qipipe.helpers import xnat_helper import logging logger = logging.getLogger(__name__) def generate_subject_name(name): """ Makes a subject name that is unique to the given test name. @param name: the test name @return: the test subject name """ return 'Test_' + encode(name).strip('=') def get_subjects(collection, source, pattern=None): """ Infers the XNAT subject names from the given source directory. The source directory contains subject subdirectories. The match pattern matches on the subdirectories and captures the subject number. The subject name is the collection name followed by the subject number, e.g. C{Breast004}. @param collection: the AIRC collection name @param source: the input parent directory @param pattern: the subject directory name match pattern (default L{airc.AIRCCollection.subject_pattern}) @return: the subject name => directory dictionary """ airc_coll = airc.collection_with_name(collection) pat = pattern or airc_coll.subject_pattern sbj_dir_dict = {} with xnat_helper.connection() as xnat: for d in os.listdir(source): match = re.match(pat, d) if match: # The XNAT subject name. subject = SUBJECT_FMT % (collection, int(match.group(1))) # The subject source directory. sbj_dir_dict[subject] = os.path.join(source, d) logger.debug("Discovered XNAT test subject %s subdirectory: %s" % (subject, d)) return sbj_dir_dict def delete_subjects(*subject_names): """ Deletes the given XNAT subjects, if they exist. @param subject_names: the XNAT subject names """ with xnat_helper.connection() as xnat: for sbj_lbl in subject_names: sbj = xnat.get_subject('QIN', sbj_lbl) if sbj.exists(): sbj.delete() logger.debug("Deleted the XNAT test subject %s." % sbj_lbl) ## Instruction: Move get_subjects and delete_subjects to qipipe helpers. ## Code After: import os, re from base64 import b64encode as encode from qipipe.staging import airc_collection as airc from qipipe.staging.staging_helper import SUBJECT_FMT from qipipe.helpers import xnat_helper import logging logger = logging.getLogger(__name__) def generate_subject_name(name): """ Makes a subject name that is unique to the given test name. @param name: the test name @return: the test subject name """ return 'Test_' + encode(name).strip('=')
# ... existing code ... return 'Test_' + encode(name).strip('=') # ... rest of the code ...
0925c1f2ab3332ddfaeefed81f379dc72dd41644
openid/test/test_urinorm.py
openid/test/test_urinorm.py
import os import unittest import openid.urinorm class UrinormTest(unittest.TestCase): def __init__(self, desc, case, expected): unittest.TestCase.__init__(self) self.desc = desc self.case = case self.expected = expected def shortDescription(self): return self.desc def runTest(self): try: actual = openid.urinorm.urinorm(self.case) except ValueError as why: self.assertEqual(self.expected, 'fail', why) else: self.assertEqual(actual, self.expected) def parse(cls, full_case): desc, case, expected = full_case.split('\n') case = str(case, 'utf-8') return cls(desc, case, expected) parse = classmethod(parse) def parseTests(test_data): result = [] cases = test_data.split('\n\n') for case in cases: case = case.strip() if case: result.append(UrinormTest.parse(case)) return result def pyUnitTests(): here = os.path.dirname(os.path.abspath(__file__)) test_data_file_name = os.path.join(here, 'urinorm.txt') test_data_file = open(test_data_file_name) test_data = test_data_file.read() test_data_file.close() tests = parseTests(test_data) return unittest.TestSuite(tests)
import os import unittest import openid.urinorm class UrinormTest(unittest.TestCase): def __init__(self, desc, case, expected): unittest.TestCase.__init__(self) self.desc = desc self.case = case self.expected = expected def shortDescription(self): return self.desc def runTest(self): try: actual = openid.urinorm.urinorm(self.case) except ValueError as why: self.assertEqual(self.expected, 'fail', why) else: self.assertEqual(actual, self.expected) def parse(cls, full_case): desc, case, expected = full_case.split('\n') case = str(case, 'utf-8') if isinstance(case, bytes) else case return cls(desc, case, expected) parse = classmethod(parse) def parseTests(test_data): result = [] cases = test_data.split('\n\n') for case in cases: case = case.strip() if case: result.append(UrinormTest.parse(case)) return result def pyUnitTests(): here = os.path.dirname(os.path.abspath(__file__)) test_data_file_name = os.path.join(here, 'urinorm.txt') test_data_file = open(test_data_file_name) test_data = test_data_file.read() test_data_file.close() tests = parseTests(test_data) return unittest.TestSuite(tests) if __name__ == '__main__': runner = unittest.TextTestRunner() runner.run(pyUnitTests())
Make urinorm tests runnable on their own
Make urinorm tests runnable on their own
Python
apache-2.0
misli/python3-openid,misli/python3-openid,moreati/python3-openid,misli/python3-openid,necaris/python3-openid,isagalaev/sm-openid,moreati/python3-openid,moreati/python3-openid,necaris/python3-openid
import os import unittest import openid.urinorm class UrinormTest(unittest.TestCase): def __init__(self, desc, case, expected): unittest.TestCase.__init__(self) self.desc = desc self.case = case self.expected = expected def shortDescription(self): return self.desc def runTest(self): try: actual = openid.urinorm.urinorm(self.case) except ValueError as why: self.assertEqual(self.expected, 'fail', why) else: self.assertEqual(actual, self.expected) def parse(cls, full_case): desc, case, expected = full_case.split('\n') - case = str(case, 'utf-8') + case = str(case, 'utf-8') if isinstance(case, bytes) else case return cls(desc, case, expected) parse = classmethod(parse) def parseTests(test_data): result = [] cases = test_data.split('\n\n') for case in cases: case = case.strip() if case: result.append(UrinormTest.parse(case)) return result + def pyUnitTests(): here = os.path.dirname(os.path.abspath(__file__)) test_data_file_name = os.path.join(here, 'urinorm.txt') test_data_file = open(test_data_file_name) test_data = test_data_file.read() test_data_file.close() tests = parseTests(test_data) return unittest.TestSuite(tests) + if __name__ == '__main__': + runner = unittest.TextTestRunner() + runner.run(pyUnitTests()) +
Make urinorm tests runnable on their own
## Code Before: import os import unittest import openid.urinorm class UrinormTest(unittest.TestCase): def __init__(self, desc, case, expected): unittest.TestCase.__init__(self) self.desc = desc self.case = case self.expected = expected def shortDescription(self): return self.desc def runTest(self): try: actual = openid.urinorm.urinorm(self.case) except ValueError as why: self.assertEqual(self.expected, 'fail', why) else: self.assertEqual(actual, self.expected) def parse(cls, full_case): desc, case, expected = full_case.split('\n') case = str(case, 'utf-8') return cls(desc, case, expected) parse = classmethod(parse) def parseTests(test_data): result = [] cases = test_data.split('\n\n') for case in cases: case = case.strip() if case: result.append(UrinormTest.parse(case)) return result def pyUnitTests(): here = os.path.dirname(os.path.abspath(__file__)) test_data_file_name = os.path.join(here, 'urinorm.txt') test_data_file = open(test_data_file_name) test_data = test_data_file.read() test_data_file.close() tests = parseTests(test_data) return unittest.TestSuite(tests) ## Instruction: Make urinorm tests runnable on their own ## Code After: import os import unittest import openid.urinorm class UrinormTest(unittest.TestCase): def __init__(self, desc, case, expected): unittest.TestCase.__init__(self) self.desc = desc self.case = case self.expected = expected def shortDescription(self): return self.desc def runTest(self): try: actual = openid.urinorm.urinorm(self.case) except ValueError as why: self.assertEqual(self.expected, 'fail', why) else: self.assertEqual(actual, self.expected) def parse(cls, full_case): desc, case, expected = full_case.split('\n') case = str(case, 'utf-8') if isinstance(case, bytes) else case return cls(desc, case, expected) parse = classmethod(parse) def parseTests(test_data): result = [] cases = test_data.split('\n\n') for case in cases: case = case.strip() if case: result.append(UrinormTest.parse(case)) return result def pyUnitTests(): here = os.path.dirname(os.path.abspath(__file__)) test_data_file_name = os.path.join(here, 'urinorm.txt') test_data_file = open(test_data_file_name) test_data = test_data_file.read() test_data_file.close() tests = parseTests(test_data) return unittest.TestSuite(tests) if __name__ == '__main__': runner = unittest.TextTestRunner() runner.run(pyUnitTests())
// ... existing code ... desc, case, expected = full_case.split('\n') case = str(case, 'utf-8') if isinstance(case, bytes) else case // ... modified code ... def pyUnitTests(): ... return unittest.TestSuite(tests) if __name__ == '__main__': runner = unittest.TextTestRunner() runner.run(pyUnitTests()) // ... rest of the code ...
77d72fe0502c64294dbacdbf8defbb44ee21c088
schools/admin.py
schools/admin.py
from django.contrib import admin from .models import * class SchoolBuildingPhotoInline(admin.TabularInline): model = SchoolBuildingPhoto @admin.register(SchoolBuilding) class SchoolBuildingAdmin(admin.ModelAdmin): fields = ('school', 'building', 'begin_year', 'end_year') readonly_fields = fields list_display = ('__str__', 'has_photo') list_filter = ('photos',) inlines = [SchoolBuildingPhotoInline]
from django.contrib import admin from .models import * class SchoolBuildingPhotoInline(admin.TabularInline): model = SchoolBuildingPhoto @admin.register(SchoolBuilding) class SchoolBuildingAdmin(admin.ModelAdmin): fields = ('school', 'building', 'begin_year', 'end_year') readonly_fields = fields search_fields = ['school__names__types__value'] list_display = ('__str__', 'has_photo') list_filter = ('photos',) inlines = [SchoolBuildingPhotoInline]
Add search based on school name
Add search based on school name
Python
agpl-3.0
City-of-Helsinki/kore,City-of-Helsinki/kore,Rikuoja/kore,Rikuoja/kore
from django.contrib import admin from .models import * class SchoolBuildingPhotoInline(admin.TabularInline): model = SchoolBuildingPhoto @admin.register(SchoolBuilding) class SchoolBuildingAdmin(admin.ModelAdmin): fields = ('school', 'building', 'begin_year', 'end_year') readonly_fields = fields + search_fields = ['school__names__types__value'] list_display = ('__str__', 'has_photo') list_filter = ('photos',) inlines = [SchoolBuildingPhotoInline]
Add search based on school name
## Code Before: from django.contrib import admin from .models import * class SchoolBuildingPhotoInline(admin.TabularInline): model = SchoolBuildingPhoto @admin.register(SchoolBuilding) class SchoolBuildingAdmin(admin.ModelAdmin): fields = ('school', 'building', 'begin_year', 'end_year') readonly_fields = fields list_display = ('__str__', 'has_photo') list_filter = ('photos',) inlines = [SchoolBuildingPhotoInline] ## Instruction: Add search based on school name ## Code After: from django.contrib import admin from .models import * class SchoolBuildingPhotoInline(admin.TabularInline): model = SchoolBuildingPhoto @admin.register(SchoolBuilding) class SchoolBuildingAdmin(admin.ModelAdmin): fields = ('school', 'building', 'begin_year', 'end_year') readonly_fields = fields search_fields = ['school__names__types__value'] list_display = ('__str__', 'has_photo') list_filter = ('photos',) inlines = [SchoolBuildingPhotoInline]
// ... existing code ... readonly_fields = fields search_fields = ['school__names__types__value'] list_display = ('__str__', 'has_photo') // ... rest of the code ...
01aa219b0058cbfbdb96e890f510fa275f3ef790
python/Completion.py
python/Completion.py
import vim, syncrequest, types class Completion: def get_completions(self, column, partialWord): parameters = {} parameters['column'] = vim.eval(column) parameters['wordToComplete'] = vim.eval(partialWord) parameters['WantDocumentationForEveryCompletionResult'] = \ bool(int(vim.eval('g:omnicomplete_fetch_full_documentation'))) want_snippet = \ bool(int(vim.eval('g:OmniSharp_want_snippet'))) parameters['WantSnippet'] = want_snippet parameters['WantMethodHeader'] = want_snippet parameters['WantReturnType'] = want_snippet parameters['buffer'] = '\r\n'.join(vim.eval('s:textBuffer')[:]) response = syncrequest.get_response('/autocomplete', parameters) enc = vim.eval('&encoding') vim_completions = [] if response is not None: for completion in response: complete = { 'snip': completion['Snippet'] if completion['Snippet'] is not None else '', 'word': completion['MethodHeader'] if completion['MethodHeader'] is not None else completion['CompletionText'], 'menu': completion['ReturnType'] if completion['ReturnType'] is not None else completion['DisplayText'], 'info': completion['Description'].replace('\r\n', '\n') if completion['Description'] is not None else '', 'icase': 1, 'dup':1 } vim_completions.append(complete) return vim_completions
import vim, syncrequest, types class Completion: def get_completions(self, column, partialWord): parameters = {} parameters['column'] = vim.eval(column) parameters['wordToComplete'] = vim.eval(partialWord) parameters['WantDocumentationForEveryCompletionResult'] = \ bool(int(vim.eval('g:omnicomplete_fetch_full_documentation'))) want_snippet = \ bool(int(vim.eval('g:OmniSharp_want_snippet'))) parameters['WantSnippet'] = want_snippet parameters['WantMethodHeader'] = want_snippet parameters['WantReturnType'] = want_snippet parameters['buffer'] = '\r\n'.join(vim.eval('s:textBuffer')[:]) response = syncrequest.get_response('/autocomplete', parameters) enc = vim.eval('&encoding') vim_completions = [] if response is not None: for completion in response: complete = { 'snip': completion['Snippet'] or '', 'word': completion['MethodHeader'] or completion['CompletionText'], 'menu': completion['ReturnType'] or completion['DisplayText'], 'info': completion['Description'].replace('\r\n', '\n') or '', 'icase': 1, 'dup':1 } vim_completions.append(complete) return vim_completions
Use or operator in python to tidy up completion building.
Use or operator in python to tidy up completion building.
Python
mit
OmniSharp/omnisharp-vim,OmniSharp/omnisharp-vim,OmniSharp/omnisharp-vim
import vim, syncrequest, types class Completion: def get_completions(self, column, partialWord): parameters = {} parameters['column'] = vim.eval(column) parameters['wordToComplete'] = vim.eval(partialWord) parameters['WantDocumentationForEveryCompletionResult'] = \ bool(int(vim.eval('g:omnicomplete_fetch_full_documentation'))) want_snippet = \ bool(int(vim.eval('g:OmniSharp_want_snippet'))) parameters['WantSnippet'] = want_snippet parameters['WantMethodHeader'] = want_snippet parameters['WantReturnType'] = want_snippet parameters['buffer'] = '\r\n'.join(vim.eval('s:textBuffer')[:]) response = syncrequest.get_response('/autocomplete', parameters) enc = vim.eval('&encoding') vim_completions = [] if response is not None: for completion in response: complete = { - 'snip': completion['Snippet'] if completion['Snippet'] is not None else '', + 'snip': completion['Snippet'] or '', - 'word': completion['MethodHeader'] if completion['MethodHeader'] is not None else completion['CompletionText'], + 'word': completion['MethodHeader'] or completion['CompletionText'], - 'menu': completion['ReturnType'] if completion['ReturnType'] is not None else completion['DisplayText'], + 'menu': completion['ReturnType'] or completion['DisplayText'], - 'info': completion['Description'].replace('\r\n', '\n') if completion['Description'] is not None else '', + 'info': completion['Description'].replace('\r\n', '\n') or '', 'icase': 1, 'dup':1 } vim_completions.append(complete) return vim_completions
Use or operator in python to tidy up completion building.
## Code Before: import vim, syncrequest, types class Completion: def get_completions(self, column, partialWord): parameters = {} parameters['column'] = vim.eval(column) parameters['wordToComplete'] = vim.eval(partialWord) parameters['WantDocumentationForEveryCompletionResult'] = \ bool(int(vim.eval('g:omnicomplete_fetch_full_documentation'))) want_snippet = \ bool(int(vim.eval('g:OmniSharp_want_snippet'))) parameters['WantSnippet'] = want_snippet parameters['WantMethodHeader'] = want_snippet parameters['WantReturnType'] = want_snippet parameters['buffer'] = '\r\n'.join(vim.eval('s:textBuffer')[:]) response = syncrequest.get_response('/autocomplete', parameters) enc = vim.eval('&encoding') vim_completions = [] if response is not None: for completion in response: complete = { 'snip': completion['Snippet'] if completion['Snippet'] is not None else '', 'word': completion['MethodHeader'] if completion['MethodHeader'] is not None else completion['CompletionText'], 'menu': completion['ReturnType'] if completion['ReturnType'] is not None else completion['DisplayText'], 'info': completion['Description'].replace('\r\n', '\n') if completion['Description'] is not None else '', 'icase': 1, 'dup':1 } vim_completions.append(complete) return vim_completions ## Instruction: Use or operator in python to tidy up completion building. ## Code After: import vim, syncrequest, types class Completion: def get_completions(self, column, partialWord): parameters = {} parameters['column'] = vim.eval(column) parameters['wordToComplete'] = vim.eval(partialWord) parameters['WantDocumentationForEveryCompletionResult'] = \ bool(int(vim.eval('g:omnicomplete_fetch_full_documentation'))) want_snippet = \ bool(int(vim.eval('g:OmniSharp_want_snippet'))) parameters['WantSnippet'] = want_snippet parameters['WantMethodHeader'] = want_snippet parameters['WantReturnType'] = want_snippet parameters['buffer'] = '\r\n'.join(vim.eval('s:textBuffer')[:]) response = syncrequest.get_response('/autocomplete', parameters) enc = vim.eval('&encoding') vim_completions = [] if response is not None: for completion in response: complete = { 'snip': completion['Snippet'] or '', 'word': completion['MethodHeader'] or completion['CompletionText'], 'menu': completion['ReturnType'] or completion['DisplayText'], 'info': completion['Description'].replace('\r\n', '\n') or '', 'icase': 1, 'dup':1 } vim_completions.append(complete) return vim_completions
... complete = { 'snip': completion['Snippet'] or '', 'word': completion['MethodHeader'] or completion['CompletionText'], 'menu': completion['ReturnType'] or completion['DisplayText'], 'info': completion['Description'].replace('\r\n', '\n') or '', 'icase': 1, ...
c7daef487fee51b68d410d2f4be3fd16068c7d5a
tests/export/test_task_types_to_csv.py
tests/export/test_task_types_to_csv.py
from tests.base import ApiDBTestCase class TasksCsvExportTestCase(ApiDBTestCase): def setUp(self): super(TasksCsvExportTestCase, self).setUp() self.generate_fixture_project_status() self.generate_fixture_project() self.generate_fixture_asset_type() self.generate_fixture_department() self.generate_fixture_task_type() def test_get_output_files(self): csv_task_types = self.get_raw("export/csv/task-types.csv") expected_result = """Department;Name\r Animation;Animation\r Modeling;Shaders\r """ self.assertEqual(csv_task_types, expected_result)
from tests.base import ApiDBTestCase class TasksCsvExportTestCase(ApiDBTestCase): def setUp(self): super(TasksCsvExportTestCase, self).setUp() self.generate_fixture_project_status() self.generate_fixture_project() self.generate_fixture_asset_type() self.generate_fixture_department() self.generate_fixture_task_type() def test_get_output_files(self): csv_task_types = self.get_raw("export/csv/task-types.csv") expected_result = """Department;Name\r Animation;Animation\r Animation;Layout\r Modeling;Shaders\r """ self.assertEqual(csv_task_types, expected_result)
Fix task type export test
Fix task type export test
Python
agpl-3.0
cgwire/zou
from tests.base import ApiDBTestCase class TasksCsvExportTestCase(ApiDBTestCase): def setUp(self): super(TasksCsvExportTestCase, self).setUp() self.generate_fixture_project_status() self.generate_fixture_project() self.generate_fixture_asset_type() self.generate_fixture_department() self.generate_fixture_task_type() def test_get_output_files(self): csv_task_types = self.get_raw("export/csv/task-types.csv") expected_result = """Department;Name\r Animation;Animation\r + Animation;Layout\r Modeling;Shaders\r """ self.assertEqual(csv_task_types, expected_result)
Fix task type export test
## Code Before: from tests.base import ApiDBTestCase class TasksCsvExportTestCase(ApiDBTestCase): def setUp(self): super(TasksCsvExportTestCase, self).setUp() self.generate_fixture_project_status() self.generate_fixture_project() self.generate_fixture_asset_type() self.generate_fixture_department() self.generate_fixture_task_type() def test_get_output_files(self): csv_task_types = self.get_raw("export/csv/task-types.csv") expected_result = """Department;Name\r Animation;Animation\r Modeling;Shaders\r """ self.assertEqual(csv_task_types, expected_result) ## Instruction: Fix task type export test ## Code After: from tests.base import ApiDBTestCase class TasksCsvExportTestCase(ApiDBTestCase): def setUp(self): super(TasksCsvExportTestCase, self).setUp() self.generate_fixture_project_status() self.generate_fixture_project() self.generate_fixture_asset_type() self.generate_fixture_department() self.generate_fixture_task_type() def test_get_output_files(self): csv_task_types = self.get_raw("export/csv/task-types.csv") expected_result = """Department;Name\r Animation;Animation\r Animation;Layout\r Modeling;Shaders\r """ self.assertEqual(csv_task_types, expected_result)
// ... existing code ... Animation;Animation\r Animation;Layout\r Modeling;Shaders\r // ... rest of the code ...
28f504dccd02046604761e997f929015a285dffd
pyQuantuccia/tests/test_get_holiday_date.py
pyQuantuccia/tests/test_get_holiday_date.py
from datetime import date import calendar print(calendar.__dir__()) print(calendar.__dict__) def test_united_kingdom_is_business_day(): """ Check a single day to see that we can identify holidays. """ assert(calendar.united_kingdom_is_business_day(date(2017, 4, 17)) is False)
from datetime import date import calendar def test_foo(): assert(calendar.__dir__() == "") def test_dummy(): assert(calendar.__dict__ == "") def test_united_kingdom_is_business_day(): """ Check a single day to see that we can identify holidays. """ assert(calendar.united_kingdom_is_business_day(date(2017, 4, 17)) is False)
Add some bogus tests to try and get this info.
Add some bogus tests to try and get this info.
Python
bsd-3-clause
jwg4/pyQuantuccia,jwg4/pyQuantuccia
from datetime import date import calendar - print(calendar.__dir__()) - print(calendar.__dict__) + + def test_foo(): + assert(calendar.__dir__() == "") + + + def test_dummy(): + assert(calendar.__dict__ == "") def test_united_kingdom_is_business_day(): """ Check a single day to see that we can identify holidays. """ assert(calendar.united_kingdom_is_business_day(date(2017, 4, 17)) is False)
Add some bogus tests to try and get this info.
## Code Before: from datetime import date import calendar print(calendar.__dir__()) print(calendar.__dict__) def test_united_kingdom_is_business_day(): """ Check a single day to see that we can identify holidays. """ assert(calendar.united_kingdom_is_business_day(date(2017, 4, 17)) is False) ## Instruction: Add some bogus tests to try and get this info. ## Code After: from datetime import date import calendar def test_foo(): assert(calendar.__dir__() == "") def test_dummy(): assert(calendar.__dict__ == "") def test_united_kingdom_is_business_day(): """ Check a single day to see that we can identify holidays. """ assert(calendar.united_kingdom_is_business_day(date(2017, 4, 17)) is False)
... def test_foo(): assert(calendar.__dir__() == "") def test_dummy(): assert(calendar.__dict__ == "") ...
f3508aa348aa6f560953cbf48c6671ccf8558410
tests/test_forms.py
tests/test_forms.py
from django.template.loader import get_template from django.test import SimpleTestCase from .utils import TemplateTestMixin class TestFieldTag(TemplateTestMixin, SimpleTestCase): TEMPLATES = { 'field': '{% load sniplates %}{% form_field form.field %}' } def test_field_tag(self): ''' Make sure the field tag is usable. ''' tmpl = get_template('field') output = tmpl.render(self.ctx)
from django import forms from django.template.loader import get_template from django.test import SimpleTestCase from .utils import TemplateTestMixin class TestForm(forms.Form): char = forms.CharField() class TestFieldTag(TemplateTestMixin, SimpleTestCase): TEMPLATES = { 'widgets': '''{% block CharField %}<input type="text" name="{{ name }}" value="{{ value|default:'' }}>{% endblock %}''', 'field': '{% load sniplates %}{% load_widgets form="widgets" %}{% form_field form.char %}' } def setUp(self): super(TestFieldTag, self).setUp() self.ctx['form'] = TestForm() def test_field_tag(self): ''' Make sure the field tag is usable. ''' tmpl = get_template('field') output = tmpl.render(self.ctx)
Make first field test work
Make first field test work
Python
mit
kezabelle/django-sniplates,funkybob/django-sniplates,funkybob/django-sniplates,sergei-maertens/django-sniplates,wengole/django-sniplates,sergei-maertens/django-sniplates,wengole/django-sniplates,kezabelle/django-sniplates,kezabelle/django-sniplates,sergei-maertens/django-sniplates
+ from django import forms from django.template.loader import get_template from django.test import SimpleTestCase from .utils import TemplateTestMixin + class TestForm(forms.Form): + char = forms.CharField() + + class TestFieldTag(TemplateTestMixin, SimpleTestCase): TEMPLATES = { - 'field': '{% load sniplates %}{% form_field form.field %}' + 'widgets': '''{% block CharField %}<input type="text" name="{{ name }}" value="{{ value|default:'' }}>{% endblock %}''', + 'field': '{% load sniplates %}{% load_widgets form="widgets" %}{% form_field form.char %}' } + def setUp(self): + super(TestFieldTag, self).setUp() + self.ctx['form'] = TestForm() def test_field_tag(self): ''' Make sure the field tag is usable. ''' tmpl = get_template('field') output = tmpl.render(self.ctx)
Make first field test work
## Code Before: from django.template.loader import get_template from django.test import SimpleTestCase from .utils import TemplateTestMixin class TestFieldTag(TemplateTestMixin, SimpleTestCase): TEMPLATES = { 'field': '{% load sniplates %}{% form_field form.field %}' } def test_field_tag(self): ''' Make sure the field tag is usable. ''' tmpl = get_template('field') output = tmpl.render(self.ctx) ## Instruction: Make first field test work ## Code After: from django import forms from django.template.loader import get_template from django.test import SimpleTestCase from .utils import TemplateTestMixin class TestForm(forms.Form): char = forms.CharField() class TestFieldTag(TemplateTestMixin, SimpleTestCase): TEMPLATES = { 'widgets': '''{% block CharField %}<input type="text" name="{{ name }}" value="{{ value|default:'' }}>{% endblock %}''', 'field': '{% load sniplates %}{% load_widgets form="widgets" %}{% form_field form.char %}' } def setUp(self): super(TestFieldTag, self).setUp() self.ctx['form'] = TestForm() def test_field_tag(self): ''' Make sure the field tag is usable. ''' tmpl = get_template('field') output = tmpl.render(self.ctx)
// ... existing code ... from django import forms from django.template.loader import get_template // ... modified code ... class TestForm(forms.Form): char = forms.CharField() class TestFieldTag(TemplateTestMixin, SimpleTestCase): ... TEMPLATES = { 'widgets': '''{% block CharField %}<input type="text" name="{{ name }}" value="{{ value|default:'' }}>{% endblock %}''', 'field': '{% load sniplates %}{% load_widgets form="widgets" %}{% form_field form.char %}' } def setUp(self): super(TestFieldTag, self).setUp() self.ctx['form'] = TestForm() // ... rest of the code ...
4299f4f410f768066aaacf885ff0a38e8af175c9
intro-django/readit/books/forms.py
intro-django/readit/books/forms.py
from django import forms from .models import Book class ReviewForm(forms.Form): """ Form for reviewing a book """ is_favourite = forms.BooleanField( label = 'Favourite?', help_text = 'In your top 100 books of all time?', required = False, ) review = forms.CharField( widget = forms.Textarea, min_length = 100, error_messages = { 'required': 'Please enter your review', 'min_length': 'Please write atleast 100 characters (You have written %(show_value)s', } ) class BookForm(forms.ModelForm) : class Meta: model = Book fields = ['title', 'authors']
from django import forms from .models import Book class ReviewForm(forms.Form): """ Form for reviewing a book """ is_favourite = forms.BooleanField( label = 'Favourite?', help_text = 'In your top 100 books of all time?', required = False, ) review = forms.CharField( widget = forms.Textarea, min_length = 100, error_messages = { 'required': 'Please enter your review', 'min_length': 'Please write atleast 100 characters (You have written %(show_value)s', } ) class BookForm(forms.ModelForm) : class Meta: model = Book fields = ['title', 'authors'] def clean(self): # Super the clean method to maintain main validation and error messages super(BookForm, self).clean() try: title = self.cleaned_data.get('title') authors = self.cleaned_data.get('authors') book = Book.objects.get(title=title, authors=authors) raise forms.ValidationError( 'The book {} by {} already exists.'.format(title, book.list_authors()), code = 'bookexists' ) except Book.DoesNotExist: return self.cleaned_data
Add custom form validation enforcing that each new book is unique
Add custom form validation enforcing that each new book is unique
Python
mit
nirajkvinit/python3-study,nirajkvinit/python3-study,nirajkvinit/python3-study,nirajkvinit/python3-study
from django import forms from .models import Book class ReviewForm(forms.Form): """ Form for reviewing a book """ is_favourite = forms.BooleanField( label = 'Favourite?', help_text = 'In your top 100 books of all time?', required = False, ) review = forms.CharField( widget = forms.Textarea, min_length = 100, error_messages = { 'required': 'Please enter your review', 'min_length': 'Please write atleast 100 characters (You have written %(show_value)s', } ) class BookForm(forms.ModelForm) : class Meta: model = Book fields = ['title', 'authors'] + + def clean(self): + # Super the clean method to maintain main validation and error messages + super(BookForm, self).clean() + + try: + title = self.cleaned_data.get('title') + authors = self.cleaned_data.get('authors') + book = Book.objects.get(title=title, authors=authors) + + raise forms.ValidationError( + 'The book {} by {} already exists.'.format(title, book.list_authors()), + code = 'bookexists' + ) + except Book.DoesNotExist: + return self.cleaned_data +
Add custom form validation enforcing that each new book is unique
## Code Before: from django import forms from .models import Book class ReviewForm(forms.Form): """ Form for reviewing a book """ is_favourite = forms.BooleanField( label = 'Favourite?', help_text = 'In your top 100 books of all time?', required = False, ) review = forms.CharField( widget = forms.Textarea, min_length = 100, error_messages = { 'required': 'Please enter your review', 'min_length': 'Please write atleast 100 characters (You have written %(show_value)s', } ) class BookForm(forms.ModelForm) : class Meta: model = Book fields = ['title', 'authors'] ## Instruction: Add custom form validation enforcing that each new book is unique ## Code After: from django import forms from .models import Book class ReviewForm(forms.Form): """ Form for reviewing a book """ is_favourite = forms.BooleanField( label = 'Favourite?', help_text = 'In your top 100 books of all time?', required = False, ) review = forms.CharField( widget = forms.Textarea, min_length = 100, error_messages = { 'required': 'Please enter your review', 'min_length': 'Please write atleast 100 characters (You have written %(show_value)s', } ) class BookForm(forms.ModelForm) : class Meta: model = Book fields = ['title', 'authors'] def clean(self): # Super the clean method to maintain main validation and error messages super(BookForm, self).clean() try: title = self.cleaned_data.get('title') authors = self.cleaned_data.get('authors') book = Book.objects.get(title=title, authors=authors) raise forms.ValidationError( 'The book {} by {} already exists.'.format(title, book.list_authors()), code = 'bookexists' ) except Book.DoesNotExist: return self.cleaned_data
... fields = ['title', 'authors'] def clean(self): # Super the clean method to maintain main validation and error messages super(BookForm, self).clean() try: title = self.cleaned_data.get('title') authors = self.cleaned_data.get('authors') book = Book.objects.get(title=title, authors=authors) raise forms.ValidationError( 'The book {} by {} already exists.'.format(title, book.list_authors()), code = 'bookexists' ) except Book.DoesNotExist: return self.cleaned_data ...
3dd22e9c88a0b02655481ef3ca0f5376b8aae1b5
spacy/tests/regression/test_issue834.py
spacy/tests/regression/test_issue834.py
from __future__ import unicode_literals from io import StringIO word2vec_str = """, -0.046107 -0.035951 -0.560418 de -0.648927 -0.400976 -0.527124 . 0.113685 0.439990 -0.634510   -1.499184 -0.184280 -0.598371""" def test_issue834(en_vocab): f = StringIO(word2vec_str) vector_length = en_vocab.load_vectors(f) assert vector_length == 3
from __future__ import unicode_literals from io import StringIO import pytest word2vec_str = """, -0.046107 -0.035951 -0.560418 de -0.648927 -0.400976 -0.527124 . 0.113685 0.439990 -0.634510   -1.499184 -0.184280 -0.598371""" @pytest.mark.xfail def test_issue834(en_vocab): f = StringIO(word2vec_str) vector_length = en_vocab.load_vectors(f) assert vector_length == 3
Mark vectors test as xfail (temporary)
Mark vectors test as xfail (temporary)
Python
mit
oroszgy/spaCy.hu,oroszgy/spaCy.hu,recognai/spaCy,Gregory-Howard/spaCy,aikramer2/spaCy,spacy-io/spaCy,Gregory-Howard/spaCy,oroszgy/spaCy.hu,raphael0202/spaCy,raphael0202/spaCy,aikramer2/spaCy,spacy-io/spaCy,honnibal/spaCy,raphael0202/spaCy,aikramer2/spaCy,aikramer2/spaCy,banglakit/spaCy,recognai/spaCy,honnibal/spaCy,Gregory-Howard/spaCy,explosion/spaCy,banglakit/spaCy,spacy-io/spaCy,banglakit/spaCy,spacy-io/spaCy,oroszgy/spaCy.hu,honnibal/spaCy,aikramer2/spaCy,raphael0202/spaCy,raphael0202/spaCy,raphael0202/spaCy,recognai/spaCy,explosion/spaCy,explosion/spaCy,recognai/spaCy,explosion/spaCy,honnibal/spaCy,oroszgy/spaCy.hu,Gregory-Howard/spaCy,recognai/spaCy,Gregory-Howard/spaCy,banglakit/spaCy,recognai/spaCy,banglakit/spaCy,oroszgy/spaCy.hu,explosion/spaCy,explosion/spaCy,aikramer2/spaCy,Gregory-Howard/spaCy,spacy-io/spaCy,spacy-io/spaCy,banglakit/spaCy
from __future__ import unicode_literals from io import StringIO + + import pytest word2vec_str = """, -0.046107 -0.035951 -0.560418 de -0.648927 -0.400976 -0.527124 . 0.113685 0.439990 -0.634510   -1.499184 -0.184280 -0.598371""" - + @pytest.mark.xfail def test_issue834(en_vocab): f = StringIO(word2vec_str) vector_length = en_vocab.load_vectors(f) assert vector_length == 3
Mark vectors test as xfail (temporary)
## Code Before: from __future__ import unicode_literals from io import StringIO word2vec_str = """, -0.046107 -0.035951 -0.560418 de -0.648927 -0.400976 -0.527124 . 0.113685 0.439990 -0.634510   -1.499184 -0.184280 -0.598371""" def test_issue834(en_vocab): f = StringIO(word2vec_str) vector_length = en_vocab.load_vectors(f) assert vector_length == 3 ## Instruction: Mark vectors test as xfail (temporary) ## Code After: from __future__ import unicode_literals from io import StringIO import pytest word2vec_str = """, -0.046107 -0.035951 -0.560418 de -0.648927 -0.400976 -0.527124 . 0.113685 0.439990 -0.634510   -1.499184 -0.184280 -0.598371""" @pytest.mark.xfail def test_issue834(en_vocab): f = StringIO(word2vec_str) vector_length = en_vocab.load_vectors(f) assert vector_length == 3
// ... existing code ... from io import StringIO import pytest // ... modified code ... @pytest.mark.xfail def test_issue834(en_vocab): // ... rest of the code ...
95eb73ce7645ae6275fbb958ec803ce521b16198
helusers/urls.py
helusers/urls.py
"""URLs module""" from django.urls import path from django.conf import settings from django.core.exceptions import ImproperlyConfigured from . import views app_name = "helusers" urlpatterns = [ path("logout/", views.LogoutView.as_view(), name="auth_logout"), path( "logout/complete/", views.LogoutCompleteView.as_view(), name="auth_logout_complete", ), path("login/", views.LoginView.as_view(), name="auth_login"), ] if not settings.LOGOUT_REDIRECT_URL: raise ImproperlyConfigured( "You must configure LOGOUT_REDIRECT_URL to use helusers views." )
"""URLs module""" from django.urls import path from django.conf import settings from django.core.exceptions import ImproperlyConfigured from . import views app_name = "helusers" urlpatterns = [] if not settings.LOGOUT_REDIRECT_URL: raise ImproperlyConfigured( "You must configure LOGOUT_REDIRECT_URL to use helusers views." ) urlpatterns.extend( [ path("logout/", views.LogoutView.as_view(), name="auth_logout"), path( "logout/complete/", views.LogoutCompleteView.as_view(), name="auth_logout_complete", ), path("login/", views.LoginView.as_view(), name="auth_login"), ] )
Check configuration before specifying urlpatterns
Check configuration before specifying urlpatterns If the configuration is incorrect, it doesn't make sense to specify the URL patterns in that case.
Python
bsd-2-clause
City-of-Helsinki/django-helusers,City-of-Helsinki/django-helusers
"""URLs module""" from django.urls import path from django.conf import settings from django.core.exceptions import ImproperlyConfigured from . import views app_name = "helusers" - urlpatterns = [ + urlpatterns = [] - path("logout/", views.LogoutView.as_view(), name="auth_logout"), - path( - "logout/complete/", - views.LogoutCompleteView.as_view(), - name="auth_logout_complete", - ), - path("login/", views.LoginView.as_view(), name="auth_login"), - ] if not settings.LOGOUT_REDIRECT_URL: raise ImproperlyConfigured( "You must configure LOGOUT_REDIRECT_URL to use helusers views." ) + urlpatterns.extend( + [ + path("logout/", views.LogoutView.as_view(), name="auth_logout"), + path( + "logout/complete/", + views.LogoutCompleteView.as_view(), + name="auth_logout_complete", + ), + path("login/", views.LoginView.as_view(), name="auth_login"), + ] + ) +
Check configuration before specifying urlpatterns
## Code Before: """URLs module""" from django.urls import path from django.conf import settings from django.core.exceptions import ImproperlyConfigured from . import views app_name = "helusers" urlpatterns = [ path("logout/", views.LogoutView.as_view(), name="auth_logout"), path( "logout/complete/", views.LogoutCompleteView.as_view(), name="auth_logout_complete", ), path("login/", views.LoginView.as_view(), name="auth_login"), ] if not settings.LOGOUT_REDIRECT_URL: raise ImproperlyConfigured( "You must configure LOGOUT_REDIRECT_URL to use helusers views." ) ## Instruction: Check configuration before specifying urlpatterns ## Code After: """URLs module""" from django.urls import path from django.conf import settings from django.core.exceptions import ImproperlyConfigured from . import views app_name = "helusers" urlpatterns = [] if not settings.LOGOUT_REDIRECT_URL: raise ImproperlyConfigured( "You must configure LOGOUT_REDIRECT_URL to use helusers views." ) urlpatterns.extend( [ path("logout/", views.LogoutView.as_view(), name="auth_logout"), path( "logout/complete/", views.LogoutCompleteView.as_view(), name="auth_logout_complete", ), path("login/", views.LoginView.as_view(), name="auth_login"), ] )
# ... existing code ... urlpatterns = [] # ... modified code ... ) urlpatterns.extend( [ path("logout/", views.LogoutView.as_view(), name="auth_logout"), path( "logout/complete/", views.LogoutCompleteView.as_view(), name="auth_logout_complete", ), path("login/", views.LoginView.as_view(), name="auth_login"), ] ) # ... rest of the code ...
dc45f973faa5655e821364cfbdb96a3e17ff9893
app/__init__.py
app/__init__.py
import os from flask import Flask, Blueprint, request, jsonify app = Flask(__name__) # Read configuration to apply from environment config_name = os.environ.get('FLASK_CONFIG', 'development') # apply configuration cfg = os.path.join(os.getcwd(), 'config', config_name + '.py') app.config.from_pyfile(cfg) # Create a blueprint api = Blueprint('api', __name__) # Import the endpoints belonging to this blueprint from . import endpoints from . import errors @api.before_request def before_request(): """All routes in this blueprint require authentication.""" if app.config['AUTH_REQUIRED']: if request.args.get('secret_token'): token = request.headers.get(app.config['TOKEN_HEADER']) if token == app.config['SECRET_TOKEN']: app.logger.info('Validated request token') app.logger.warn('Unauthorized: Invalid request token') app.logger.warn('Unauthorized: No request token included') return jsonify({'error': 'unauthorized'}), 401 app.logger.info('No authentication required') # register blueprints app.register_blueprint(api, url_prefix=app.config['URL_PREFIX'])
import os from flask import Flask, Blueprint, request, jsonify app = Flask(__name__) # Read configuration to apply from environment config_name = os.environ.get('FLASK_CONFIG', 'development') # apply configuration cfg = os.path.join(os.getcwd(), 'config', config_name + '.py') app.config.from_pyfile(cfg) # Create a blueprint api = Blueprint('api', __name__) # Import the endpoints belonging to this blueprint from . import endpoints from . import errors @api.before_request def before_request(): """All routes in this blueprint require authentication.""" if app.config['AUTH_REQUIRED']: token_header = app.config['TOKEN_HEADER'] if request.headers.get(token_header): token = request.headers[token_header] if token == app.config['SECRET_TOKEN']: app.logger.info('Validated request token') app.logger.warn('Unauthorized: Invalid request token') app.logger.warn('Unauthorized: No request token included') return jsonify({'error': 'unauthorized'}), 401 app.logger.info('No authentication required') # register blueprints app.register_blueprint(api, url_prefix=app.config['URL_PREFIX'])
Fix bug in token authentication
Fix bug in token authentication
Python
apache-2.0
javicacheiro/salt-git-synchronizer-proxy
import os from flask import Flask, Blueprint, request, jsonify app = Flask(__name__) # Read configuration to apply from environment config_name = os.environ.get('FLASK_CONFIG', 'development') # apply configuration cfg = os.path.join(os.getcwd(), 'config', config_name + '.py') app.config.from_pyfile(cfg) # Create a blueprint api = Blueprint('api', __name__) # Import the endpoints belonging to this blueprint from . import endpoints from . import errors @api.before_request def before_request(): """All routes in this blueprint require authentication.""" if app.config['AUTH_REQUIRED']: - if request.args.get('secret_token'): - token = request.headers.get(app.config['TOKEN_HEADER']) + token_header = app.config['TOKEN_HEADER'] + if request.headers.get(token_header): + token = request.headers[token_header] if token == app.config['SECRET_TOKEN']: app.logger.info('Validated request token') app.logger.warn('Unauthorized: Invalid request token') app.logger.warn('Unauthorized: No request token included') return jsonify({'error': 'unauthorized'}), 401 app.logger.info('No authentication required') # register blueprints app.register_blueprint(api, url_prefix=app.config['URL_PREFIX'])
Fix bug in token authentication
## Code Before: import os from flask import Flask, Blueprint, request, jsonify app = Flask(__name__) # Read configuration to apply from environment config_name = os.environ.get('FLASK_CONFIG', 'development') # apply configuration cfg = os.path.join(os.getcwd(), 'config', config_name + '.py') app.config.from_pyfile(cfg) # Create a blueprint api = Blueprint('api', __name__) # Import the endpoints belonging to this blueprint from . import endpoints from . import errors @api.before_request def before_request(): """All routes in this blueprint require authentication.""" if app.config['AUTH_REQUIRED']: if request.args.get('secret_token'): token = request.headers.get(app.config['TOKEN_HEADER']) if token == app.config['SECRET_TOKEN']: app.logger.info('Validated request token') app.logger.warn('Unauthorized: Invalid request token') app.logger.warn('Unauthorized: No request token included') return jsonify({'error': 'unauthorized'}), 401 app.logger.info('No authentication required') # register blueprints app.register_blueprint(api, url_prefix=app.config['URL_PREFIX']) ## Instruction: Fix bug in token authentication ## Code After: import os from flask import Flask, Blueprint, request, jsonify app = Flask(__name__) # Read configuration to apply from environment config_name = os.environ.get('FLASK_CONFIG', 'development') # apply configuration cfg = os.path.join(os.getcwd(), 'config', config_name + '.py') app.config.from_pyfile(cfg) # Create a blueprint api = Blueprint('api', __name__) # Import the endpoints belonging to this blueprint from . import endpoints from . import errors @api.before_request def before_request(): """All routes in this blueprint require authentication.""" if app.config['AUTH_REQUIRED']: token_header = app.config['TOKEN_HEADER'] if request.headers.get(token_header): token = request.headers[token_header] if token == app.config['SECRET_TOKEN']: app.logger.info('Validated request token') app.logger.warn('Unauthorized: Invalid request token') app.logger.warn('Unauthorized: No request token included') return jsonify({'error': 'unauthorized'}), 401 app.logger.info('No authentication required') # register blueprints app.register_blueprint(api, url_prefix=app.config['URL_PREFIX'])
# ... existing code ... if app.config['AUTH_REQUIRED']: token_header = app.config['TOKEN_HEADER'] if request.headers.get(token_header): token = request.headers[token_header] if token == app.config['SECRET_TOKEN']: # ... rest of the code ...
38d5e165363f55dfedea94397ca85634bf800941
libqtile/layout/sublayouts.py
libqtile/layout/sublayouts.py
from base import SubLayout, Rect from Xlib import Xatom class TopLevelSubLayout(SubLayout): ''' This class effectively wraps a sublayout, and automatically adds a floating sublayout, ''' def __init__(self, sublayout_data, clientStack, theme): WrappedSubLayout, args = sublayout_data SubLayout.__init__(self, clientStack, theme) self.sublayouts.append(Floating(clientStack, theme, parent=self ) ) self.sublayouts.append(WrappedSubLayout(clientStack, theme, parent=self, **args ) ) class VerticalStack(SubLayout): def layout(self, rectangle, windows): SubLayout.layout(self, rectangle, windows) def configure(self, r, client): position = self.windows.index(client) cliheight = int(r.h / len(self.windows)) #inc border self.place(client, r.x, r.y + cliheight*position, r.w, cliheight, ) class Floating(SubLayout): def filter(self, client): return client.floating def request_rectangle(self, r, windows): return (Rect(0,0,0,0), r) #we want nothing def configure(self, r, client): client.unhide() #let it be where it wants
from base import SubLayout, Rect from Xlib import Xatom class TopLevelSubLayout(SubLayout): ''' This class effectively wraps a sublayout, and automatically adds a floating sublayout, ''' def __init__(self, sublayout_data, clientStack, theme): WrappedSubLayout, args = sublayout_data SubLayout.__init__(self, clientStack, theme) self.sublayouts.append(Floating(clientStack, theme, parent=self ) ) self.sublayouts.append(WrappedSubLayout(clientStack, theme, parent=self, **args ) ) class VerticalStack(SubLayout): def layout(self, rectangle, windows): SubLayout.layout(self, rectangle, windows) def configure(self, r, client): position = self.windows.index(client) cliheight = int(r.h / len(self.windows)) #inc border self.place(client, r.x, r.y + cliheight*position, r.w, cliheight, ) class Floating(SubLayout): def filter(self, client): return client.floating def request_rectangle(self, r, windows): return (Rect(0,0,0,0), r) #we want nothing def configure(self, r, client): d = client.floatDimensions self.place(client, **d)
Update floating sublayout to use floatDimensions
Update floating sublayout to use floatDimensions
Python
mit
himaaaatti/qtile,dequis/qtile,cortesi/qtile,kopchik/qtile,zordsdavini/qtile,frostidaho/qtile,nxnfufunezn/qtile,himaaaatti/qtile,EndPointCorp/qtile,zordsdavini/qtile,encukou/qtile,kynikos/qtile,flacjacket/qtile,bavardage/qtile,kseistrup/qtile,soulchainer/qtile,jdowner/qtile,apinsard/qtile,rxcomm/qtile,ramnes/qtile,EndPointCorp/qtile,de-vri-es/qtile,StephenBarnes/qtile,qtile/qtile,xplv/qtile,jdowner/qtile,cortesi/qtile,de-vri-es/qtile,frostidaho/qtile,kseistrup/qtile,w1ndy/qtile,andrewyoung1991/qtile,tych0/qtile,dequis/qtile,tych0/qtile,flacjacket/qtile,aniruddhkanojia/qtile,soulchainer/qtile,farebord/qtile,rxcomm/qtile,kiniou/qtile,aniruddhkanojia/qtile,encukou/qtile,kiniou/qtile,nxnfufunezn/qtile,xplv/qtile,kopchik/qtile,StephenBarnes/qtile,w1ndy/qtile,apinsard/qtile,ramnes/qtile,qtile/qtile,kynikos/qtile,farebord/qtile,andrewyoung1991/qtile
from base import SubLayout, Rect from Xlib import Xatom class TopLevelSubLayout(SubLayout): ''' This class effectively wraps a sublayout, and automatically adds a floating sublayout, ''' def __init__(self, sublayout_data, clientStack, theme): WrappedSubLayout, args = sublayout_data SubLayout.__init__(self, clientStack, theme) self.sublayouts.append(Floating(clientStack, theme, parent=self ) ) self.sublayouts.append(WrappedSubLayout(clientStack, theme, parent=self, **args ) ) class VerticalStack(SubLayout): def layout(self, rectangle, windows): SubLayout.layout(self, rectangle, windows) def configure(self, r, client): position = self.windows.index(client) cliheight = int(r.h / len(self.windows)) #inc border self.place(client, r.x, r.y + cliheight*position, r.w, cliheight, ) class Floating(SubLayout): def filter(self, client): return client.floating def request_rectangle(self, r, windows): return (Rect(0,0,0,0), r) #we want nothing def configure(self, r, client): - client.unhide() #let it be where it wants + d = client.floatDimensions + self.place(client, **d)
Update floating sublayout to use floatDimensions
## Code Before: from base import SubLayout, Rect from Xlib import Xatom class TopLevelSubLayout(SubLayout): ''' This class effectively wraps a sublayout, and automatically adds a floating sublayout, ''' def __init__(self, sublayout_data, clientStack, theme): WrappedSubLayout, args = sublayout_data SubLayout.__init__(self, clientStack, theme) self.sublayouts.append(Floating(clientStack, theme, parent=self ) ) self.sublayouts.append(WrappedSubLayout(clientStack, theme, parent=self, **args ) ) class VerticalStack(SubLayout): def layout(self, rectangle, windows): SubLayout.layout(self, rectangle, windows) def configure(self, r, client): position = self.windows.index(client) cliheight = int(r.h / len(self.windows)) #inc border self.place(client, r.x, r.y + cliheight*position, r.w, cliheight, ) class Floating(SubLayout): def filter(self, client): return client.floating def request_rectangle(self, r, windows): return (Rect(0,0,0,0), r) #we want nothing def configure(self, r, client): client.unhide() #let it be where it wants ## Instruction: Update floating sublayout to use floatDimensions ## Code After: from base import SubLayout, Rect from Xlib import Xatom class TopLevelSubLayout(SubLayout): ''' This class effectively wraps a sublayout, and automatically adds a floating sublayout, ''' def __init__(self, sublayout_data, clientStack, theme): WrappedSubLayout, args = sublayout_data SubLayout.__init__(self, clientStack, theme) self.sublayouts.append(Floating(clientStack, theme, parent=self ) ) self.sublayouts.append(WrappedSubLayout(clientStack, theme, parent=self, **args ) ) class VerticalStack(SubLayout): def layout(self, rectangle, windows): SubLayout.layout(self, rectangle, windows) def configure(self, r, client): position = self.windows.index(client) cliheight = int(r.h / len(self.windows)) #inc border self.place(client, r.x, r.y + cliheight*position, r.w, cliheight, ) class Floating(SubLayout): def filter(self, client): return client.floating def request_rectangle(self, r, windows): return (Rect(0,0,0,0), r) #we want nothing def configure(self, r, client): d = client.floatDimensions self.place(client, **d)
... def configure(self, r, client): d = client.floatDimensions self.place(client, **d) ...
69d3ec01ec3e9e9369b5c0425bc63cc7f2797b52
__init__.py
__init__.py
import pyOmicron import STS __all__=["pyOmicron","STS"] __version__ = 0.1
import pyOmicron try: import STS except: import pyOmicron.STS __all__=["pyOmicron","STS"] __version__ = 0.1
Fix import for python 3
Fix import for python 3
Python
apache-2.0
scholi/pyOmicron
import pyOmicron + try: - import STS + import STS + except: + import pyOmicron.STS __all__=["pyOmicron","STS"] __version__ = 0.1
Fix import for python 3
## Code Before: import pyOmicron import STS __all__=["pyOmicron","STS"] __version__ = 0.1 ## Instruction: Fix import for python 3 ## Code After: import pyOmicron try: import STS except: import pyOmicron.STS __all__=["pyOmicron","STS"] __version__ = 0.1
# ... existing code ... import pyOmicron try: import STS except: import pyOmicron.STS # ... rest of the code ...
63e5bd0e7c771e4a2efe2ff203b75e4a56024af5
app.py
app.py
from flask import Flask from flask.ext.mongoengine import MongoEngine from flask import request from flask import render_template app = Flask(__name__) app.config.from_pyfile('flask-conf.cfg') db = MongoEngine(app) @app.route('/') def index(): return render_template('index.html') @app.route('/signup', methods=['GET', 'POST']) def signup(): if request.method == 'GET': return render_template('signup.html') else: return 'ok' @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'GET': return render_template('login.html') else: return 'ok' @app.route('/forgot-password', methods=['GET', 'POST']) def forgot_password(): if request.method == 'GET': return render_template('forgot-password.html') else: return 'ok' @app.route('/password-reset/<token>', methods=['GET', 'POST']) def password_reset(token): if request.method == 'GET': return render_template('password-reset.html') else: return 'ok' if __name__ == '__main__': app.run()
from flask import Flask from flask.ext.mongoengine import MongoEngine from flask import request from flask import render_template app = Flask(__name__, static_url_path='', static_folder='frontend/dist') app.config.from_pyfile('flask-conf.cfg') # db = MongoEngine(app) @app.route('/') def index(): return render_template('index.html') @app.route('/signup', methods=['GET', 'POST']) def signup(): if request.method == 'GET': return render_template('signup.html') else: return 'ok' @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'GET': return render_template('login.html') else: return 'ok' @app.route('/forgot-password', methods=['GET', 'POST']) def forgot_password(): if request.method == 'GET': return render_template('forgot-password.html') else: return 'ok' @app.route('/password-reset/<token>', methods=['GET', 'POST']) def password_reset(token): if request.method == 'GET': return render_template('password-reset.html') else: return 'ok' if __name__ == '__main__': app.run()
Change static directory, commented mongo dev stuff
Change static directory, commented mongo dev stuff
Python
mit
cogniteev/logup-factory,cogniteev/logup-factory
from flask import Flask from flask.ext.mongoengine import MongoEngine from flask import request from flask import render_template - app = Flask(__name__) + app = Flask(__name__, static_url_path='', static_folder='frontend/dist') app.config.from_pyfile('flask-conf.cfg') - db = MongoEngine(app) + # db = MongoEngine(app) @app.route('/') def index(): return render_template('index.html') @app.route('/signup', methods=['GET', 'POST']) def signup(): if request.method == 'GET': return render_template('signup.html') else: return 'ok' @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'GET': return render_template('login.html') else: return 'ok' @app.route('/forgot-password', methods=['GET', 'POST']) def forgot_password(): if request.method == 'GET': return render_template('forgot-password.html') else: return 'ok' @app.route('/password-reset/<token>', methods=['GET', 'POST']) def password_reset(token): if request.method == 'GET': return render_template('password-reset.html') else: return 'ok' if __name__ == '__main__': app.run()
Change static directory, commented mongo dev stuff
## Code Before: from flask import Flask from flask.ext.mongoengine import MongoEngine from flask import request from flask import render_template app = Flask(__name__) app.config.from_pyfile('flask-conf.cfg') db = MongoEngine(app) @app.route('/') def index(): return render_template('index.html') @app.route('/signup', methods=['GET', 'POST']) def signup(): if request.method == 'GET': return render_template('signup.html') else: return 'ok' @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'GET': return render_template('login.html') else: return 'ok' @app.route('/forgot-password', methods=['GET', 'POST']) def forgot_password(): if request.method == 'GET': return render_template('forgot-password.html') else: return 'ok' @app.route('/password-reset/<token>', methods=['GET', 'POST']) def password_reset(token): if request.method == 'GET': return render_template('password-reset.html') else: return 'ok' if __name__ == '__main__': app.run() ## Instruction: Change static directory, commented mongo dev stuff ## Code After: from flask import Flask from flask.ext.mongoengine import MongoEngine from flask import request from flask import render_template app = Flask(__name__, static_url_path='', static_folder='frontend/dist') app.config.from_pyfile('flask-conf.cfg') # db = MongoEngine(app) @app.route('/') def index(): return render_template('index.html') @app.route('/signup', methods=['GET', 'POST']) def signup(): if request.method == 'GET': return render_template('signup.html') else: return 'ok' @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'GET': return render_template('login.html') else: return 'ok' @app.route('/forgot-password', methods=['GET', 'POST']) def forgot_password(): if request.method == 'GET': return render_template('forgot-password.html') else: return 'ok' @app.route('/password-reset/<token>', methods=['GET', 'POST']) def password_reset(token): if request.method == 'GET': return render_template('password-reset.html') else: return 'ok' if __name__ == '__main__': app.run()
// ... existing code ... app = Flask(__name__, static_url_path='', static_folder='frontend/dist') app.config.from_pyfile('flask-conf.cfg') // ... modified code ... # db = MongoEngine(app) // ... rest of the code ...
ed0f115e600a564117ed540e7692e0efccf5826b
server/nso.py
server/nso.py
from flask import request, Response from .base import * from server import app import requests import re import sys reload(sys) sys.setdefaultencoding('utf-8') @app.route('/nso') def get_nso_events(): r = requests.get("http://www.nso.upenn.edu/event-calendar.rss") split = r.text.split("\n") filtered = [i if "<pubDate" not in i else "<pubDate>Wed, 02 Aug 2016 08:00:00 EST</pubDate>" for i in split] output = "\n".join(filtered) return Response(output, mimetype="text/xml")
from flask import request, Response from .base import * from server import app import requests import re import sys reload(sys) sys.setdefaultencoding('utf-8') @app.route('/nso') def get_nso_events(): r = requests.get("http://www.nso.upenn.edu/event-calendar.rss") split = r.text.split("\n") filtered = [i if "<pubDate" not in i else "<pubDate>Wed, 02 Aug 2016 08:00:00 EST</pubDate>" for i in split] filtered = [i if ("<title" not in i or "NSO Event Calendar" in i) else changeTitle(i) for i in filtered] output = "\n".join(filtered) return Response(output, mimetype="text/xml") def changeTitle(a): index = a.index("event") + 17 a = subFour(a,index) if a[index+6] == '-': a = subFour(a,index + 18) return a def subFour(string, index): val = string[index:index+6] new_val = str(int(val) - 40000) if len(new_val) < 6: new_val = "0" + new_val return string.replace(val, new_val)
Set time back four hours to EST
Set time back four hours to EST
Python
mit
pennlabs/penn-mobile-server,pennlabs/penn-mobile-server
from flask import request, Response from .base import * from server import app import requests import re import sys reload(sys) sys.setdefaultencoding('utf-8') @app.route('/nso') def get_nso_events(): r = requests.get("http://www.nso.upenn.edu/event-calendar.rss") split = r.text.split("\n") - filtered = [i if "<pubDate" not in i else "<pubDate>Wed, 02 Aug 2016 08:00:00 EST</pubDate>" for i in split] + filtered = [i if "<pubDate" not in i else "<pubDate>Wed, 02 Aug 2016 08:00:00 EST</pubDate>" for i in split] + filtered = [i if ("<title" not in i or "NSO Event Calendar" in i) else changeTitle(i) for i in filtered] output = "\n".join(filtered) return Response(output, mimetype="text/xml") + def changeTitle(a): + index = a.index("event") + 17 + a = subFour(a,index) + if a[index+6] == '-': + a = subFour(a,index + 18) + return a + + def subFour(string, index): + val = string[index:index+6] + new_val = str(int(val) - 40000) + if len(new_val) < 6: + new_val = "0" + new_val + return string.replace(val, new_val) + +
Set time back four hours to EST
## Code Before: from flask import request, Response from .base import * from server import app import requests import re import sys reload(sys) sys.setdefaultencoding('utf-8') @app.route('/nso') def get_nso_events(): r = requests.get("http://www.nso.upenn.edu/event-calendar.rss") split = r.text.split("\n") filtered = [i if "<pubDate" not in i else "<pubDate>Wed, 02 Aug 2016 08:00:00 EST</pubDate>" for i in split] output = "\n".join(filtered) return Response(output, mimetype="text/xml") ## Instruction: Set time back four hours to EST ## Code After: from flask import request, Response from .base import * from server import app import requests import re import sys reload(sys) sys.setdefaultencoding('utf-8') @app.route('/nso') def get_nso_events(): r = requests.get("http://www.nso.upenn.edu/event-calendar.rss") split = r.text.split("\n") filtered = [i if "<pubDate" not in i else "<pubDate>Wed, 02 Aug 2016 08:00:00 EST</pubDate>" for i in split] filtered = [i if ("<title" not in i or "NSO Event Calendar" in i) else changeTitle(i) for i in filtered] output = "\n".join(filtered) return Response(output, mimetype="text/xml") def changeTitle(a): index = a.index("event") + 17 a = subFour(a,index) if a[index+6] == '-': a = subFour(a,index + 18) return a def subFour(string, index): val = string[index:index+6] new_val = str(int(val) - 40000) if len(new_val) < 6: new_val = "0" + new_val return string.replace(val, new_val)
# ... existing code ... split = r.text.split("\n") filtered = [i if "<pubDate" not in i else "<pubDate>Wed, 02 Aug 2016 08:00:00 EST</pubDate>" for i in split] filtered = [i if ("<title" not in i or "NSO Event Calendar" in i) else changeTitle(i) for i in filtered] output = "\n".join(filtered) # ... modified code ... return Response(output, mimetype="text/xml") def changeTitle(a): index = a.index("event") + 17 a = subFour(a,index) if a[index+6] == '-': a = subFour(a,index + 18) return a def subFour(string, index): val = string[index:index+6] new_val = str(int(val) - 40000) if len(new_val) < 6: new_val = "0" + new_val return string.replace(val, new_val) # ... rest of the code ...
b66143e2984fb390766cf47dd2297a3f06ad26d0
apps/home/views.py
apps/home/views.py
from django.core.urlresolvers import reverse from django.shortcuts import redirect from django.views.generic.base import View from django.contrib.auth import login class Home(View): # Get the homepage. If the user isn't logged in, (we can find no trace # of the user) or they are logged in but somehow don't have a valid slug # then we bounce them to the login page. # Otherwise (for the moment) we take them to the list of links. def get(self, request, *args, **kwargs): userid = request.META.get('HTTP_KEYCLOAK_USERNAME') if userid: try: user = get_user_model().objects.get(userid=userid) except: user = get_user_model().objects.create_user( userid=userid, is_active=True) user.backend = 'django.contrib.auth.backends.ModelBackend' login(self.request, user) self.user = user return redirect(reverse('link-list')) try: u = request.user.slug if (u is not None and u is not ''): return redirect(reverse('link-list')) else: return redirect(reverse('login')) except: return redirect(reverse('login'))
from django.core.urlresolvers import reverse from django.shortcuts import redirect from django.views.generic.base import View from django.contrib.auth import login from django.contrib.auth import get_user_model class Home(View): # Get the homepage. If the user isn't logged in, (we can find no trace # of the user) or they are logged in but somehow don't have a valid slug # then we bounce them to the login page. # Otherwise (for the moment) we take them to the list of links. def get(self, request, *args, **kwargs): userid = request.META.get('HTTP_KEYCLOAK_USERNAME') if userid: try: user = get_user_model().objects.get(userid=userid) except: user = get_user_model().objects.create_user( userid=userid, is_active=True) user.backend = 'django.contrib.auth.backends.ModelBackend' login(self.request, user) self.user = user return redirect(reverse('link-list')) try: u = request.user.slug if (u is not None and u is not ''): return redirect(reverse('link-list')) else: return redirect(reverse('login')) except: return redirect(reverse('login'))
Add import statement for get_user_model.
Add import statement for get_user_model.
Python
mit
dstl/lighthouse,dstl/lighthouse,dstl/lighthouse,dstl/lighthouse,dstl/lighthouse
from django.core.urlresolvers import reverse from django.shortcuts import redirect from django.views.generic.base import View from django.contrib.auth import login + from django.contrib.auth import get_user_model class Home(View): # Get the homepage. If the user isn't logged in, (we can find no trace # of the user) or they are logged in but somehow don't have a valid slug # then we bounce them to the login page. # Otherwise (for the moment) we take them to the list of links. def get(self, request, *args, **kwargs): userid = request.META.get('HTTP_KEYCLOAK_USERNAME') if userid: try: user = get_user_model().objects.get(userid=userid) except: user = get_user_model().objects.create_user( userid=userid, is_active=True) user.backend = 'django.contrib.auth.backends.ModelBackend' login(self.request, user) self.user = user return redirect(reverse('link-list')) try: u = request.user.slug if (u is not None and u is not ''): return redirect(reverse('link-list')) else: return redirect(reverse('login')) except: return redirect(reverse('login'))
Add import statement for get_user_model.
## Code Before: from django.core.urlresolvers import reverse from django.shortcuts import redirect from django.views.generic.base import View from django.contrib.auth import login class Home(View): # Get the homepage. If the user isn't logged in, (we can find no trace # of the user) or they are logged in but somehow don't have a valid slug # then we bounce them to the login page. # Otherwise (for the moment) we take them to the list of links. def get(self, request, *args, **kwargs): userid = request.META.get('HTTP_KEYCLOAK_USERNAME') if userid: try: user = get_user_model().objects.get(userid=userid) except: user = get_user_model().objects.create_user( userid=userid, is_active=True) user.backend = 'django.contrib.auth.backends.ModelBackend' login(self.request, user) self.user = user return redirect(reverse('link-list')) try: u = request.user.slug if (u is not None and u is not ''): return redirect(reverse('link-list')) else: return redirect(reverse('login')) except: return redirect(reverse('login')) ## Instruction: Add import statement for get_user_model. ## Code After: from django.core.urlresolvers import reverse from django.shortcuts import redirect from django.views.generic.base import View from django.contrib.auth import login from django.contrib.auth import get_user_model class Home(View): # Get the homepage. If the user isn't logged in, (we can find no trace # of the user) or they are logged in but somehow don't have a valid slug # then we bounce them to the login page. # Otherwise (for the moment) we take them to the list of links. def get(self, request, *args, **kwargs): userid = request.META.get('HTTP_KEYCLOAK_USERNAME') if userid: try: user = get_user_model().objects.get(userid=userid) except: user = get_user_model().objects.create_user( userid=userid, is_active=True) user.backend = 'django.contrib.auth.backends.ModelBackend' login(self.request, user) self.user = user return redirect(reverse('link-list')) try: u = request.user.slug if (u is not None and u is not ''): return redirect(reverse('link-list')) else: return redirect(reverse('login')) except: return redirect(reverse('login'))
# ... existing code ... from django.contrib.auth import login from django.contrib.auth import get_user_model # ... rest of the code ...
b3935065232a97b7eb65c38e5c7bc60570467c71
news/urls.py
news/urls.py
from django.conf.urls import url from . import views app_name = 'news' urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='index'), url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/(?P<slug>[-\w]+)/$', views.ArticleView.as_view(), name='article'), ]
from django.urls import include, path from . import views app_name = 'news' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<int:year>/<int:month>/<int:day>/<slug:slug>/', views.ArticleView.as_view(), name='article'), ]
Move news urlpatterns to Django 2.0 preferred method
Move news urlpatterns to Django 2.0 preferred method
Python
mit
evanepio/dotmanca,evanepio/dotmanca,evanepio/dotmanca
- from django.conf.urls import url + from django.urls import include, path from . import views app_name = 'news' urlpatterns = [ - url(r'^$', views.IndexView.as_view(), name='index'), + path('', views.IndexView.as_view(), name='index'), + path('<int:year>/<int:month>/<int:day>/<slug:slug>/', views.ArticleView.as_view(), name='article'), - url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/(?P<slug>[-\w]+)/$', - views.ArticleView.as_view(), name='article'), ]
Move news urlpatterns to Django 2.0 preferred method
## Code Before: from django.conf.urls import url from . import views app_name = 'news' urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='index'), url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/(?P<slug>[-\w]+)/$', views.ArticleView.as_view(), name='article'), ] ## Instruction: Move news urlpatterns to Django 2.0 preferred method ## Code After: from django.urls import include, path from . import views app_name = 'news' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<int:year>/<int:month>/<int:day>/<slug:slug>/', views.ArticleView.as_view(), name='article'), ]
// ... existing code ... from django.urls import include, path // ... modified code ... urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<int:year>/<int:month>/<int:day>/<slug:slug>/', views.ArticleView.as_view(), name='article'), ] // ... rest of the code ...
c1dc571faa9bf2ae0e0a580365943806826ced4a
src/adhocracy_spd/adhocracy_spd/workflows/digital_leben.py
src/adhocracy_spd/adhocracy_spd/workflows/digital_leben.py
"""Digital leben workflow.""" from adhocracy_core.workflows import add_workflow from adhocracy_core.workflows.standard import standard_meta digital_leben_meta = standard_meta \ .transform(('states', 'participate', 'acm'), {'principals': [ 'participant', 'moderator', 'creator', 'initiator'], # noqa 'permissions': [['create_proposal', None, None, None, 'Allow'], # noqa ['edit_proposal', None, None, 'Allow', 'Allow'], # noqa ['create_comment', 'Allow', 'Allow', None, 'Allow'], # noqa ['edit_comment', None, None, 'Allow', None ], # noqa ['create_rate', 'Allow', None, None, None ], # noqa ['edit_rate', None, None, 'Allow', None ], # noqa ]}) def includeme(config): """Add workflow.""" add_workflow(config.registry, digital_leben_meta, 'digital_leben')
"""Digital leben workflow.""" from adhocracy_core.workflows import add_workflow from adhocracy_core.workflows.standard import standard_meta digital_leben_meta = standard_meta \ .transform(('states', 'participate', 'acm'), {'principals': ['participant', 'moderator', 'creator', 'initiator'], # noqa 'permissions': [['create_proposal', None, None, None, 'Allow'], # noqa ['edit_proposal', None, None, 'Allow', 'Allow'], # noqa ['create_comment', 'Allow', 'Allow', None, 'Allow'], # noqa ['edit_comment', None, None, 'Allow', None], # noqa ['create_rate', 'Allow', None, None, None], # noqa ['edit_rate', None, None, 'Allow', None], # noqa ]}) def includeme(config): """Add workflow.""" add_workflow(config.registry, digital_leben_meta, 'digital_leben')
Make flake8 happy for spd
Make flake8 happy for spd
Python
agpl-3.0
liqd/adhocracy3.mercator,xs2maverick/adhocracy3.mercator,liqd/adhocracy3.mercator,fhartwig/adhocracy3.mercator,fhartwig/adhocracy3.mercator,fhartwig/adhocracy3.mercator,xs2maverick/adhocracy3.mercator,liqd/adhocracy3.mercator,liqd/adhocracy3.mercator,fhartwig/adhocracy3.mercator,liqd/adhocracy3.mercator,xs2maverick/adhocracy3.mercator,xs2maverick/adhocracy3.mercator,liqd/adhocracy3.mercator,liqd/adhocracy3.mercator,xs2maverick/adhocracy3.mercator,xs2maverick/adhocracy3.mercator,fhartwig/adhocracy3.mercator,fhartwig/adhocracy3.mercator,fhartwig/adhocracy3.mercator
"""Digital leben workflow.""" from adhocracy_core.workflows import add_workflow from adhocracy_core.workflows.standard import standard_meta - digital_leben_meta = standard_meta \ + digital_leben_meta = standard_meta \ - .transform(('states', 'participate', 'acm'), + .transform(('states', 'participate', 'acm'), - {'principals': [ 'participant', 'moderator', 'creator', 'initiator'], # noqa + {'principals': ['participant', 'moderator', 'creator', 'initiator'], # noqa - 'permissions': + 'permissions': - [['create_proposal', None, None, None, 'Allow'], # noqa + [['create_proposal', None, None, None, 'Allow'], # noqa - ['edit_proposal', None, None, 'Allow', 'Allow'], # noqa + ['edit_proposal', None, None, 'Allow', 'Allow'], # noqa - ['create_comment', 'Allow', 'Allow', None, 'Allow'], # noqa + ['create_comment', 'Allow', 'Allow', None, 'Allow'], # noqa - ['edit_comment', None, None, 'Allow', None ], # noqa + ['edit_comment', None, None, 'Allow', None], # noqa - ['create_rate', 'Allow', None, None, None ], # noqa + ['create_rate', 'Allow', None, None, None], # noqa - ['edit_rate', None, None, 'Allow', None ], # noqa + ['edit_rate', None, None, 'Allow', None], # noqa - ]}) + ]}) def includeme(config): """Add workflow.""" add_workflow(config.registry, digital_leben_meta, 'digital_leben')
Make flake8 happy for spd
## Code Before: """Digital leben workflow.""" from adhocracy_core.workflows import add_workflow from adhocracy_core.workflows.standard import standard_meta digital_leben_meta = standard_meta \ .transform(('states', 'participate', 'acm'), {'principals': [ 'participant', 'moderator', 'creator', 'initiator'], # noqa 'permissions': [['create_proposal', None, None, None, 'Allow'], # noqa ['edit_proposal', None, None, 'Allow', 'Allow'], # noqa ['create_comment', 'Allow', 'Allow', None, 'Allow'], # noqa ['edit_comment', None, None, 'Allow', None ], # noqa ['create_rate', 'Allow', None, None, None ], # noqa ['edit_rate', None, None, 'Allow', None ], # noqa ]}) def includeme(config): """Add workflow.""" add_workflow(config.registry, digital_leben_meta, 'digital_leben') ## Instruction: Make flake8 happy for spd ## Code After: """Digital leben workflow.""" from adhocracy_core.workflows import add_workflow from adhocracy_core.workflows.standard import standard_meta digital_leben_meta = standard_meta \ .transform(('states', 'participate', 'acm'), {'principals': ['participant', 'moderator', 'creator', 'initiator'], # noqa 'permissions': [['create_proposal', None, None, None, 'Allow'], # noqa ['edit_proposal', None, None, 'Allow', 'Allow'], # noqa ['create_comment', 'Allow', 'Allow', None, 'Allow'], # noqa ['edit_comment', None, None, 'Allow', None], # noqa ['create_rate', 'Allow', None, None, None], # noqa ['edit_rate', None, None, 'Allow', None], # noqa ]}) def includeme(config): """Add workflow.""" add_workflow(config.registry, digital_leben_meta, 'digital_leben')
// ... existing code ... digital_leben_meta = standard_meta \ .transform(('states', 'participate', 'acm'), {'principals': ['participant', 'moderator', 'creator', 'initiator'], # noqa 'permissions': [['create_proposal', None, None, None, 'Allow'], # noqa ['edit_proposal', None, None, 'Allow', 'Allow'], # noqa ['create_comment', 'Allow', 'Allow', None, 'Allow'], # noqa ['edit_comment', None, None, 'Allow', None], # noqa ['create_rate', 'Allow', None, None, None], # noqa ['edit_rate', None, None, 'Allow', None], # noqa ]}) // ... rest of the code ...
a6ce774d11100208d2a65aa71c3cb147a550a906
dpath/__init__.py
dpath/__init__.py
import sys # Python version flags for Python 3 support PY2 = ( sys.version_info.major == 2 ) PY3 = ( sys.version_info.major == 3 )
import sys # Python version flags for Python 3 support python_major_version = 0 if hasattr(sys.version_info, 'major'): python_major_version = sys.version_info.major else: python_major_version = sys.version_info[0] PY2 = ( python_major_version == 2 ) PY3 = ( python_major_version == 3 )
Make this work on python2.6 again
Make this work on python2.6 again
Python
mit
akesterson/dpath-python,pombredanne/dpath-python,benthomasson/dpath-python,lexhung/dpath-python,calebcase/dpath-python
import sys # Python version flags for Python 3 support - PY2 = ( sys.version_info.major == 2 ) - PY3 = ( sys.version_info.major == 3 ) + python_major_version = 0 + if hasattr(sys.version_info, 'major'): + python_major_version = sys.version_info.major + else: + python_major_version = sys.version_info[0] + PY2 = ( python_major_version == 2 ) + PY3 = ( python_major_version == 3 ) +
Make this work on python2.6 again
## Code Before: import sys # Python version flags for Python 3 support PY2 = ( sys.version_info.major == 2 ) PY3 = ( sys.version_info.major == 3 ) ## Instruction: Make this work on python2.6 again ## Code After: import sys # Python version flags for Python 3 support python_major_version = 0 if hasattr(sys.version_info, 'major'): python_major_version = sys.version_info.major else: python_major_version = sys.version_info[0] PY2 = ( python_major_version == 2 ) PY3 = ( python_major_version == 3 )
# ... existing code ... # Python version flags for Python 3 support python_major_version = 0 if hasattr(sys.version_info, 'major'): python_major_version = sys.version_info.major else: python_major_version = sys.version_info[0] PY2 = ( python_major_version == 2 ) PY3 = ( python_major_version == 3 ) # ... rest of the code ...
fe5eb7db52725f8d136cbeba4341f5c3a33cf199
tensorflow_model_optimization/python/core/api/quantization/keras/quantizers/__init__.py
tensorflow_model_optimization/python/core/api/quantization/keras/quantizers/__init__.py
"""Module containing Quantization abstraction and quantizers.""" # quantize with custom quantization parameterization or implementation, or # handle custom Keras layers. from tensorflow_model_optimization.python.core.quantization.keras.quantizers import LastValueQuantizer from tensorflow_model_optimization.python.core.quantization.keras.quantizers import MovingAverageQuantizer from tensorflow_model_optimization.python.core.quantization.keras.quantizers import Quantizer
"""Module containing Quantization abstraction and quantizers.""" # quantize with custom quantization parameterization or implementation, or # handle custom Keras layers. from tensorflow_model_optimization.python.core.quantization.keras.quantizers import AllValuesQuantizer from tensorflow_model_optimization.python.core.quantization.keras.quantizers import LastValueQuantizer from tensorflow_model_optimization.python.core.quantization.keras.quantizers import MovingAverageQuantizer from tensorflow_model_optimization.python.core.quantization.keras.quantizers import Quantizer
Include AllValuesQuantizer in external APIs
Include AllValuesQuantizer in external APIs PiperOrigin-RevId: 320104499
Python
apache-2.0
tensorflow/model-optimization,tensorflow/model-optimization
"""Module containing Quantization abstraction and quantizers.""" # quantize with custom quantization parameterization or implementation, or # handle custom Keras layers. + from tensorflow_model_optimization.python.core.quantization.keras.quantizers import AllValuesQuantizer from tensorflow_model_optimization.python.core.quantization.keras.quantizers import LastValueQuantizer from tensorflow_model_optimization.python.core.quantization.keras.quantizers import MovingAverageQuantizer from tensorflow_model_optimization.python.core.quantization.keras.quantizers import Quantizer
Include AllValuesQuantizer in external APIs
## Code Before: """Module containing Quantization abstraction and quantizers.""" # quantize with custom quantization parameterization or implementation, or # handle custom Keras layers. from tensorflow_model_optimization.python.core.quantization.keras.quantizers import LastValueQuantizer from tensorflow_model_optimization.python.core.quantization.keras.quantizers import MovingAverageQuantizer from tensorflow_model_optimization.python.core.quantization.keras.quantizers import Quantizer ## Instruction: Include AllValuesQuantizer in external APIs ## Code After: """Module containing Quantization abstraction and quantizers.""" # quantize with custom quantization parameterization or implementation, or # handle custom Keras layers. from tensorflow_model_optimization.python.core.quantization.keras.quantizers import AllValuesQuantizer from tensorflow_model_optimization.python.core.quantization.keras.quantizers import LastValueQuantizer from tensorflow_model_optimization.python.core.quantization.keras.quantizers import MovingAverageQuantizer from tensorflow_model_optimization.python.core.quantization.keras.quantizers import Quantizer
// ... existing code ... # handle custom Keras layers. from tensorflow_model_optimization.python.core.quantization.keras.quantizers import AllValuesQuantizer from tensorflow_model_optimization.python.core.quantization.keras.quantizers import LastValueQuantizer // ... rest of the code ...
115615a2a183684eed4f11e98a7da12190059fb1
armstrong/core/arm_layout/utils.py
armstrong/core/arm_layout/utils.py
from django.utils.safestring import mark_safe from django.template.loader import render_to_string from armstrong.utils.backends import GenericBackend render_model = (GenericBackend("ARMSTRONG_RENDER_MODEL_BACKEND", defaults="armstrong.core.arm_layout.backends.BasicRenderModelBackend") .get_backend()) # Here for backwards compatibility (deprecated) get_layout_template_name = render_model.get_layout_template_name
import warnings from armstrong.utils.backends import GenericBackend render_model = (GenericBackend("ARMSTRONG_RENDER_MODEL_BACKEND", defaults="armstrong.core.arm_layout.backends.BasicRenderModelBackend") .get_backend()) # DEPRECATED: To be removed in ArmLayout 1.4. Here for backwards compatibility from django.utils.safestring import mark_safe from django.template.loader import render_to_string def deprecate(func): def wrapper(*args, **kwargs): msg = "Importing `{}` from this module is deprecated and will be removed in ArmLayout 1.4" warnings.warn(msg.format(func.__name__), DeprecationWarning) return func(*args, **kwargs) return wrapper mark_safe = deprecate(mark_safe) render_to_string = deprecate(render_to_string) get_layout_template_name = deprecate(render_model.get_layout_template_name)
Throw deprecation warnings for these imports, which will be removed in the next version. They've been deprecated for two years so we can make it happen.
Throw deprecation warnings for these imports, which will be removed in the next version. They've been deprecated for two years so we can make it happen.
Python
apache-2.0
armstrong/armstrong.core.arm_layout,armstrong/armstrong.core.arm_layout
+ import warnings - from django.utils.safestring import mark_safe - from django.template.loader import render_to_string - from armstrong.utils.backends import GenericBackend render_model = (GenericBackend("ARMSTRONG_RENDER_MODEL_BACKEND", defaults="armstrong.core.arm_layout.backends.BasicRenderModelBackend") .get_backend()) - # Here for backwards compatibility (deprecated) - get_layout_template_name = render_model.get_layout_template_name + # DEPRECATED: To be removed in ArmLayout 1.4. Here for backwards compatibility + from django.utils.safestring import mark_safe + from django.template.loader import render_to_string + + def deprecate(func): + def wrapper(*args, **kwargs): + msg = "Importing `{}` from this module is deprecated and will be removed in ArmLayout 1.4" + warnings.warn(msg.format(func.__name__), DeprecationWarning) + return func(*args, **kwargs) + return wrapper + + mark_safe = deprecate(mark_safe) + render_to_string = deprecate(render_to_string) + get_layout_template_name = deprecate(render_model.get_layout_template_name) +
Throw deprecation warnings for these imports, which will be removed in the next version. They've been deprecated for two years so we can make it happen.
## Code Before: from django.utils.safestring import mark_safe from django.template.loader import render_to_string from armstrong.utils.backends import GenericBackend render_model = (GenericBackend("ARMSTRONG_RENDER_MODEL_BACKEND", defaults="armstrong.core.arm_layout.backends.BasicRenderModelBackend") .get_backend()) # Here for backwards compatibility (deprecated) get_layout_template_name = render_model.get_layout_template_name ## Instruction: Throw deprecation warnings for these imports, which will be removed in the next version. They've been deprecated for two years so we can make it happen. ## Code After: import warnings from armstrong.utils.backends import GenericBackend render_model = (GenericBackend("ARMSTRONG_RENDER_MODEL_BACKEND", defaults="armstrong.core.arm_layout.backends.BasicRenderModelBackend") .get_backend()) # DEPRECATED: To be removed in ArmLayout 1.4. Here for backwards compatibility from django.utils.safestring import mark_safe from django.template.loader import render_to_string def deprecate(func): def wrapper(*args, **kwargs): msg = "Importing `{}` from this module is deprecated and will be removed in ArmLayout 1.4" warnings.warn(msg.format(func.__name__), DeprecationWarning) return func(*args, **kwargs) return wrapper mark_safe = deprecate(mark_safe) render_to_string = deprecate(render_to_string) get_layout_template_name = deprecate(render_model.get_layout_template_name)
# ... existing code ... import warnings from armstrong.utils.backends import GenericBackend # ... modified code ... # DEPRECATED: To be removed in ArmLayout 1.4. Here for backwards compatibility from django.utils.safestring import mark_safe from django.template.loader import render_to_string def deprecate(func): def wrapper(*args, **kwargs): msg = "Importing `{}` from this module is deprecated and will be removed in ArmLayout 1.4" warnings.warn(msg.format(func.__name__), DeprecationWarning) return func(*args, **kwargs) return wrapper mark_safe = deprecate(mark_safe) render_to_string = deprecate(render_to_string) get_layout_template_name = deprecate(render_model.get_layout_template_name) # ... rest of the code ...
83042027fe74ffe200d0bdaa79b0529af54ae6dc
addons/website/__openerp__.py
addons/website/__openerp__.py
{ 'name': 'Website Builder', 'category': 'Website', 'sequence': 50, 'summary': 'Build Your Enterprise Website', 'website': 'https://www.odoo.com/page/website-builder', 'version': '1.0', 'description': """ Odoo Website CMS =================== """, 'depends': ['base_setup', 'web', 'web_editor', 'web_planner'], 'installable': True, 'data': [ 'data/website_data.xml', 'data/web_planner_data.xml', 'security/ir.model.access.csv', 'security/website_security.xml', 'views/website_templates.xml', 'views/website_navbar_templates.xml', 'views/snippets.xml', 'views/website_views.xml', 'views/res_config_views.xml', 'views/ir_actions_views.xml', 'wizard/base_language_install_views.xml', ], 'demo': [ 'data/website_demo.xml', ], 'qweb': ['static/src/xml/website.backend.xml'], 'application': True, }
{ 'name': 'Website Builder', 'category': 'Website', 'sequence': 50, 'summary': 'Build Your Enterprise Website', 'website': 'https://www.odoo.com/page/website-builder', 'version': '1.0', 'description': """ Odoo Website CMS =================== """, 'depends': ['web', 'web_editor', 'web_planner'], 'installable': True, 'data': [ 'data/website_data.xml', 'data/web_planner_data.xml', 'security/ir.model.access.csv', 'security/website_security.xml', 'views/website_templates.xml', 'views/website_navbar_templates.xml', 'views/snippets.xml', 'views/website_views.xml', 'views/res_config_views.xml', 'views/ir_actions_views.xml', 'wizard/base_language_install_views.xml', ], 'demo': [ 'data/website_demo.xml', ], 'qweb': ['static/src/xml/website.backend.xml'], 'application': True, }
Revert "[FIX] website: add missing module dependency `base_setup`"
Revert "[FIX] website: add missing module dependency `base_setup`" This reverts commit d269eb0eb62d88e02c4fa33b84178d0e73d82ef1. The issue has been fixed in 61f2c90d507645492e1904c1005e8da6253788ea.
Python
agpl-3.0
ygol/odoo,dfang/odoo,hip-odoo/odoo,hip-odoo/odoo,ygol/odoo,ygol/odoo,dfang/odoo,dfang/odoo,ygol/odoo,hip-odoo/odoo,hip-odoo/odoo,ygol/odoo,ygol/odoo,ygol/odoo,dfang/odoo,hip-odoo/odoo,hip-odoo/odoo,dfang/odoo,dfang/odoo
{ 'name': 'Website Builder', 'category': 'Website', 'sequence': 50, 'summary': 'Build Your Enterprise Website', 'website': 'https://www.odoo.com/page/website-builder', 'version': '1.0', 'description': """ Odoo Website CMS =================== """, - 'depends': ['base_setup', 'web', 'web_editor', 'web_planner'], + 'depends': ['web', 'web_editor', 'web_planner'], 'installable': True, 'data': [ 'data/website_data.xml', 'data/web_planner_data.xml', 'security/ir.model.access.csv', 'security/website_security.xml', 'views/website_templates.xml', 'views/website_navbar_templates.xml', 'views/snippets.xml', 'views/website_views.xml', 'views/res_config_views.xml', 'views/ir_actions_views.xml', 'wizard/base_language_install_views.xml', ], 'demo': [ 'data/website_demo.xml', ], 'qweb': ['static/src/xml/website.backend.xml'], 'application': True, }
Revert "[FIX] website: add missing module dependency `base_setup`"
## Code Before: { 'name': 'Website Builder', 'category': 'Website', 'sequence': 50, 'summary': 'Build Your Enterprise Website', 'website': 'https://www.odoo.com/page/website-builder', 'version': '1.0', 'description': """ Odoo Website CMS =================== """, 'depends': ['base_setup', 'web', 'web_editor', 'web_planner'], 'installable': True, 'data': [ 'data/website_data.xml', 'data/web_planner_data.xml', 'security/ir.model.access.csv', 'security/website_security.xml', 'views/website_templates.xml', 'views/website_navbar_templates.xml', 'views/snippets.xml', 'views/website_views.xml', 'views/res_config_views.xml', 'views/ir_actions_views.xml', 'wizard/base_language_install_views.xml', ], 'demo': [ 'data/website_demo.xml', ], 'qweb': ['static/src/xml/website.backend.xml'], 'application': True, } ## Instruction: Revert "[FIX] website: add missing module dependency `base_setup`" ## Code After: { 'name': 'Website Builder', 'category': 'Website', 'sequence': 50, 'summary': 'Build Your Enterprise Website', 'website': 'https://www.odoo.com/page/website-builder', 'version': '1.0', 'description': """ Odoo Website CMS =================== """, 'depends': ['web', 'web_editor', 'web_planner'], 'installable': True, 'data': [ 'data/website_data.xml', 'data/web_planner_data.xml', 'security/ir.model.access.csv', 'security/website_security.xml', 'views/website_templates.xml', 'views/website_navbar_templates.xml', 'views/snippets.xml', 'views/website_views.xml', 'views/res_config_views.xml', 'views/ir_actions_views.xml', 'wizard/base_language_install_views.xml', ], 'demo': [ 'data/website_demo.xml', ], 'qweb': ['static/src/xml/website.backend.xml'], 'application': True, }
// ... existing code ... """, 'depends': ['web', 'web_editor', 'web_planner'], 'installable': True, // ... rest of the code ...
97d1dd6b14cff5196ccd2e2efad8a0aba5bf240b
tests/test_money.py
tests/test_money.py
from decimal import Decimal from django.test import TestCase from shop.money.money_maker import AbstractMoney, MoneyMaker class AbstractMoneyTest(TestCase): def test_is_abstract(self): self.assertRaises(TypeError, lambda: AbstractMoney(1)) class MoneyMakerTest(TestCase): def test_create_new_money_type_without_argumens(self): Money = MoneyMaker() money = Money() self.assertTrue(money.is_nan()) def test_wrong_currency_raises_assertion_error(self): # If we try to call a money class with a value that has a # different currency than the class, there should be an # AssertionError. Money = MoneyMaker(currency_code='EUR') value = Money() value._currency_code = 'USD' self.assertRaises(AssertionError, lambda: Money(value)) def test_create_instance_from_decimal(self): Money = MoneyMaker() value = Decimal("1.2") inst = Money(value) self.assertEquals(inst, value)
from __future__ import unicode_literals from decimal import Decimal from django.test import TestCase from shop.money.money_maker import AbstractMoney, MoneyMaker class AbstractMoneyTest(TestCase): def test_is_abstract(self): self.assertRaises(TypeError, lambda: AbstractMoney(1)) class MoneyMakerTest(TestCase): def test_create_new_money_type_without_argumens(self): Money = MoneyMaker() money = Money() self.assertTrue(money.is_nan()) def test_wrong_currency_raises_assertion_error(self): # If we try to call a money class with a value that has a # different currency than the class, and the value is an # instance of the money class, there should be an # AssertionError. Money = MoneyMaker(currency_code='EUR') value = Money() value._currency_code = 'USD' self.assertRaises(AssertionError, lambda: Money(value)) def test_create_instance_from_decimal(self): Money = MoneyMaker() value = Decimal("1.2") inst = Money(value) self.assertEquals(inst, value) def test_unicode(self): Money = MoneyMaker() value = Money(1) self.assertEqual(unicode(value), "€ 1.00")
Add a test for AbstractMoney.__unicode__
Add a test for AbstractMoney.__unicode__
Python
bsd-3-clause
nimbis/django-shop,jrief/django-shop,awesto/django-shop,rfleschenberg/django-shop,jrief/django-shop,nimbis/django-shop,jrief/django-shop,awesto/django-shop,khchine5/django-shop,rfleschenberg/django-shop,jrief/django-shop,divio/django-shop,divio/django-shop,rfleschenberg/django-shop,nimbis/django-shop,khchine5/django-shop,khchine5/django-shop,awesto/django-shop,rfleschenberg/django-shop,divio/django-shop,khchine5/django-shop,nimbis/django-shop
+ from __future__ import unicode_literals + from decimal import Decimal from django.test import TestCase from shop.money.money_maker import AbstractMoney, MoneyMaker class AbstractMoneyTest(TestCase): def test_is_abstract(self): self.assertRaises(TypeError, lambda: AbstractMoney(1)) class MoneyMakerTest(TestCase): def test_create_new_money_type_without_argumens(self): Money = MoneyMaker() money = Money() self.assertTrue(money.is_nan()) def test_wrong_currency_raises_assertion_error(self): # If we try to call a money class with a value that has a - # different currency than the class, there should be an + # different currency than the class, and the value is an + # instance of the money class, there should be an # AssertionError. Money = MoneyMaker(currency_code='EUR') value = Money() value._currency_code = 'USD' self.assertRaises(AssertionError, lambda: Money(value)) def test_create_instance_from_decimal(self): Money = MoneyMaker() value = Decimal("1.2") inst = Money(value) self.assertEquals(inst, value) + def test_unicode(self): + Money = MoneyMaker() + value = Money(1) + self.assertEqual(unicode(value), "€ 1.00") +
Add a test for AbstractMoney.__unicode__
## Code Before: from decimal import Decimal from django.test import TestCase from shop.money.money_maker import AbstractMoney, MoneyMaker class AbstractMoneyTest(TestCase): def test_is_abstract(self): self.assertRaises(TypeError, lambda: AbstractMoney(1)) class MoneyMakerTest(TestCase): def test_create_new_money_type_without_argumens(self): Money = MoneyMaker() money = Money() self.assertTrue(money.is_nan()) def test_wrong_currency_raises_assertion_error(self): # If we try to call a money class with a value that has a # different currency than the class, there should be an # AssertionError. Money = MoneyMaker(currency_code='EUR') value = Money() value._currency_code = 'USD' self.assertRaises(AssertionError, lambda: Money(value)) def test_create_instance_from_decimal(self): Money = MoneyMaker() value = Decimal("1.2") inst = Money(value) self.assertEquals(inst, value) ## Instruction: Add a test for AbstractMoney.__unicode__ ## Code After: from __future__ import unicode_literals from decimal import Decimal from django.test import TestCase from shop.money.money_maker import AbstractMoney, MoneyMaker class AbstractMoneyTest(TestCase): def test_is_abstract(self): self.assertRaises(TypeError, lambda: AbstractMoney(1)) class MoneyMakerTest(TestCase): def test_create_new_money_type_without_argumens(self): Money = MoneyMaker() money = Money() self.assertTrue(money.is_nan()) def test_wrong_currency_raises_assertion_error(self): # If we try to call a money class with a value that has a # different currency than the class, and the value is an # instance of the money class, there should be an # AssertionError. Money = MoneyMaker(currency_code='EUR') value = Money() value._currency_code = 'USD' self.assertRaises(AssertionError, lambda: Money(value)) def test_create_instance_from_decimal(self): Money = MoneyMaker() value = Decimal("1.2") inst = Money(value) self.assertEquals(inst, value) def test_unicode(self): Money = MoneyMaker() value = Money(1) self.assertEqual(unicode(value), "€ 1.00")
... from __future__ import unicode_literals from decimal import Decimal ... # If we try to call a money class with a value that has a # different currency than the class, and the value is an # instance of the money class, there should be an # AssertionError. ... self.assertEquals(inst, value) def test_unicode(self): Money = MoneyMaker() value = Money(1) self.assertEqual(unicode(value), "€ 1.00") ...
4ca6d139139a08151f7cdf89993ded3440287a4a
keyform/urls.py
keyform/urls.py
from django.conf.urls import url, include from django.contrib import admin from django.contrib.auth.views import login, logout_then_login from keyform import views urlpatterns = [ url(r'^$', views.HomeView.as_view(), name='home'), url(r'^contact$', views.ContactView.as_view(), name='contact'), url(r'^edit-contact/(?P<pk>\d+)$', views.EditContactView.as_view(), name='edit-contact'), url(r'^create-contact$', views.NewContactView.as_view(), name='create-contact'), url(r'^edit-request/(?P<pk>\d+)$', views.RequestView.as_view(), name='edit-request'), url(r'^create$', views.KeyRequest.as_view(), name='create'), url(r'^add-comment$', views.RequestCommentView.as_view(), name='add-comment'), url(r'^login$', login, name='login', kwargs={'template_name': 'keyform/login.html'}), url(r'^logout$', logout_then_login, name='logout'), ]
from django.conf.urls import url, include from django.contrib import admin from django.views.generic import RedirectView from django.contrib.auth.views import login, logout_then_login from keyform import views urlpatterns = [ url(r'^$', views.HomeView.as_view(), name='home'), url(r'^table.php$', RedirectView.as_view(pattern_name='home', permanent=True)), url(r'^contact$', views.ContactView.as_view(), name='contact'), url(r'^edit-contact/(?P<pk>\d+)$', views.EditContactView.as_view(), name='edit-contact'), url(r'^create-contact$', views.NewContactView.as_view(), name='create-contact'), url(r'^edit-request/(?P<pk>\d+)$', views.RequestView.as_view(), name='edit-request'), url(r'^create$', views.KeyRequest.as_view(), name='create'), url(r'^add-comment$', views.RequestCommentView.as_view(), name='add-comment'), url(r'^login$', login, name='login', kwargs={'template_name': 'keyform/login.html'}), url(r'^logout$', logout_then_login, name='logout'), ]
Add redirect for old hotlinks
Add redirect for old hotlinks
Python
mit
mostateresnet/keyformproject,mostateresnet/keyformproject,mostateresnet/keyformproject
from django.conf.urls import url, include from django.contrib import admin + from django.views.generic import RedirectView from django.contrib.auth.views import login, logout_then_login from keyform import views urlpatterns = [ url(r'^$', views.HomeView.as_view(), name='home'), + url(r'^table.php$', RedirectView.as_view(pattern_name='home', permanent=True)), url(r'^contact$', views.ContactView.as_view(), name='contact'), url(r'^edit-contact/(?P<pk>\d+)$', views.EditContactView.as_view(), name='edit-contact'), url(r'^create-contact$', views.NewContactView.as_view(), name='create-contact'), url(r'^edit-request/(?P<pk>\d+)$', views.RequestView.as_view(), name='edit-request'), url(r'^create$', views.KeyRequest.as_view(), name='create'), url(r'^add-comment$', views.RequestCommentView.as_view(), name='add-comment'), url(r'^login$', login, name='login', kwargs={'template_name': 'keyform/login.html'}), url(r'^logout$', logout_then_login, name='logout'), ]
Add redirect for old hotlinks
## Code Before: from django.conf.urls import url, include from django.contrib import admin from django.contrib.auth.views import login, logout_then_login from keyform import views urlpatterns = [ url(r'^$', views.HomeView.as_view(), name='home'), url(r'^contact$', views.ContactView.as_view(), name='contact'), url(r'^edit-contact/(?P<pk>\d+)$', views.EditContactView.as_view(), name='edit-contact'), url(r'^create-contact$', views.NewContactView.as_view(), name='create-contact'), url(r'^edit-request/(?P<pk>\d+)$', views.RequestView.as_view(), name='edit-request'), url(r'^create$', views.KeyRequest.as_view(), name='create'), url(r'^add-comment$', views.RequestCommentView.as_view(), name='add-comment'), url(r'^login$', login, name='login', kwargs={'template_name': 'keyform/login.html'}), url(r'^logout$', logout_then_login, name='logout'), ] ## Instruction: Add redirect for old hotlinks ## Code After: from django.conf.urls import url, include from django.contrib import admin from django.views.generic import RedirectView from django.contrib.auth.views import login, logout_then_login from keyform import views urlpatterns = [ url(r'^$', views.HomeView.as_view(), name='home'), url(r'^table.php$', RedirectView.as_view(pattern_name='home', permanent=True)), url(r'^contact$', views.ContactView.as_view(), name='contact'), url(r'^edit-contact/(?P<pk>\d+)$', views.EditContactView.as_view(), name='edit-contact'), url(r'^create-contact$', views.NewContactView.as_view(), name='create-contact'), url(r'^edit-request/(?P<pk>\d+)$', views.RequestView.as_view(), name='edit-request'), url(r'^create$', views.KeyRequest.as_view(), name='create'), url(r'^add-comment$', views.RequestCommentView.as_view(), name='add-comment'), url(r'^login$', login, name='login', kwargs={'template_name': 'keyform/login.html'}), url(r'^logout$', logout_then_login, name='logout'), ]
... from django.contrib import admin from django.views.generic import RedirectView from django.contrib.auth.views import login, logout_then_login ... url(r'^$', views.HomeView.as_view(), name='home'), url(r'^table.php$', RedirectView.as_view(pattern_name='home', permanent=True)), url(r'^contact$', views.ContactView.as_view(), name='contact'), ...
7350422a1364f996b7ac362e8457e2a5e04afc7c
sympy/interactive/tests/test_ipythonprinting.py
sympy/interactive/tests/test_ipythonprinting.py
"""Tests that the IPython printing module is properly loaded. """ from sympy.interactive.session import init_ipython_session from sympy.external import import_module ipython = import_module("IPython", min_module_version="0.11") # disable tests if ipython is not present if not ipython: disabled = True def test_ipythonprinting(): # Initialize and setup IPython session app = init_ipython_session() app.run_cell("from IPython.core.interactiveshell import InteractiveShell") app.run_cell("inst = InteractiveShell.instance()") app.run_cell("format = inst.display_formatter.format") app.run_cell("from sympy import Symbol") # Printing without printing extension app.run_cell("a = format(Symbol('pi'))") assert app.user_ns['a']['text/plain'] == "pi" # Load printing extension app.run_cell("%load_ext sympy.interactive.ipythonprinting") # Printing with printing extension app.run_cell("a = format(Symbol('pi'))") assert app.user_ns['a']['text/plain'] == u'\u03c0'
"""Tests that the IPython printing module is properly loaded. """ from sympy.interactive.session import init_ipython_session from sympy.external import import_module ipython = import_module("IPython", min_module_version="0.11") # disable tests if ipython is not present if not ipython: disabled = True def test_ipythonprinting(): # Initialize and setup IPython session app = init_ipython_session() app.run_cell("ip = get_ipython()") app.run_cell("inst = ip.instance()") app.run_cell("format = inst.display_formatter.format") app.run_cell("from sympy import Symbol") # Printing without printing extension app.run_cell("a = format(Symbol('pi'))") assert app.user_ns['a']['text/plain'] == "pi" # Load printing extension app.run_cell("%load_ext sympy.interactive.ipythonprinting") # Printing with printing extension app.run_cell("a = format(Symbol('pi'))") assert app.user_ns['a']['text/plain'] == u'\u03c0'
Make ipythonprinting test more robust
Make ipythonprinting test more robust
Python
bsd-3-clause
Vishluck/sympy,Mitchkoens/sympy,Davidjohnwilson/sympy,pandeyadarsh/sympy,hrashk/sympy,Davidjohnwilson/sympy,sahmed95/sympy,yukoba/sympy,Sumith1896/sympy,jamesblunt/sympy,moble/sympy,chaffra/sympy,Mitchkoens/sympy,Shaswat27/sympy,saurabhjn76/sympy,abhiii5459/sympy,jerli/sympy,jaimahajan1997/sympy,ahhda/sympy,sunny94/temp,wanglongqi/sympy,meghana1995/sympy,jaimahajan1997/sympy,lindsayad/sympy,Sumith1896/sympy,atsao72/sympy,sampadsaha5/sympy,atreyv/sympy,kaichogami/sympy,Curious72/sympy,kumarkrishna/sympy,Designist/sympy,abhiii5459/sympy,mafiya69/sympy,lidavidm/sympy,meghana1995/sympy,maniteja123/sympy,amitjamadagni/sympy,Titan-C/sympy,yashsharan/sympy,debugger22/sympy,skidzo/sympy,ga7g08/sympy,ga7g08/sympy,liangjiaxing/sympy,skidzo/sympy,cswiercz/sympy,beni55/sympy,liangjiaxing/sympy,Curious72/sympy,MechCoder/sympy,cccfran/sympy,Designist/sympy,cswiercz/sympy,skidzo/sympy,kumarkrishna/sympy,Gadal/sympy,cswiercz/sympy,emon10005/sympy,ahhda/sympy,AkademieOlympia/sympy,mcdaniel67/sympy,ChristinaZografou/sympy,drufat/sympy,rahuldan/sympy,toolforger/sympy,Davidjohnwilson/sympy,rahuldan/sympy,wanglongqi/sympy,souravsingh/sympy,AkademieOlympia/sympy,MechCoder/sympy,kaushik94/sympy,kevalds51/sympy,AunShiLord/sympy,sampadsaha5/sympy,wyom/sympy,asm666/sympy,jbbskinny/sympy,kumarkrishna/sympy,shikil/sympy,sunny94/temp,dqnykamp/sympy,lidavidm/sympy,madan96/sympy,ahhda/sympy,AunShiLord/sympy,bukzor/sympy,saurabhjn76/sympy,MridulS/sympy,vipulroxx/sympy,shipci/sympy,Vishluck/sympy,Vishluck/sympy,ChristinaZografou/sympy,jamesblunt/sympy,hrashk/sympy,jerli/sympy,abloomston/sympy,oliverlee/sympy,Sumith1896/sympy,emon10005/sympy,farhaanbukhsh/sympy,sunny94/temp,abloomston/sympy,moble/sympy,madan96/sympy,grevutiu-gabriel/sympy,AunShiLord/sympy,cccfran/sympy,oliverlee/sympy,kevalds51/sympy,iamutkarshtiwari/sympy,shipci/sympy,souravsingh/sympy,farhaanbukhsh/sympy,vipulroxx/sympy,Gadal/sympy,hrashk/sympy,maniteja123/sympy,sahmed95/sympy,kmacinnis/sympy,jbbskinny/sympy,Titan-C/sympy,cccfran/sympy,VaibhavAgarwalVA/sympy,asm666/sympy,rahuldan/sympy,postvakje/sympy,emon10005/sympy,diofant/diofant,yukoba/sympy,aktech/sympy,sahilshekhawat/sympy,drufat/sympy,pandeyadarsh/sympy,MechCoder/sympy,Designist/sympy,MridulS/sympy,aktech/sympy,grevutiu-gabriel/sympy,garvitr/sympy,meghana1995/sympy,Gadal/sympy,moble/sympy,Curious72/sympy,jamesblunt/sympy,kmacinnis/sympy,lindsayad/sympy,postvakje/sympy,atsao72/sympy,iamutkarshtiwari/sympy,debugger22/sympy,toolforger/sympy,hargup/sympy,hargup/sympy,amitjamadagni/sympy,ga7g08/sympy,atreyv/sympy,Shaswat27/sympy,hargup/sympy,Arafatk/sympy,mcdaniel67/sympy,skirpichev/omg,pbrady/sympy,jerli/sympy,Mitchkoens/sympy,liangjiaxing/sympy,dqnykamp/sympy,sahilshekhawat/sympy,beni55/sympy,mafiya69/sympy,MridulS/sympy,Shaswat27/sympy,Arafatk/sympy,souravsingh/sympy,dqnykamp/sympy,jaimahajan1997/sympy,oliverlee/sympy,shipci/sympy,lindsayad/sympy,kaushik94/sympy,abloomston/sympy,atsao72/sympy,wanglongqi/sympy,kaushik94/sympy,toolforger/sympy,shikil/sympy,postvakje/sympy,Arafatk/sympy,VaibhavAgarwalVA/sympy,yukoba/sympy,maniteja123/sympy,beni55/sympy,yashsharan/sympy,mcdaniel67/sympy,pbrady/sympy,yashsharan/sympy,VaibhavAgarwalVA/sympy,farhaanbukhsh/sympy,wyom/sympy,jbbskinny/sympy,vipulroxx/sympy,lidavidm/sympy,iamutkarshtiwari/sympy,atreyv/sympy,garvitr/sympy,bukzor/sympy,kaichogami/sympy,AkademieOlympia/sympy,bukzor/sympy,chaffra/sympy,asm666/sympy,garvitr/sympy,grevutiu-gabriel/sympy,Titan-C/sympy,kmacinnis/sympy,aktech/sympy,madan96/sympy,abhiii5459/sympy,chaffra/sympy,drufat/sympy,saurabhjn76/sympy,pbrady/sympy,sampadsaha5/sympy,wyom/sympy,shikil/sympy,ChristinaZografou/sympy,pandeyadarsh/sympy,debugger22/sympy,kaichogami/sympy,sahmed95/sympy,kevalds51/sympy,sahilshekhawat/sympy,mafiya69/sympy
"""Tests that the IPython printing module is properly loaded. """ from sympy.interactive.session import init_ipython_session from sympy.external import import_module ipython = import_module("IPython", min_module_version="0.11") # disable tests if ipython is not present if not ipython: disabled = True def test_ipythonprinting(): # Initialize and setup IPython session app = init_ipython_session() - app.run_cell("from IPython.core.interactiveshell import InteractiveShell") + app.run_cell("ip = get_ipython()") - app.run_cell("inst = InteractiveShell.instance()") + app.run_cell("inst = ip.instance()") app.run_cell("format = inst.display_formatter.format") app.run_cell("from sympy import Symbol") # Printing without printing extension app.run_cell("a = format(Symbol('pi'))") assert app.user_ns['a']['text/plain'] == "pi" # Load printing extension app.run_cell("%load_ext sympy.interactive.ipythonprinting") # Printing with printing extension app.run_cell("a = format(Symbol('pi'))") assert app.user_ns['a']['text/plain'] == u'\u03c0'
Make ipythonprinting test more robust
## Code Before: """Tests that the IPython printing module is properly loaded. """ from sympy.interactive.session import init_ipython_session from sympy.external import import_module ipython = import_module("IPython", min_module_version="0.11") # disable tests if ipython is not present if not ipython: disabled = True def test_ipythonprinting(): # Initialize and setup IPython session app = init_ipython_session() app.run_cell("from IPython.core.interactiveshell import InteractiveShell") app.run_cell("inst = InteractiveShell.instance()") app.run_cell("format = inst.display_formatter.format") app.run_cell("from sympy import Symbol") # Printing without printing extension app.run_cell("a = format(Symbol('pi'))") assert app.user_ns['a']['text/plain'] == "pi" # Load printing extension app.run_cell("%load_ext sympy.interactive.ipythonprinting") # Printing with printing extension app.run_cell("a = format(Symbol('pi'))") assert app.user_ns['a']['text/plain'] == u'\u03c0' ## Instruction: Make ipythonprinting test more robust ## Code After: """Tests that the IPython printing module is properly loaded. """ from sympy.interactive.session import init_ipython_session from sympy.external import import_module ipython = import_module("IPython", min_module_version="0.11") # disable tests if ipython is not present if not ipython: disabled = True def test_ipythonprinting(): # Initialize and setup IPython session app = init_ipython_session() app.run_cell("ip = get_ipython()") app.run_cell("inst = ip.instance()") app.run_cell("format = inst.display_formatter.format") app.run_cell("from sympy import Symbol") # Printing without printing extension app.run_cell("a = format(Symbol('pi'))") assert app.user_ns['a']['text/plain'] == "pi" # Load printing extension app.run_cell("%load_ext sympy.interactive.ipythonprinting") # Printing with printing extension app.run_cell("a = format(Symbol('pi'))") assert app.user_ns['a']['text/plain'] == u'\u03c0'
// ... existing code ... app = init_ipython_session() app.run_cell("ip = get_ipython()") app.run_cell("inst = ip.instance()") app.run_cell("format = inst.display_formatter.format") // ... rest of the code ...
52610add5ae887dcbc06f1435fdff34f182d78c9
go/campaigns/forms.py
go/campaigns/forms.py
from django import forms class CampaignGeneralForm(forms.Form): TYPE_CHOICES = ( ('', 'Select campaign type'), ('B', 'Bulk Message'), ('C', 'Conversation'), ) name = forms.CharField(label="Campaign name", max_length=100) type = forms.ChoiceField(label="Which kind of campaign would you like?", widget=forms.Select(), choices=TYPE_CHOICES) class CampaignConfigurationForm(forms.Form): COUNTRY_CHOICES = ( ('.za', 'South Africa'), ) CHANNEL_CHOICES = ( ('ussd', 'USSD'), ) # more than likely a many to many field, or something similair in the riak # world. Whom I kidding, this is probably just a modelform? countries = forms.MultipleChoiceField(label="Destinations", widget=forms.Select(), choices=COUNTRY_CHOICES) channels = forms.MultipleChoiceField(label="Channels", widget=forms.Select(), choices=CHANNEL_CHOICES) keyword = forms.CharField(label="Keyword", max_length=100) class CampaignBulkMessageForm(forms.Form): message = forms.CharField(label="Bulk message text", widget=forms.Textarea)
from django import forms class CampaignGeneralForm(forms.Form): TYPE_CHOICES = ( ('', 'Select campaign type'), ('B', 'Bulk Message'), ('D', 'Dialogue'), ) name = forms.CharField(label="Campaign name", max_length=100) type = forms.ChoiceField(label="Which kind of campaign would you like?", widget=forms.Select(), choices=TYPE_CHOICES) class CampaignConfigurationForm(forms.Form): COUNTRY_CHOICES = ( ('.za', 'South Africa'), ) CHANNEL_CHOICES = ( ('ussd', 'USSD'), ) # more than likely a many to many field, or something similair in the riak # world. Whom I kidding, this is probably just a modelform? countries = forms.MultipleChoiceField(label="Destinations", widget=forms.Select(), choices=COUNTRY_CHOICES) channels = forms.MultipleChoiceField(label="Channels", widget=forms.Select(), choices=CHANNEL_CHOICES) keyword = forms.CharField(label="Keyword", max_length=100) class CampaignBulkMessageForm(forms.Form): message = forms.CharField(label="Bulk message text", widget=forms.Textarea)
Use dialogue terminology in menu
Use dialogue terminology in menu
Python
bsd-3-clause
praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go
from django import forms class CampaignGeneralForm(forms.Form): TYPE_CHOICES = ( ('', 'Select campaign type'), ('B', 'Bulk Message'), - ('C', 'Conversation'), + ('D', 'Dialogue'), ) name = forms.CharField(label="Campaign name", max_length=100) type = forms.ChoiceField(label="Which kind of campaign would you like?", widget=forms.Select(), choices=TYPE_CHOICES) class CampaignConfigurationForm(forms.Form): COUNTRY_CHOICES = ( ('.za', 'South Africa'), ) CHANNEL_CHOICES = ( ('ussd', 'USSD'), ) # more than likely a many to many field, or something similair in the riak # world. Whom I kidding, this is probably just a modelform? countries = forms.MultipleChoiceField(label="Destinations", widget=forms.Select(), choices=COUNTRY_CHOICES) channels = forms.MultipleChoiceField(label="Channels", widget=forms.Select(), choices=CHANNEL_CHOICES) keyword = forms.CharField(label="Keyword", max_length=100) class CampaignBulkMessageForm(forms.Form): message = forms.CharField(label="Bulk message text", widget=forms.Textarea)
Use dialogue terminology in menu
## Code Before: from django import forms class CampaignGeneralForm(forms.Form): TYPE_CHOICES = ( ('', 'Select campaign type'), ('B', 'Bulk Message'), ('C', 'Conversation'), ) name = forms.CharField(label="Campaign name", max_length=100) type = forms.ChoiceField(label="Which kind of campaign would you like?", widget=forms.Select(), choices=TYPE_CHOICES) class CampaignConfigurationForm(forms.Form): COUNTRY_CHOICES = ( ('.za', 'South Africa'), ) CHANNEL_CHOICES = ( ('ussd', 'USSD'), ) # more than likely a many to many field, or something similair in the riak # world. Whom I kidding, this is probably just a modelform? countries = forms.MultipleChoiceField(label="Destinations", widget=forms.Select(), choices=COUNTRY_CHOICES) channels = forms.MultipleChoiceField(label="Channels", widget=forms.Select(), choices=CHANNEL_CHOICES) keyword = forms.CharField(label="Keyword", max_length=100) class CampaignBulkMessageForm(forms.Form): message = forms.CharField(label="Bulk message text", widget=forms.Textarea) ## Instruction: Use dialogue terminology in menu ## Code After: from django import forms class CampaignGeneralForm(forms.Form): TYPE_CHOICES = ( ('', 'Select campaign type'), ('B', 'Bulk Message'), ('D', 'Dialogue'), ) name = forms.CharField(label="Campaign name", max_length=100) type = forms.ChoiceField(label="Which kind of campaign would you like?", widget=forms.Select(), choices=TYPE_CHOICES) class CampaignConfigurationForm(forms.Form): COUNTRY_CHOICES = ( ('.za', 'South Africa'), ) CHANNEL_CHOICES = ( ('ussd', 'USSD'), ) # more than likely a many to many field, or something similair in the riak # world. Whom I kidding, this is probably just a modelform? countries = forms.MultipleChoiceField(label="Destinations", widget=forms.Select(), choices=COUNTRY_CHOICES) channels = forms.MultipleChoiceField(label="Channels", widget=forms.Select(), choices=CHANNEL_CHOICES) keyword = forms.CharField(label="Keyword", max_length=100) class CampaignBulkMessageForm(forms.Form): message = forms.CharField(label="Bulk message text", widget=forms.Textarea)
// ... existing code ... ('B', 'Bulk Message'), ('D', 'Dialogue'), ) // ... rest of the code ...
44191360586beeec04a4abc8a4aa262bc5ec052d
odinweb/exceptions.py
odinweb/exceptions.py
from .constants import HTTPStatus from .resources import Error class ImmediateHttpResponse(Exception): """ A response that should be returned immediately. """ def __init__(self, resource, status=HTTPStatus.OK, headers=None): self.resource = resource self.status = status self.headers = headers class HttpError(ImmediateHttpResponse): """ An error response that should be returned immediately. """ def __init__(self, status, code, message, developer_message=None, meta=None, headers=None): super(HttpError, self).__init__( Error(status, code, message, developer_message, meta), status, headers ) class PermissionDenied(HttpError): """ Permission to access the specified resource is denied. """ def __init__(self, message=None, developer_method=None, headers=None): super(PermissionDenied, self).__init__( HTTPStatus.FORBIDDEN, 40300, message or HTTPStatus.FORBIDDEN.description, developer_method, None, headers )
from .constants import HTTPStatus from .resources import Error __all__ = ('ImmediateHttpResponse', 'HttpError', 'PermissionDenied') class ImmediateHttpResponse(Exception): """ A response that should be returned immediately. """ def __init__(self, resource, status=HTTPStatus.OK, headers=None): self.resource = resource self.status = status self.headers = headers class HttpError(ImmediateHttpResponse): """ An error response that should be returned immediately. """ def __init__(self, status, code_index=0, message=None, developer_message=None, meta=None, headers=None): super(HttpError, self).__init__( Error.from_status(status, code_index, message, developer_message, meta), status, headers ) class PermissionDenied(HttpError): """ Permission to access the specified resource is denied. """ def __init__(self, message=None, developer_method=None, headers=None): super(PermissionDenied, self).__init__(HTTPStatus.FORBIDDEN, 0, message, developer_method, None, headers)
Refactor HttpError to use Error.from_status helper
Refactor HttpError to use Error.from_status helper
Python
bsd-3-clause
python-odin/odinweb,python-odin/odinweb
from .constants import HTTPStatus from .resources import Error + + __all__ = ('ImmediateHttpResponse', 'HttpError', 'PermissionDenied') class ImmediateHttpResponse(Exception): """ A response that should be returned immediately. """ def __init__(self, resource, status=HTTPStatus.OK, headers=None): self.resource = resource self.status = status self.headers = headers class HttpError(ImmediateHttpResponse): """ An error response that should be returned immediately. """ - def __init__(self, status, code, message, developer_message=None, meta=None, headers=None): + def __init__(self, status, code_index=0, message=None, developer_message=None, meta=None, headers=None): super(HttpError, self).__init__( - Error(status, code, message, developer_message, meta), + Error.from_status(status, code_index, message, developer_message, meta), status, headers - status, headers ) class PermissionDenied(HttpError): """ Permission to access the specified resource is denied. """ def __init__(self, message=None, developer_method=None, headers=None): + super(PermissionDenied, self).__init__(HTTPStatus.FORBIDDEN, 0, message, developer_method, None, headers) - super(PermissionDenied, self).__init__( - HTTPStatus.FORBIDDEN, 40300, message or HTTPStatus.FORBIDDEN.description, - developer_method, None, headers - )
Refactor HttpError to use Error.from_status helper
## Code Before: from .constants import HTTPStatus from .resources import Error class ImmediateHttpResponse(Exception): """ A response that should be returned immediately. """ def __init__(self, resource, status=HTTPStatus.OK, headers=None): self.resource = resource self.status = status self.headers = headers class HttpError(ImmediateHttpResponse): """ An error response that should be returned immediately. """ def __init__(self, status, code, message, developer_message=None, meta=None, headers=None): super(HttpError, self).__init__( Error(status, code, message, developer_message, meta), status, headers ) class PermissionDenied(HttpError): """ Permission to access the specified resource is denied. """ def __init__(self, message=None, developer_method=None, headers=None): super(PermissionDenied, self).__init__( HTTPStatus.FORBIDDEN, 40300, message or HTTPStatus.FORBIDDEN.description, developer_method, None, headers ) ## Instruction: Refactor HttpError to use Error.from_status helper ## Code After: from .constants import HTTPStatus from .resources import Error __all__ = ('ImmediateHttpResponse', 'HttpError', 'PermissionDenied') class ImmediateHttpResponse(Exception): """ A response that should be returned immediately. """ def __init__(self, resource, status=HTTPStatus.OK, headers=None): self.resource = resource self.status = status self.headers = headers class HttpError(ImmediateHttpResponse): """ An error response that should be returned immediately. """ def __init__(self, status, code_index=0, message=None, developer_message=None, meta=None, headers=None): super(HttpError, self).__init__( Error.from_status(status, code_index, message, developer_message, meta), status, headers ) class PermissionDenied(HttpError): """ Permission to access the specified resource is denied. """ def __init__(self, message=None, developer_method=None, headers=None): super(PermissionDenied, self).__init__(HTTPStatus.FORBIDDEN, 0, message, developer_method, None, headers)
// ... existing code ... from .resources import Error __all__ = ('ImmediateHttpResponse', 'HttpError', 'PermissionDenied') // ... modified code ... """ def __init__(self, status, code_index=0, message=None, developer_message=None, meta=None, headers=None): super(HttpError, self).__init__( Error.from_status(status, code_index, message, developer_message, meta), status, headers ) ... def __init__(self, message=None, developer_method=None, headers=None): super(PermissionDenied, self).__init__(HTTPStatus.FORBIDDEN, 0, message, developer_method, None, headers) // ... rest of the code ...
9d65eaa14bc3f04ea998ed7bc43b7c71e5d232f7
v3/scripts/testing/create-8gb-metadata.py
v3/scripts/testing/create-8gb-metadata.py
__author__ = 'eric' ''' Need to create some test data '''
__author__ = 'eric' ''' Need to create some test data 8 gigabytes dataset '''
Test script for generating metadata
Test script for generating metadata
Python
mit
TheShellLand/pies,TheShellLand/pies
__author__ = 'eric' ''' Need to create some test data + 8 gigabytes dataset ''' +
Test script for generating metadata
## Code Before: __author__ = 'eric' ''' Need to create some test data ''' ## Instruction: Test script for generating metadata ## Code After: __author__ = 'eric' ''' Need to create some test data 8 gigabytes dataset '''
// ... existing code ... Need to create some test data 8 gigabytes dataset ''' // ... rest of the code ...
9883a1ac995816160a35fd66107a576289062123
apis/betterself/v1/events/views.py
apis/betterself/v1/events/views.py
from apis.betterself.v1.events.serializers import SupplementEventSerializer from apis.betterself.v1.utils.views import BaseGenericListCreateAPIViewV1 from events.models import SupplementEvent class SupplementEventView(BaseGenericListCreateAPIViewV1): serializer_class = SupplementEventSerializer model = SupplementEvent
from apis.betterself.v1.events.serializers import SupplementEventSerializer from apis.betterself.v1.utils.views import BaseGenericListCreateAPIViewV1 from events.models import SupplementEvent class SupplementEventView(BaseGenericListCreateAPIViewV1): serializer_class = SupplementEventSerializer model = SupplementEvent def get_queryset(self): name = self.request.query_params.get('name') if name: queryset = self.model.objects.filter(name__iexact=name) else: queryset = self.model.objects.all() return queryset
Add queryset, but debate if better options
Add queryset, but debate if better options
Python
mit
jeffshek/betterself,jeffshek/betterself,jeffshek/betterself,jeffshek/betterself
from apis.betterself.v1.events.serializers import SupplementEventSerializer from apis.betterself.v1.utils.views import BaseGenericListCreateAPIViewV1 from events.models import SupplementEvent class SupplementEventView(BaseGenericListCreateAPIViewV1): serializer_class = SupplementEventSerializer model = SupplementEvent + def get_queryset(self): + name = self.request.query_params.get('name') + if name: + queryset = self.model.objects.filter(name__iexact=name) + else: + queryset = self.model.objects.all() + + return queryset +
Add queryset, but debate if better options
## Code Before: from apis.betterself.v1.events.serializers import SupplementEventSerializer from apis.betterself.v1.utils.views import BaseGenericListCreateAPIViewV1 from events.models import SupplementEvent class SupplementEventView(BaseGenericListCreateAPIViewV1): serializer_class = SupplementEventSerializer model = SupplementEvent ## Instruction: Add queryset, but debate if better options ## Code After: from apis.betterself.v1.events.serializers import SupplementEventSerializer from apis.betterself.v1.utils.views import BaseGenericListCreateAPIViewV1 from events.models import SupplementEvent class SupplementEventView(BaseGenericListCreateAPIViewV1): serializer_class = SupplementEventSerializer model = SupplementEvent def get_queryset(self): name = self.request.query_params.get('name') if name: queryset = self.model.objects.filter(name__iexact=name) else: queryset = self.model.objects.all() return queryset
# ... existing code ... model = SupplementEvent def get_queryset(self): name = self.request.query_params.get('name') if name: queryset = self.model.objects.filter(name__iexact=name) else: queryset = self.model.objects.all() return queryset # ... rest of the code ...
57444bdd253e428174c7a5475ef205063ac95ef3
lms/djangoapps/heartbeat/views.py
lms/djangoapps/heartbeat/views.py
import json from datetime import datetime from django.http import HttpResponse def heartbeat(request): """ Simple view that a loadbalancer can check to verify that the app is up """ output = { 'date': datetime.now().isoformat() } return HttpResponse(json.dumps(output, indent=4))
import json from datetime import datetime from django.http import HttpResponse from xmodule.modulestore.django import modulestore def heartbeat(request): """ Simple view that a loadbalancer can check to verify that the app is up """ output = { 'date': datetime.now().isoformat(), 'courses': [course.location for course in modulestore().get_courses()], } return HttpResponse(json.dumps(output, indent=4))
Make heartbeat url wait for courses to be loaded
Make heartbeat url wait for courses to be loaded
Python
agpl-3.0
benpatterson/edx-platform,bigdatauniversity/edx-platform,Softmotions/edx-platform,shashank971/edx-platform,shabab12/edx-platform,ampax/edx-platform,mcgachey/edx-platform,yokose-ks/edx-platform,Livit/Livit.Learn.EdX,DefyVentures/edx-platform,pdehaye/theming-edx-platform,jruiperezv/ANALYSE,carsongee/edx-platform,jjmiranda/edx-platform,sudheerchintala/LearnEraPlatForm,olexiim/edx-platform,shubhdev/edx-platform,beacloudgenius/edx-platform,eestay/edx-platform,beacloudgenius/edx-platform,Edraak/edx-platform,torchingloom/edx-platform,EDUlib/edx-platform,IONISx/edx-platform,alu042/edx-platform,alexthered/kienhoc-platform,zhenzhai/edx-platform,jruiperezv/ANALYSE,dkarakats/edx-platform,inares/edx-platform,hmcmooc/muddx-platform,xingyepei/edx-platform,cyanna/edx-platform,hkawasaki/kawasaki-aio8-0,Stanford-Online/edx-platform,Kalyzee/edx-platform,playm2mboy/edx-platform,atsolakid/edx-platform,cognitiveclass/edx-platform,Livit/Livit.Learn.EdX,prarthitm/edxplatform,procangroup/edx-platform,angelapper/edx-platform,arbrandes/edx-platform,angelapper/edx-platform,Softmotions/edx-platform,itsjeyd/edx-platform,adoosii/edx-platform,mtlchun/edx,dsajkl/123,chauhanhardik/populo_2,benpatterson/edx-platform,mjirayu/sit_academy,kalebhartje/schoolboost,alu042/edx-platform,chrisndodge/edx-platform,DNFcode/edx-platform,analyseuc3m/ANALYSE-v1,CourseTalk/edx-platform,appliedx/edx-platform,dsajkl/123,mahendra-r/edx-platform,waheedahmed/edx-platform,antoviaque/edx-platform,Stanford-Online/edx-platform,dsajkl/reqiop,vasyarv/edx-platform,xingyepei/edx-platform,torchingloom/edx-platform,bigdatauniversity/edx-platform,cecep-edu/edx-platform,shabab12/edx-platform,MakeHer/edx-platform,rhndg/openedx,mtlchun/edx,zofuthan/edx-platform,shubhdev/edxOnBaadal,Semi-global/edx-platform,zhenzhai/edx-platform,Endika/edx-platform,eestay/edx-platform,nttks/edx-platform,shurihell/testasia,jbzdak/edx-platform,chand3040/cloud_that,ESOedX/edx-platform,LICEF/edx-platform,cpennington/edx-platform,hkawasaki/kawasaki-aio8-2,xinjiguaike/edx-platform,edx-solutions/edx-platform,sameetb-cuelogic/edx-platform-test,MSOpenTech/edx-platform,ak2703/edx-platform,nanolearningllc/edx-platform-cypress,devs1991/test_edx_docmode,ZLLab-Mooc/edx-platform,eduNEXT/edx-platform,waheedahmed/edx-platform,romain-li/edx-platform,vasyarv/edx-platform,PepperPD/edx-pepper-platform,Ayub-Khan/edx-platform,halvertoluke/edx-platform,mitocw/edx-platform,peterm-itr/edx-platform,nttks/jenkins-test,inares/edx-platform,hkawasaki/kawasaki-aio8-2,defance/edx-platform,chauhanhardik/populo_2,shubhdev/edxOnBaadal,kamalx/edx-platform,arbrandes/edx-platform,fintech-circle/edx-platform,polimediaupv/edx-platform,shubhdev/edx-platform,inares/edx-platform,shashank971/edx-platform,TeachAtTUM/edx-platform,kamalx/edx-platform,carsongee/edx-platform,IONISx/edx-platform,iivic/BoiseStateX,OmarIthawi/edx-platform,knehez/edx-platform,IITBinterns13/edx-platform-dev,beacloudgenius/edx-platform,dcosentino/edx-platform,eestay/edx-platform,procangroup/edx-platform,iivic/BoiseStateX,martynovp/edx-platform,jelugbo/tundex,appsembler/edx-platform,ahmedaljazzar/edx-platform,msegado/edx-platform,olexiim/edx-platform,torchingloom/edx-platform,dsajkl/reqiop,alexthered/kienhoc-platform,AkA84/edx-platform,edx/edx-platform,naresh21/synergetics-edx-platform,kmoocdev/edx-platform,adoosii/edx-platform,y12uc231/edx-platform,jbassen/edx-platform,jamesblunt/edx-platform,appliedx/edx-platform,pabloborrego93/edx-platform,dkarakats/edx-platform,chand3040/cloud_that,pabloborrego93/edx-platform,B-MOOC/edx-platform,apigee/edx-platform,jswope00/griffinx,waheedahmed/edx-platform,eemirtekin/edx-platform,gsehub/edx-platform,SivilTaram/edx-platform,UOMx/edx-platform,J861449197/edx-platform,mitocw/edx-platform,hkawasaki/kawasaki-aio8-2,MSOpenTech/edx-platform,y12uc231/edx-platform,arbrandes/edx-platform,Edraak/edraak-platform,chudaol/edx-platform,eemirtekin/edx-platform,motion2015/edx-platform,IndonesiaX/edx-platform,jswope00/griffinx,rationalAgent/edx-platform-custom,shubhdev/edxOnBaadal,xinjiguaike/edx-platform,jonathan-beard/edx-platform,TeachAtTUM/edx-platform,gymnasium/edx-platform,kxliugang/edx-platform,etzhou/edx-platform,tanmaykm/edx-platform,auferack08/edx-platform,andyzsf/edx,vismartltd/edx-platform,chand3040/cloud_that,nagyistoce/edx-platform,valtech-mooc/edx-platform,kursitet/edx-platform,Unow/edx-platform,morenopc/edx-platform,iivic/BoiseStateX,hamzehd/edx-platform,teltek/edx-platform,etzhou/edx-platform,longmen21/edx-platform,openfun/edx-platform,jjmiranda/edx-platform,marcore/edx-platform,philanthropy-u/edx-platform,SivilTaram/edx-platform,nagyistoce/edx-platform,benpatterson/edx-platform,martynovp/edx-platform,PepperPD/edx-pepper-platform,jbzdak/edx-platform,EDUlib/edx-platform,pomegranited/edx-platform,AkA84/edx-platform,caesar2164/edx-platform,ubc/edx-platform,pepeportela/edx-platform,auferack08/edx-platform,pku9104038/edx-platform,stvstnfrd/edx-platform,10clouds/edx-platform,EduPepperPDTesting/pepper2013-testing,ESOedX/edx-platform,jswope00/GAI,zofuthan/edx-platform,antonve/s4-project-mooc,ZLLab-Mooc/edx-platform,xuxiao19910803/edx,10clouds/edx-platform,chauhanhardik/populo,nagyistoce/edx-platform,bdero/edx-platform,EduPepperPD/pepper2013,mtlchun/edx,fintech-circle/edx-platform,kxliugang/edx-platform,unicri/edx-platform,alexthered/kienhoc-platform,arifsetiawan/edx-platform,kalebhartje/schoolboost,ovnicraft/edx-platform,Semi-global/edx-platform,beni55/edx-platform,deepsrijit1105/edx-platform,WatanabeYasumasa/edx-platform,franosincic/edx-platform,torchingloom/edx-platform,bdero/edx-platform,fintech-circle/edx-platform,jbassen/edx-platform,jzoldak/edx-platform,pomegranited/edx-platform,mahendra-r/edx-platform,angelapper/edx-platform,kursitet/edx-platform,ZLLab-Mooc/edx-platform,sameetb-cuelogic/edx-platform-test,morpheby/levelup-by,jamesblunt/edx-platform,y12uc231/edx-platform,shubhdev/edx-platform,yokose-ks/edx-platform,pdehaye/theming-edx-platform,morenopc/edx-platform,nanolearning/edx-platform,philanthropy-u/edx-platform,Kalyzee/edx-platform,dsajkl/reqiop,mtlchun/edx,JCBarahona/edX,motion2015/a3,rationalAgent/edx-platform-custom,Endika/edx-platform,zubair-arbi/edx-platform,caesar2164/edx-platform,eduNEXT/edx-platform,SravanthiSinha/edx-platform,kmoocdev2/edx-platform,franosincic/edx-platform,LearnEra/LearnEraPlaftform,antonve/s4-project-mooc,nanolearning/edx-platform,jbzdak/edx-platform,10clouds/edx-platform,wwj718/edx-platform,Kalyzee/edx-platform,jbassen/edx-platform,10clouds/edx-platform,sudheerchintala/LearnEraPlatForm,ahmadio/edx-platform,nanolearningllc/edx-platform-cypress,ampax/edx-platform-backup,CredoReference/edx-platform,4eek/edx-platform,chand3040/cloud_that,hkawasaki/kawasaki-aio8-1,iivic/BoiseStateX,don-github/edx-platform,cpennington/edx-platform,valtech-mooc/edx-platform,wwj718/edx-platform,polimediaupv/edx-platform,kamalx/edx-platform,xinjiguaike/edx-platform,rue89-tech/edx-platform,zerobatu/edx-platform,bitifirefly/edx-platform,shubhdev/openedx,lduarte1991/edx-platform,nanolearningllc/edx-platform-cypress-2,ahmedaljazzar/edx-platform,jazkarta/edx-platform-for-isc,vasyarv/edx-platform,syjeon/new_edx,nikolas/edx-platform,marcore/edx-platform,longmen21/edx-platform,a-parhom/edx-platform,ovnicraft/edx-platform,sameetb-cuelogic/edx-platform-test,cselis86/edx-platform,ovnicraft/edx-platform,nanolearning/edx-platform,shurihell/testasia,arifsetiawan/edx-platform,DefyVentures/edx-platform,nttks/edx-platform,EduPepperPD/pepper2013,louyihua/edx-platform,atsolakid/edx-platform,xingyepei/edx-platform,CourseTalk/edx-platform,ubc/edx-platform,jazztpt/edx-platform,shashank971/edx-platform,OmarIthawi/edx-platform,franosincic/edx-platform,raccoongang/edx-platform,jazkarta/edx-platform,kxliugang/edx-platform,MSOpenTech/edx-platform,nanolearningllc/edx-platform-cypress,msegado/edx-platform,Livit/Livit.Learn.EdX,hastexo/edx-platform,peterm-itr/edx-platform,ahmadio/edx-platform,nanolearningllc/edx-platform-cypress-2,amir-qayyum-khan/edx-platform,SivilTaram/edx-platform,mushtaqak/edx-platform,zadgroup/edx-platform,edx/edx-platform,pepeportela/edx-platform,ahmadiga/min_edx,fly19890211/edx-platform,jruiperezv/ANALYSE,kmoocdev/edx-platform,RPI-OPENEDX/edx-platform,WatanabeYasumasa/edx-platform,zadgroup/edx-platform,etzhou/edx-platform,jruiperezv/ANALYSE,shubhdev/edx-platform,openfun/edx-platform,cselis86/edx-platform,Edraak/circleci-edx-platform,abdoosh00/edx-rtl-final,eduNEXT/edx-platform,dkarakats/edx-platform,zubair-arbi/edx-platform,romain-li/edx-platform,iivic/BoiseStateX,gsehub/edx-platform,morpheby/levelup-by,nttks/jenkins-test,leansoft/edx-platform,antoviaque/edx-platform,Edraak/edraak-platform,unicri/edx-platform,jelugbo/tundex,edry/edx-platform,abdoosh00/edraak,Stanford-Online/edx-platform,itsjeyd/edx-platform,shubhdev/openedx,rismalrv/edx-platform,motion2015/edx-platform,yokose-ks/edx-platform,utecuy/edx-platform,ferabra/edx-platform,nikolas/edx-platform,romain-li/edx-platform,Edraak/edraak-platform,a-parhom/edx-platform,mahendra-r/edx-platform,amir-qayyum-khan/edx-platform,abdoosh00/edraak,jswope00/GAI,DNFcode/edx-platform,beni55/edx-platform,dcosentino/edx-platform,atsolakid/edx-platform,naresh21/synergetics-edx-platform,4eek/edx-platform,UOMx/edx-platform,xuxiao19910803/edx-platform,chauhanhardik/populo,longmen21/edx-platform,shubhdev/openedx,edx/edx-platform,pelikanchik/edx-platform,yokose-ks/edx-platform,SravanthiSinha/edx-platform,apigee/edx-platform,alu042/edx-platform,Lektorium-LLC/edx-platform,fly19890211/edx-platform,xuxiao19910803/edx,pelikanchik/edx-platform,carsongee/edx-platform,fintech-circle/edx-platform,jolyonb/edx-platform,Semi-global/edx-platform,apigee/edx-platform,mcgachey/edx-platform,jamesblunt/edx-platform,antonve/s4-project-mooc,doismellburning/edx-platform,Ayub-Khan/edx-platform,Edraak/circleci-edx-platform,xuxiao19910803/edx-platform,zofuthan/edx-platform,jzoldak/edx-platform,beacloudgenius/edx-platform,motion2015/edx-platform,appliedx/edx-platform,olexiim/edx-platform,a-parhom/edx-platform,cognitiveclass/edx-platform,olexiim/edx-platform,valtech-mooc/edx-platform,Livit/Livit.Learn.EdX,IndonesiaX/edx-platform,dkarakats/edx-platform,morpheby/levelup-by,dsajkl/123,martynovp/edx-platform,ampax/edx-platform-backup,tanmaykm/edx-platform,angelapper/edx-platform,jazkarta/edx-platform,SivilTaram/edx-platform,pelikanchik/edx-platform,IONISx/edx-platform,edx-solutions/edx-platform,J861449197/edx-platform,chrisndodge/edx-platform,Softmotions/edx-platform,openfun/edx-platform,zerobatu/edx-platform,atsolakid/edx-platform,atsolakid/edx-platform,mjirayu/sit_academy,rue89-tech/edx-platform,appliedx/edx-platform,ak2703/edx-platform,gsehub/edx-platform,ahmadiga/min_edx,don-github/edx-platform,shubhdev/edx-platform,Edraak/edx-platform,pku9104038/edx-platform,prarthitm/edxplatform,solashirai/edx-platform,mbareta/edx-platform-ft,xinjiguaike/edx-platform,BehavioralInsightsTeam/edx-platform,Softmotions/edx-platform,devs1991/test_edx_docmode,shabab12/edx-platform,TeachAtTUM/edx-platform,mjg2203/edx-platform-seas,peterm-itr/edx-platform,synergeticsedx/deployment-wipro,inares/edx-platform,lduarte1991/edx-platform,motion2015/a3,xuxiao19910803/edx-platform,Stanford-Online/edx-platform,doganov/edx-platform,appsembler/edx-platform,philanthropy-u/edx-platform,nanolearningllc/edx-platform-cypress-2,morenopc/edx-platform,carsongee/edx-platform,ferabra/edx-platform,andyzsf/edx,appsembler/edx-platform,Shrhawk/edx-platform,teltek/edx-platform,halvertoluke/edx-platform,eemirtekin/edx-platform,etzhou/edx-platform,tanmaykm/edx-platform,B-MOOC/edx-platform,xingyepei/edx-platform,beacloudgenius/edx-platform,jolyonb/edx-platform,jelugbo/tundex,mushtaqak/edx-platform,jazkarta/edx-platform,pku9104038/edx-platform,Edraak/edx-platform,ahmedaljazzar/edx-platform,appsembler/edx-platform,jswope00/griffinx,playm2mboy/edx-platform,ubc/edx-platform,kxliugang/edx-platform,y12uc231/edx-platform,JCBarahona/edX,RPI-OPENEDX/edx-platform,devs1991/test_edx_docmode,IITBinterns13/edx-platform-dev,adoosii/edx-platform,polimediaupv/edx-platform,UXE/local-edx,mahendra-r/edx-platform,SravanthiSinha/edx-platform,analyseuc3m/ANALYSE-v1,hmcmooc/muddx-platform,auferack08/edx-platform,jbzdak/edx-platform,kursitet/edx-platform,Endika/edx-platform,rismalrv/edx-platform,EduPepperPDTesting/pepper2013-testing,devs1991/test_edx_docmode,hamzehd/edx-platform,sudheerchintala/LearnEraPlatForm,dcosentino/edx-platform,ahmadiga/min_edx,kalebhartje/schoolboost,wwj718/ANALYSE,deepsrijit1105/edx-platform,syjeon/new_edx,procangroup/edx-platform,Unow/edx-platform,nikolas/edx-platform,J861449197/edx-platform,ahmedaljazzar/edx-platform,cognitiveclass/edx-platform,prarthitm/edxplatform,syjeon/new_edx,louyihua/edx-platform,defance/edx-platform,EduPepperPDTesting/pepper2013-testing,mjg2203/edx-platform-seas,MSOpenTech/edx-platform,Ayub-Khan/edx-platform,Edraak/edx-platform,devs1991/test_edx_docmode,edx-solutions/edx-platform,peterm-itr/edx-platform,vismartltd/edx-platform,vasyarv/edx-platform,ferabra/edx-platform,Shrhawk/edx-platform,openfun/edx-platform,pomegranited/edx-platform,ahmadio/edx-platform,eduNEXT/edunext-platform,UXE/local-edx,Lektorium-LLC/edx-platform,Edraak/circleci-edx-platform,don-github/edx-platform,simbs/edx-platform,chauhanhardik/populo,hmcmooc/muddx-platform,zubair-arbi/edx-platform,bitifirefly/edx-platform,DNFcode/edx-platform,Kalyzee/edx-platform,fly19890211/edx-platform,pdehaye/theming-edx-platform,shubhdev/edxOnBaadal,doganov/edx-platform,doismellburning/edx-platform,EDUlib/edx-platform,antonve/s4-project-mooc,rhndg/openedx,pku9104038/edx-platform,inares/edx-platform,philanthropy-u/edx-platform,deepsrijit1105/edx-platform,bdero/edx-platform,edry/edx-platform,prarthitm/edxplatform,jswope00/GAI,nanolearning/edx-platform,mjg2203/edx-platform-seas,nttks/jenkins-test,teltek/edx-platform,jamiefolsom/edx-platform,Unow/edx-platform,caesar2164/edx-platform,cecep-edu/edx-platform,solashirai/edx-platform,procangroup/edx-platform,gymnasium/edx-platform,devs1991/test_edx_docmode,polimediaupv/edx-platform,don-github/edx-platform,tiagochiavericosta/edx-platform,gymnasium/edx-platform,shubhdev/edxOnBaadal,nikolas/edx-platform,bigdatauniversity/edx-platform,vikas1885/test1,mjirayu/sit_academy,wwj718/edx-platform,utecuy/edx-platform,doismellburning/edx-platform,UXE/local-edx,vismartltd/edx-platform,Shrhawk/edx-platform,xuxiao19910803/edx,zhenzhai/edx-platform,rhndg/openedx,IndonesiaX/edx-platform,praveen-pal/edx-platform,MSOpenTech/edx-platform,kxliugang/edx-platform,WatanabeYasumasa/edx-platform,utecuy/edx-platform,jonathan-beard/edx-platform,vasyarv/edx-platform,simbs/edx-platform,alexthered/kienhoc-platform,EduPepperPD/pepper2013,chauhanhardik/populo,morenopc/edx-platform,J861449197/edx-platform,SravanthiSinha/edx-platform,hkawasaki/kawasaki-aio8-1,OmarIthawi/edx-platform,vikas1885/test1,devs1991/test_edx_docmode,eduNEXT/edunext-platform,jamiefolsom/edx-platform,amir-qayyum-khan/edx-platform,rue89-tech/edx-platform,waheedahmed/edx-platform,Endika/edx-platform,utecuy/edx-platform,raccoongang/edx-platform,beni55/edx-platform,jamiefolsom/edx-platform,gymnasium/edx-platform,AkA84/edx-platform,synergeticsedx/deployment-wipro,shashank971/edx-platform,ampax/edx-platform-backup,jazztpt/edx-platform,cognitiveclass/edx-platform,itsjeyd/edx-platform,bigdatauniversity/edx-platform,playm2mboy/edx-platform,shubhdev/openedx,jazkarta/edx-platform,eemirtekin/edx-platform,rue89-tech/edx-platform,4eek/edx-platform,pabloborrego93/edx-platform,olexiim/edx-platform,hamzehd/edx-platform,chauhanhardik/populo_2,louyihua/edx-platform,jjmiranda/edx-platform,mtlchun/edx,abdoosh00/edraak,IONISx/edx-platform,playm2mboy/edx-platform,jonathan-beard/edx-platform,kmoocdev2/edx-platform,pepeportela/edx-platform,benpatterson/edx-platform,vismartltd/edx-platform,rationalAgent/edx-platform-custom,yokose-ks/edx-platform,adoosii/edx-platform,jamesblunt/edx-platform,mcgachey/edx-platform,JioEducation/edx-platform,Edraak/edraak-platform,utecuy/edx-platform,martynovp/edx-platform,mushtaqak/edx-platform,jazkarta/edx-platform-for-isc,kursitet/edx-platform,cselis86/edx-platform,franosincic/edx-platform,franosincic/edx-platform,J861449197/edx-platform,PepperPD/edx-pepper-platform,jazztpt/edx-platform,bdero/edx-platform,hamzehd/edx-platform,pelikanchik/edx-platform,jazkarta/edx-platform,kmoocdev/edx-platform,chand3040/cloud_that,morenopc/edx-platform,edry/edx-platform,cecep-edu/edx-platform,LearnEra/LearnEraPlaftform,Unow/edx-platform,openfun/edx-platform,edry/edx-platform,LICEF/edx-platform,unicri/edx-platform,ESOedX/edx-platform,jelugbo/tundex,ubc/edx-platform,wwj718/ANALYSE,appliedx/edx-platform,cselis86/edx-platform,ak2703/edx-platform,MakeHer/edx-platform,alexthered/kienhoc-platform,rismalrv/edx-platform,cognitiveclass/edx-platform,halvertoluke/edx-platform,wwj718/edx-platform,teltek/edx-platform,zerobatu/edx-platform,DNFcode/edx-platform,shurihell/testasia,hkawasaki/kawasaki-aio8-0,andyzsf/edx,nanolearningllc/edx-platform-cypress,ovnicraft/edx-platform,ahmadiga/min_edx,nagyistoce/edx-platform,kmoocdev2/edx-platform,motion2015/a3,sudheerchintala/LearnEraPlatForm,EDUlib/edx-platform,Semi-global/edx-platform,eestay/edx-platform,hkawasaki/kawasaki-aio8-2,arifsetiawan/edx-platform,longmen21/edx-platform,defance/edx-platform,RPI-OPENEDX/edx-platform,morpheby/levelup-by,ferabra/edx-platform,valtech-mooc/edx-platform,leansoft/edx-platform,arifsetiawan/edx-platform,knehez/edx-platform,rue89-tech/edx-platform,DefyVentures/edx-platform,B-MOOC/edx-platform,cecep-edu/edx-platform,synergeticsedx/deployment-wipro,mushtaqak/edx-platform,IndonesiaX/edx-platform,xuxiao19910803/edx,analyseuc3m/ANALYSE-v1,rhndg/openedx,nanolearningllc/edx-platform-cypress,eestay/edx-platform,chauhanhardik/populo_2,playm2mboy/edx-platform,miptliot/edx-platform,adoosii/edx-platform,nttks/edx-platform,cpennington/edx-platform,tiagochiavericosta/edx-platform,abdoosh00/edx-rtl-final,rismalrv/edx-platform,4eek/edx-platform,wwj718/ANALYSE,JioEducation/edx-platform,kamalx/edx-platform,jazztpt/edx-platform,proversity-org/edx-platform,BehavioralInsightsTeam/edx-platform,motion2015/edx-platform,apigee/edx-platform,caesar2164/edx-platform,chauhanhardik/populo_2,jonathan-beard/edx-platform,WatanabeYasumasa/edx-platform,MakeHer/edx-platform,nttks/jenkins-test,B-MOOC/edx-platform,MakeHer/edx-platform,pabloborrego93/edx-platform,bigdatauniversity/edx-platform,mjg2203/edx-platform-seas,dkarakats/edx-platform,mitocw/edx-platform,nttks/jenkins-test,abdoosh00/edx-rtl-final,alu042/edx-platform,eduNEXT/edunext-platform,SivilTaram/edx-platform,ampax/edx-platform-backup,RPI-OPENEDX/edx-platform,chudaol/edx-platform,cselis86/edx-platform,benpatterson/edx-platform,halvertoluke/edx-platform,ampax/edx-platform,rationalAgent/edx-platform-custom,amir-qayyum-khan/edx-platform,arbrandes/edx-platform,dsajkl/123,ahmadiga/min_edx,doismellburning/edx-platform,AkA84/edx-platform,devs1991/test_edx_docmode,AkA84/edx-platform,LICEF/edx-platform,dcosentino/edx-platform,rismalrv/edx-platform,xingyepei/edx-platform,miptliot/edx-platform,chudaol/edx-platform,itsjeyd/edx-platform,solashirai/edx-platform,motion2015/edx-platform,pomegranited/edx-platform,vikas1885/test1,RPI-OPENEDX/edx-platform,mahendra-r/edx-platform,jswope00/griffinx,doismellburning/edx-platform,IITBinterns13/edx-platform-dev,praveen-pal/edx-platform,chudaol/edx-platform,cpennington/edx-platform,Edraak/edx-platform,Edraak/circleci-edx-platform,ahmadio/edx-platform,vikas1885/test1,nanolearning/edx-platform,vikas1885/test1,knehez/edx-platform,zerobatu/edx-platform,IndonesiaX/edx-platform,romain-li/edx-platform,hamzehd/edx-platform,hkawasaki/kawasaki-aio8-0,UOMx/edx-platform,naresh21/synergetics-edx-platform,UOMx/edx-platform,cyanna/edx-platform,jruiperezv/ANALYSE,bitifirefly/edx-platform,jelugbo/tundex,hkawasaki/kawasaki-aio8-1,leansoft/edx-platform,solashirai/edx-platform,nikolas/edx-platform,Softmotions/edx-platform,OmarIthawi/edx-platform,ampax/edx-platform,shurihell/testasia,proversity-org/edx-platform,cyanna/edx-platform,jazkarta/edx-platform-for-isc,kmoocdev/edx-platform,edx/edx-platform,eemirtekin/edx-platform,Shrhawk/edx-platform,hastexo/edx-platform,ampax/edx-platform-backup,PepperPD/edx-pepper-platform,unicri/edx-platform,zadgroup/edx-platform,analyseuc3m/ANALYSE-v1,eduNEXT/edx-platform,mitocw/edx-platform,JCBarahona/edX,UXE/local-edx,kalebhartje/schoolboost,abdoosh00/edx-rtl-final,msegado/edx-platform,leansoft/edx-platform,antonve/s4-project-mooc,hastexo/edx-platform,zubair-arbi/edx-platform,praveen-pal/edx-platform,ahmadio/edx-platform,Lektorium-LLC/edx-platform,arifsetiawan/edx-platform,ZLLab-Mooc/edx-platform,chudaol/edx-platform,dcosentino/edx-platform,JCBarahona/edX,JCBarahona/edX,fly19890211/edx-platform,SravanthiSinha/edx-platform,TsinghuaX/edx-platform,jbassen/edx-platform,marcore/edx-platform,jolyonb/edx-platform,LearnEra/LearnEraPlaftform,edry/edx-platform,ampax/edx-platform,jolyonb/edx-platform,edx-solutions/edx-platform,msegado/edx-platform,lduarte1991/edx-platform,solashirai/edx-platform,deepsrijit1105/edx-platform,bitifirefly/edx-platform,knehez/edx-platform,eduNEXT/edunext-platform,BehavioralInsightsTeam/edx-platform,beni55/edx-platform,xuxiao19910803/edx-platform,LICEF/edx-platform,LICEF/edx-platform,cyanna/edx-platform,Semi-global/edx-platform,miptliot/edx-platform,zubair-arbi/edx-platform,wwj718/edx-platform,DNFcode/edx-platform,a-parhom/edx-platform,simbs/edx-platform,miptliot/edx-platform,halvertoluke/edx-platform,DefyVentures/edx-platform,zofuthan/edx-platform,dsajkl/reqiop,proversity-org/edx-platform,jazztpt/edx-platform,wwj718/ANALYSE,TsinghuaX/edx-platform,chauhanhardik/populo,hkawasaki/kawasaki-aio8-1,kmoocdev2/edx-platform,ak2703/edx-platform,Ayub-Khan/edx-platform,tiagochiavericosta/edx-platform,B-MOOC/edx-platform,nanolearningllc/edx-platform-cypress-2,defance/edx-platform,xinjiguaike/edx-platform,martynovp/edx-platform,jonathan-beard/edx-platform,BehavioralInsightsTeam/edx-platform,abdoosh00/edraak,mbareta/edx-platform-ft,mbareta/edx-platform-ft,tiagochiavericosta/edx-platform,valtech-mooc/edx-platform,CourseTalk/edx-platform,JioEducation/edx-platform,praveen-pal/edx-platform,zerobatu/edx-platform,antoviaque/edx-platform,mushtaqak/edx-platform,jzoldak/edx-platform,Ayub-Khan/edx-platform,pepeportela/edx-platform,EduPepperPD/pepper2013,CredoReference/edx-platform,rationalAgent/edx-platform-custom,JioEducation/edx-platform,louyihua/edx-platform,mjirayu/sit_academy,don-github/edx-platform,TeachAtTUM/edx-platform,gsehub/edx-platform,kamalx/edx-platform,andyzsf/edx,ferabra/edx-platform,4eek/edx-platform,shurihell/testasia,ovnicraft/edx-platform,auferack08/edx-platform,cyanna/edx-platform,nanolearningllc/edx-platform-cypress-2,xuxiao19910803/edx,stvstnfrd/edx-platform,bitifirefly/edx-platform,ak2703/edx-platform,Edraak/circleci-edx-platform,antoviaque/edx-platform,raccoongang/edx-platform,mcgachey/edx-platform,zhenzhai/edx-platform,nagyistoce/edx-platform,motion2015/a3,xuxiao19910803/edx-platform,stvstnfrd/edx-platform,tanmaykm/edx-platform,MakeHer/edx-platform,jbzdak/edx-platform,longmen21/edx-platform,kmoocdev/edx-platform,EduPepperPDTesting/pepper2013-testing,simbs/edx-platform,msegado/edx-platform,mcgachey/edx-platform,TsinghuaX/edx-platform,mbareta/edx-platform-ft,jjmiranda/edx-platform,chrisndodge/edx-platform,beni55/edx-platform,tiagochiavericosta/edx-platform,kmoocdev2/edx-platform,stvstnfrd/edx-platform,IITBinterns13/edx-platform-dev,shubhdev/openedx,leansoft/edx-platform,fly19890211/edx-platform,zadgroup/edx-platform,unicri/edx-platform,Shrhawk/edx-platform,kalebhartje/schoolboost,vismartltd/edx-platform,cecep-edu/edx-platform,IONISx/edx-platform,jamesblunt/edx-platform,doganov/edx-platform,jamiefolsom/edx-platform,jswope00/GAI,marcore/edx-platform,kursitet/edx-platform,doganov/edx-platform,CredoReference/edx-platform,Lektorium-LLC/edx-platform,LearnEra/LearnEraPlaftform,waheedahmed/edx-platform,polimediaupv/edx-platform,naresh21/synergetics-edx-platform,DefyVentures/edx-platform,romain-li/edx-platform,chrisndodge/edx-platform,dsajkl/123,mjirayu/sit_academy,zhenzhai/edx-platform,CredoReference/edx-platform,TsinghuaX/edx-platform,ZLLab-Mooc/edx-platform,y12uc231/edx-platform,wwj718/ANALYSE,pdehaye/theming-edx-platform,jbassen/edx-platform,nttks/edx-platform,PepperPD/edx-pepper-platform,motion2015/a3,knehez/edx-platform,jswope00/griffinx,jamiefolsom/edx-platform,rhndg/openedx,raccoongang/edx-platform,etzhou/edx-platform,doganov/edx-platform,sameetb-cuelogic/edx-platform-test,lduarte1991/edx-platform,jazkarta/edx-platform-for-isc,ubc/edx-platform,hmcmooc/muddx-platform,hastexo/edx-platform,syjeon/new_edx,ESOedX/edx-platform,nttks/edx-platform,zadgroup/edx-platform,CourseTalk/edx-platform,shabab12/edx-platform,simbs/edx-platform,zofuthan/edx-platform,sameetb-cuelogic/edx-platform-test,pomegranited/edx-platform,hkawasaki/kawasaki-aio8-0,jazkarta/edx-platform-for-isc,shashank971/edx-platform,Kalyzee/edx-platform,EduPepperPD/pepper2013,torchingloom/edx-platform,jzoldak/edx-platform,proversity-org/edx-platform,synergeticsedx/deployment-wipro,EduPepperPDTesting/pepper2013-testing,EduPepperPDTesting/pepper2013-testing
import json from datetime import datetime from django.http import HttpResponse + from xmodule.modulestore.django import modulestore def heartbeat(request): """ Simple view that a loadbalancer can check to verify that the app is up """ output = { - 'date': datetime.now().isoformat() + 'date': datetime.now().isoformat(), + 'courses': [course.location for course in modulestore().get_courses()], } return HttpResponse(json.dumps(output, indent=4))
Make heartbeat url wait for courses to be loaded
## Code Before: import json from datetime import datetime from django.http import HttpResponse def heartbeat(request): """ Simple view that a loadbalancer can check to verify that the app is up """ output = { 'date': datetime.now().isoformat() } return HttpResponse(json.dumps(output, indent=4)) ## Instruction: Make heartbeat url wait for courses to be loaded ## Code After: import json from datetime import datetime from django.http import HttpResponse from xmodule.modulestore.django import modulestore def heartbeat(request): """ Simple view that a loadbalancer can check to verify that the app is up """ output = { 'date': datetime.now().isoformat(), 'courses': [course.location for course in modulestore().get_courses()], } return HttpResponse(json.dumps(output, indent=4))
... from django.http import HttpResponse from xmodule.modulestore.django import modulestore ... output = { 'date': datetime.now().isoformat(), 'courses': [course.location for course in modulestore().get_courses()], } ...
e1ffdcc5f12be623633e2abab2041fcb574173ea
homeassistant/components/zeroconf.py
homeassistant/components/zeroconf.py
import logging import socket from homeassistant.const import (EVENT_HOMEASSISTANT_STOP, __version__) REQUIREMENTS = ["zeroconf==0.17.5"] _LOGGER = logging.getLogger(__name__) DOMAIN = "zeroconf" ZEROCONF_TYPE = "_home-assistant._tcp.local." DEPENDENCIES = ["http"] def setup(hass, config): """Set up Zeroconf and make Home Assistant discoverable.""" from zeroconf import Zeroconf, ServiceInfo zeroconf = Zeroconf() zeroconf_name = "{}.{}".format(hass.config.location_name, ZEROCONF_TYPE) params = {"version": __version__, "base_url": hass.http.base_url, "needs_auth": (hass.http.api_password != "")} info = ServiceInfo(ZEROCONF_TYPE, zeroconf_name, socket.inet_aton(hass.http.routable_address), hass.http.server_address[1], 0, 0, params) zeroconf.register_service(info) def stop_zeroconf(event): """Stop Zeroconf.""" zeroconf.unregister_service(info) hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_zeroconf) return True
import logging import socket from homeassistant.const import (EVENT_HOMEASSISTANT_STOP, __version__) REQUIREMENTS = ["zeroconf==0.17.5"] DEPENDENCIES = ["api"] _LOGGER = logging.getLogger(__name__) DOMAIN = "zeroconf" ZEROCONF_TYPE = "_home-assistant._tcp.local." def setup(hass, config): """Set up Zeroconf and make Home Assistant discoverable.""" from zeroconf import Zeroconf, ServiceInfo zeroconf = Zeroconf() zeroconf_name = "{}.{}".format(hass.config.location_name, ZEROCONF_TYPE) params = {"version": __version__, "base_url": hass.config.api.base_url, "needs_auth": (hass.config.api.api_password != "")} info = ServiceInfo(ZEROCONF_TYPE, zeroconf_name, socket.inet_aton(hass.config.api.host), hass.config.api.port, 0, 0, params) zeroconf.register_service(info) def stop_zeroconf(event): """Stop Zeroconf.""" zeroconf.unregister_service(info) hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_zeroconf) return True
Use hass.config.api instead of hass.http
Use hass.config.api instead of hass.http
Python
mit
miniconfig/home-assistant,Julian/home-assistant,toddeye/home-assistant,ct-23/home-assistant,deisi/home-assistant,tchellomello/home-assistant,rohitranjan1991/home-assistant,Julian/home-assistant,Duoxilian/home-assistant,betrisey/home-assistant,keerts/home-assistant,ct-23/home-assistant,tboyce021/home-assistant,kyvinh/home-assistant,leoc/home-assistant,jawilson/home-assistant,JshWright/home-assistant,turbokongen/home-assistant,varunr047/homefile,open-homeautomation/home-assistant,betrisey/home-assistant,GenericStudent/home-assistant,alexmogavero/home-assistant,fbradyirl/home-assistant,eagleamon/home-assistant,kyvinh/home-assistant,toddeye/home-assistant,auduny/home-assistant,aronsky/home-assistant,hmronline/home-assistant,bdfoster/blumate,jaharkes/home-assistant,fbradyirl/home-assistant,srcLurker/home-assistant,morphis/home-assistant,deisi/home-assistant,LinuxChristian/home-assistant,hexxter/home-assistant,sdague/home-assistant,LinuxChristian/home-assistant,shaftoe/home-assistant,stefan-jonasson/home-assistant,adrienbrault/home-assistant,w1ll1am23/home-assistant,tinloaf/home-assistant,soldag/home-assistant,molobrakos/home-assistant,Zyell/home-assistant,HydrelioxGitHub/home-assistant,keerts/home-assistant,molobrakos/home-assistant,varunr047/homefile,jaharkes/home-assistant,xifle/home-assistant,Smart-Torvy/torvy-home-assistant,stefan-jonasson/home-assistant,tboyce1/home-assistant,kennedyshead/home-assistant,sffjunkie/home-assistant,kennedyshead/home-assistant,jnewland/home-assistant,tinloaf/home-assistant,dmeulen/home-assistant,xifle/home-assistant,mikaelboman/home-assistant,Zac-HD/home-assistant,hmronline/home-assistant,partofthething/home-assistant,robjohnson189/home-assistant,lukas-hetzenecker/home-assistant,nugget/home-assistant,aequitas/home-assistant,oandrew/home-assistant,morphis/home-assistant,eagleamon/home-assistant,HydrelioxGitHub/home-assistant,Teagan42/home-assistant,ct-23/home-assistant,Zyell/home-assistant,sffjunkie/home-assistant,tinloaf/home-assistant,philipbl/home-assistant,kyvinh/home-assistant,Julian/home-assistant,PetePriority/home-assistant,sffjunkie/home-assistant,bdfoster/blumate,Teagan42/home-assistant,rohitranjan1991/home-assistant,deisi/home-assistant,miniconfig/home-assistant,robjohnson189/home-assistant,happyleavesaoc/home-assistant,morphis/home-assistant,GenericStudent/home-assistant,soldag/home-assistant,deisi/home-assistant,Duoxilian/home-assistant,persandstrom/home-assistant,w1ll1am23/home-assistant,oandrew/home-assistant,mezz64/home-assistant,DavidLP/home-assistant,morphis/home-assistant,tboyce1/home-assistant,florianholzapfel/home-assistant,Danielhiversen/home-assistant,home-assistant/home-assistant,florianholzapfel/home-assistant,srcLurker/home-assistant,stefan-jonasson/home-assistant,Smart-Torvy/torvy-home-assistant,sdague/home-assistant,kyvinh/home-assistant,balloob/home-assistant,happyleavesaoc/home-assistant,MartinHjelmare/home-assistant,happyleavesaoc/home-assistant,adrienbrault/home-assistant,ewandor/home-assistant,nugget/home-assistant,xifle/home-assistant,MungoRae/home-assistant,robbiet480/home-assistant,MartinHjelmare/home-assistant,alexmogavero/home-assistant,leppa/home-assistant,open-homeautomation/home-assistant,leoc/home-assistant,LinuxChristian/home-assistant,leoc/home-assistant,MartinHjelmare/home-assistant,Julian/home-assistant,miniconfig/home-assistant,lukas-hetzenecker/home-assistant,mikaelboman/home-assistant,joopert/home-assistant,Zac-HD/home-assistant,auduny/home-assistant,Zac-HD/home-assistant,joopert/home-assistant,ma314smith/home-assistant,Zyell/home-assistant,devdelay/home-assistant,srcLurker/home-assistant,hexxter/home-assistant,HydrelioxGitHub/home-assistant,mikaelboman/home-assistant,aequitas/home-assistant,qedi-r/home-assistant,nkgilley/home-assistant,jnewland/home-assistant,deisi/home-assistant,leoc/home-assistant,jaharkes/home-assistant,varunr047/homefile,nugget/home-assistant,hexxter/home-assistant,sander76/home-assistant,fbradyirl/home-assistant,partofthething/home-assistant,jamespcole/home-assistant,persandstrom/home-assistant,jnewland/home-assistant,balloob/home-assistant,leppa/home-assistant,bdfoster/blumate,keerts/home-assistant,shaftoe/home-assistant,pschmitt/home-assistant,philipbl/home-assistant,tboyce1/home-assistant,betrisey/home-assistant,hmronline/home-assistant,sander76/home-assistant,xifle/home-assistant,JshWright/home-assistant,oandrew/home-assistant,PetePriority/home-assistant,varunr047/homefile,dmeulen/home-assistant,tboyce021/home-assistant,alexmogavero/home-assistant,DavidLP/home-assistant,persandstrom/home-assistant,LinuxChristian/home-assistant,philipbl/home-assistant,JshWright/home-assistant,FreekingDean/home-assistant,robbiet480/home-assistant,jabesq/home-assistant,ct-23/home-assistant,hmronline/home-assistant,ma314smith/home-assistant,Smart-Torvy/torvy-home-assistant,JshWright/home-assistant,home-assistant/home-assistant,shaftoe/home-assistant,devdelay/home-assistant,emilhetty/home-assistant,emilhetty/home-assistant,Smart-Torvy/torvy-home-assistant,mKeRix/home-assistant,mKeRix/home-assistant,Danielhiversen/home-assistant,stefan-jonasson/home-assistant,bdfoster/blumate,sffjunkie/home-assistant,bdfoster/blumate,jawilson/home-assistant,florianholzapfel/home-assistant,MungoRae/home-assistant,jaharkes/home-assistant,Cinntax/home-assistant,aronsky/home-assistant,auduny/home-assistant,robjohnson189/home-assistant,florianholzapfel/home-assistant,emilhetty/home-assistant,devdelay/home-assistant,sffjunkie/home-assistant,MungoRae/home-assistant,mikaelboman/home-assistant,Duoxilian/home-assistant,Duoxilian/home-assistant,dmeulen/home-assistant,betrisey/home-assistant,ma314smith/home-assistant,open-homeautomation/home-assistant,DavidLP/home-assistant,robjohnson189/home-assistant,dmeulen/home-assistant,mikaelboman/home-assistant,jamespcole/home-assistant,philipbl/home-assistant,jabesq/home-assistant,emilhetty/home-assistant,oandrew/home-assistant,rohitranjan1991/home-assistant,MungoRae/home-assistant,mKeRix/home-assistant,shaftoe/home-assistant,titilambert/home-assistant,MungoRae/home-assistant,varunr047/homefile,balloob/home-assistant,molobrakos/home-assistant,postlund/home-assistant,happyleavesaoc/home-assistant,mezz64/home-assistant,Zac-HD/home-assistant,ct-23/home-assistant,open-homeautomation/home-assistant,ma314smith/home-assistant,FreekingDean/home-assistant,mKeRix/home-assistant,qedi-r/home-assistant,miniconfig/home-assistant,ewandor/home-assistant,srcLurker/home-assistant,ewandor/home-assistant,PetePriority/home-assistant,postlund/home-assistant,jabesq/home-assistant,alexmogavero/home-assistant,aequitas/home-assistant,devdelay/home-assistant,hexxter/home-assistant,Cinntax/home-assistant,titilambert/home-assistant,emilhetty/home-assistant,tchellomello/home-assistant,keerts/home-assistant,LinuxChristian/home-assistant,eagleamon/home-assistant,nkgilley/home-assistant,hmronline/home-assistant,jamespcole/home-assistant,pschmitt/home-assistant,tboyce1/home-assistant,eagleamon/home-assistant,turbokongen/home-assistant
import logging import socket from homeassistant.const import (EVENT_HOMEASSISTANT_STOP, __version__) REQUIREMENTS = ["zeroconf==0.17.5"] + DEPENDENCIES = ["api"] + _LOGGER = logging.getLogger(__name__) DOMAIN = "zeroconf" ZEROCONF_TYPE = "_home-assistant._tcp.local." - - DEPENDENCIES = ["http"] def setup(hass, config): """Set up Zeroconf and make Home Assistant discoverable.""" from zeroconf import Zeroconf, ServiceInfo zeroconf = Zeroconf() zeroconf_name = "{}.{}".format(hass.config.location_name, ZEROCONF_TYPE) - params = {"version": __version__, "base_url": hass.http.base_url, + params = {"version": __version__, "base_url": hass.config.api.base_url, - "needs_auth": (hass.http.api_password != "")} + "needs_auth": (hass.config.api.api_password != "")} info = ServiceInfo(ZEROCONF_TYPE, zeroconf_name, - socket.inet_aton(hass.http.routable_address), + socket.inet_aton(hass.config.api.host), - hass.http.server_address[1], 0, 0, params) + hass.config.api.port, 0, 0, params) zeroconf.register_service(info) def stop_zeroconf(event): """Stop Zeroconf.""" zeroconf.unregister_service(info) hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_zeroconf) return True
Use hass.config.api instead of hass.http
## Code Before: import logging import socket from homeassistant.const import (EVENT_HOMEASSISTANT_STOP, __version__) REQUIREMENTS = ["zeroconf==0.17.5"] _LOGGER = logging.getLogger(__name__) DOMAIN = "zeroconf" ZEROCONF_TYPE = "_home-assistant._tcp.local." DEPENDENCIES = ["http"] def setup(hass, config): """Set up Zeroconf and make Home Assistant discoverable.""" from zeroconf import Zeroconf, ServiceInfo zeroconf = Zeroconf() zeroconf_name = "{}.{}".format(hass.config.location_name, ZEROCONF_TYPE) params = {"version": __version__, "base_url": hass.http.base_url, "needs_auth": (hass.http.api_password != "")} info = ServiceInfo(ZEROCONF_TYPE, zeroconf_name, socket.inet_aton(hass.http.routable_address), hass.http.server_address[1], 0, 0, params) zeroconf.register_service(info) def stop_zeroconf(event): """Stop Zeroconf.""" zeroconf.unregister_service(info) hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_zeroconf) return True ## Instruction: Use hass.config.api instead of hass.http ## Code After: import logging import socket from homeassistant.const import (EVENT_HOMEASSISTANT_STOP, __version__) REQUIREMENTS = ["zeroconf==0.17.5"] DEPENDENCIES = ["api"] _LOGGER = logging.getLogger(__name__) DOMAIN = "zeroconf" ZEROCONF_TYPE = "_home-assistant._tcp.local." def setup(hass, config): """Set up Zeroconf and make Home Assistant discoverable.""" from zeroconf import Zeroconf, ServiceInfo zeroconf = Zeroconf() zeroconf_name = "{}.{}".format(hass.config.location_name, ZEROCONF_TYPE) params = {"version": __version__, "base_url": hass.config.api.base_url, "needs_auth": (hass.config.api.api_password != "")} info = ServiceInfo(ZEROCONF_TYPE, zeroconf_name, socket.inet_aton(hass.config.api.host), hass.config.api.port, 0, 0, params) zeroconf.register_service(info) def stop_zeroconf(event): """Stop Zeroconf.""" zeroconf.unregister_service(info) hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_zeroconf) return True
# ... existing code ... DEPENDENCIES = ["api"] _LOGGER = logging.getLogger(__name__) # ... modified code ... ZEROCONF_TYPE = "_home-assistant._tcp.local." ... params = {"version": __version__, "base_url": hass.config.api.base_url, "needs_auth": (hass.config.api.api_password != "")} ... info = ServiceInfo(ZEROCONF_TYPE, zeroconf_name, socket.inet_aton(hass.config.api.host), hass.config.api.port, 0, 0, params) # ... rest of the code ...
2c05dba69c838cfd3808d8e03dbea3cc56d4f6d2
pyinfra_kubernetes/__init__.py
pyinfra_kubernetes/__init__.py
from .configure import configure_kubeconfig, configure_kubernetes_component from .install import install_kubernetes def deploy_kubernetes_master(etcd_nodes): # Install server components install_kubernetes(components=( 'kube-apiserver', 'kube-scheduler', 'kube-controller-manager', )) # Configure the API server, passing in our etcd nodes configure_kubernetes_component('kube-apiserver', etcd_nodes=etcd_nodes) configure_kubernetes_component('kube-scheduler') configure_kubernetes_component('kube-controller-manager') def deploy_kubernetes_node(master_address): # Install node components install_kubernetes(components=( 'kubelet', 'kube-proxy', )) # Setup the kubeconfig for kubelet & kube-proxy to use configure_kubeconfig(master_address) configure_kubernetes_component('kubelet') configure_kubernetes_component('kube-proxy')
from pyinfra.api import deploy from .configure import configure_kubeconfig, configure_kubernetes_component from .install import install_kubernetes @deploy('Deploy Kubernetes master') def deploy_kubernetes_master( state, host, etcd_nodes, ): # Install server components install_kubernetes(components=( 'kube-apiserver', 'kube-scheduler', 'kube-controller-manager', )) # Configure the API server, passing in our etcd nodes configure_kubernetes_component('kube-apiserver', etcd_nodes=etcd_nodes) configure_kubernetes_component('kube-scheduler') configure_kubernetes_component('kube-controller-manager') @deploy('Deploy Kubernetes node') def deploy_kubernetes_node( state, host, master_address, ): # Install node components install_kubernetes(components=( 'kubelet', 'kube-proxy', )) # Setup the kubeconfig for kubelet & kube-proxy to use configure_kubeconfig(master_address) configure_kubernetes_component('kubelet') configure_kubernetes_component('kube-proxy')
Make helper functions full `@deploy`s so they support global pyinfra kwargs.
Make helper functions full `@deploy`s so they support global pyinfra kwargs.
Python
mit
EDITD/pyinfra-kubernetes,EDITD/pyinfra-kubernetes
+ from pyinfra.api import deploy + from .configure import configure_kubeconfig, configure_kubernetes_component from .install import install_kubernetes + @deploy('Deploy Kubernetes master') - def deploy_kubernetes_master(etcd_nodes): + def deploy_kubernetes_master( + state, host, + etcd_nodes, + ): # Install server components install_kubernetes(components=( 'kube-apiserver', 'kube-scheduler', 'kube-controller-manager', )) # Configure the API server, passing in our etcd nodes configure_kubernetes_component('kube-apiserver', etcd_nodes=etcd_nodes) configure_kubernetes_component('kube-scheduler') configure_kubernetes_component('kube-controller-manager') + @deploy('Deploy Kubernetes node') - def deploy_kubernetes_node(master_address): + def deploy_kubernetes_node( + state, host, + master_address, + ): # Install node components install_kubernetes(components=( 'kubelet', 'kube-proxy', )) # Setup the kubeconfig for kubelet & kube-proxy to use configure_kubeconfig(master_address) configure_kubernetes_component('kubelet') configure_kubernetes_component('kube-proxy')
Make helper functions full `@deploy`s so they support global pyinfra kwargs.
## Code Before: from .configure import configure_kubeconfig, configure_kubernetes_component from .install import install_kubernetes def deploy_kubernetes_master(etcd_nodes): # Install server components install_kubernetes(components=( 'kube-apiserver', 'kube-scheduler', 'kube-controller-manager', )) # Configure the API server, passing in our etcd nodes configure_kubernetes_component('kube-apiserver', etcd_nodes=etcd_nodes) configure_kubernetes_component('kube-scheduler') configure_kubernetes_component('kube-controller-manager') def deploy_kubernetes_node(master_address): # Install node components install_kubernetes(components=( 'kubelet', 'kube-proxy', )) # Setup the kubeconfig for kubelet & kube-proxy to use configure_kubeconfig(master_address) configure_kubernetes_component('kubelet') configure_kubernetes_component('kube-proxy') ## Instruction: Make helper functions full `@deploy`s so they support global pyinfra kwargs. ## Code After: from pyinfra.api import deploy from .configure import configure_kubeconfig, configure_kubernetes_component from .install import install_kubernetes @deploy('Deploy Kubernetes master') def deploy_kubernetes_master( state, host, etcd_nodes, ): # Install server components install_kubernetes(components=( 'kube-apiserver', 'kube-scheduler', 'kube-controller-manager', )) # Configure the API server, passing in our etcd nodes configure_kubernetes_component('kube-apiserver', etcd_nodes=etcd_nodes) configure_kubernetes_component('kube-scheduler') configure_kubernetes_component('kube-controller-manager') @deploy('Deploy Kubernetes node') def deploy_kubernetes_node( state, host, master_address, ): # Install node components install_kubernetes(components=( 'kubelet', 'kube-proxy', )) # Setup the kubeconfig for kubelet & kube-proxy to use configure_kubeconfig(master_address) configure_kubernetes_component('kubelet') configure_kubernetes_component('kube-proxy')
... from pyinfra.api import deploy from .configure import configure_kubeconfig, configure_kubernetes_component ... @deploy('Deploy Kubernetes master') def deploy_kubernetes_master( state, host, etcd_nodes, ): # Install server components ... @deploy('Deploy Kubernetes node') def deploy_kubernetes_node( state, host, master_address, ): # Install node components ...
5458a44ed193a7c4a37a3414e860a23dc5564c39
github3/repos/deployment.py
github3/repos/deployment.py
from github3.models import GitHubCore from github3.users import User class Deployment(GitHubCore): CUSTOM_HEADERS = { 'Accept': 'application/vnd.github.cannonball-preview+json' } def __init__(self, deployment, session=None): super(Deployment, self).__init__(deployment, session) self._api = deployment.get('url') #: GitHub's id of this deployment self.id = deployment.get('id') #: SHA of the branch on GitHub self.sha = deployment.get('sha') #: User object representing the creator of the deployment self.creator = deployment.get('creator') if self.creator: self.creator = User(self.creator, self) #: JSON string payload of the Deployment self.payload = deployment.get('payload') #: Date the Deployment was created self.created_at = deployment.get('created_at') if self.created_at: self.created_at = self._strptime(self.created_at) #: Date the Deployment was updated self.updated_at = deployment.get('updated_at') if self.updated_at: self.updated_at = self._strptime(self.updated_at) #: Description of the deployment self.description = deployment.get('description') #: URL to get the statuses of this deployment self.statuses_url = deployment.get('statuses_url')
from github3.models import GitHubCore from github3.users import User class Deployment(GitHubCore): CUSTOM_HEADERS = { 'Accept': 'application/vnd.github.cannonball-preview+json' } def __init__(self, deployment, session=None): super(Deployment, self).__init__(deployment, session) self._api = deployment.get('url') #: GitHub's id of this deployment self.id = deployment.get('id') #: SHA of the branch on GitHub self.sha = deployment.get('sha') #: User object representing the creator of the deployment self.creator = deployment.get('creator') if self.creator: self.creator = User(self.creator, self) #: JSON string payload of the Deployment self.payload = deployment.get('payload') #: Date the Deployment was created self.created_at = deployment.get('created_at') if self.created_at: self.created_at = self._strptime(self.created_at) #: Date the Deployment was updated self.updated_at = deployment.get('updated_at') if self.updated_at: self.updated_at = self._strptime(self.updated_at) #: Description of the deployment self.description = deployment.get('description') #: URL to get the statuses of this deployment self.statuses_url = deployment.get('statuses_url') def __repr__(self): return '<Deployment [{0} @ {1}]>'.format(self.id, self.sha)
Add repr to Deployment class
Add repr to Deployment class
Python
bsd-3-clause
wbrefvem/github3.py,icio/github3.py,jim-minter/github3.py,itsmemattchung/github3.py,sigmavirus24/github3.py,ueg1990/github3.py,agamdua/github3.py,balloob/github3.py,krxsky/github3.py,degustaf/github3.py,christophelec/github3.py,h4ck3rm1k3/github3.py
from github3.models import GitHubCore from github3.users import User class Deployment(GitHubCore): CUSTOM_HEADERS = { 'Accept': 'application/vnd.github.cannonball-preview+json' } def __init__(self, deployment, session=None): super(Deployment, self).__init__(deployment, session) self._api = deployment.get('url') #: GitHub's id of this deployment self.id = deployment.get('id') #: SHA of the branch on GitHub self.sha = deployment.get('sha') #: User object representing the creator of the deployment self.creator = deployment.get('creator') if self.creator: self.creator = User(self.creator, self) #: JSON string payload of the Deployment self.payload = deployment.get('payload') #: Date the Deployment was created self.created_at = deployment.get('created_at') if self.created_at: self.created_at = self._strptime(self.created_at) #: Date the Deployment was updated self.updated_at = deployment.get('updated_at') if self.updated_at: self.updated_at = self._strptime(self.updated_at) #: Description of the deployment self.description = deployment.get('description') #: URL to get the statuses of this deployment self.statuses_url = deployment.get('statuses_url') + def __repr__(self): + return '<Deployment [{0} @ {1}]>'.format(self.id, self.sha) +
Add repr to Deployment class
## Code Before: from github3.models import GitHubCore from github3.users import User class Deployment(GitHubCore): CUSTOM_HEADERS = { 'Accept': 'application/vnd.github.cannonball-preview+json' } def __init__(self, deployment, session=None): super(Deployment, self).__init__(deployment, session) self._api = deployment.get('url') #: GitHub's id of this deployment self.id = deployment.get('id') #: SHA of the branch on GitHub self.sha = deployment.get('sha') #: User object representing the creator of the deployment self.creator = deployment.get('creator') if self.creator: self.creator = User(self.creator, self) #: JSON string payload of the Deployment self.payload = deployment.get('payload') #: Date the Deployment was created self.created_at = deployment.get('created_at') if self.created_at: self.created_at = self._strptime(self.created_at) #: Date the Deployment was updated self.updated_at = deployment.get('updated_at') if self.updated_at: self.updated_at = self._strptime(self.updated_at) #: Description of the deployment self.description = deployment.get('description') #: URL to get the statuses of this deployment self.statuses_url = deployment.get('statuses_url') ## Instruction: Add repr to Deployment class ## Code After: from github3.models import GitHubCore from github3.users import User class Deployment(GitHubCore): CUSTOM_HEADERS = { 'Accept': 'application/vnd.github.cannonball-preview+json' } def __init__(self, deployment, session=None): super(Deployment, self).__init__(deployment, session) self._api = deployment.get('url') #: GitHub's id of this deployment self.id = deployment.get('id') #: SHA of the branch on GitHub self.sha = deployment.get('sha') #: User object representing the creator of the deployment self.creator = deployment.get('creator') if self.creator: self.creator = User(self.creator, self) #: JSON string payload of the Deployment self.payload = deployment.get('payload') #: Date the Deployment was created self.created_at = deployment.get('created_at') if self.created_at: self.created_at = self._strptime(self.created_at) #: Date the Deployment was updated self.updated_at = deployment.get('updated_at') if self.updated_at: self.updated_at = self._strptime(self.updated_at) #: Description of the deployment self.description = deployment.get('description') #: URL to get the statuses of this deployment self.statuses_url = deployment.get('statuses_url') def __repr__(self): return '<Deployment [{0} @ {1}]>'.format(self.id, self.sha)
... self.statuses_url = deployment.get('statuses_url') def __repr__(self): return '<Deployment [{0} @ {1}]>'.format(self.id, self.sha) ...
a1b4afc062b246dc347526202ef00a43992afa28
code/kmeans.py
code/kmeans.py
def distance(X, Y): d = 0 for row in range(len(X)): for col in range(len(X[row]): if X[row][col] != Y[row][col]: d += 1 return d #partitions the data into the sets closest to each centroid def fit(data, centroids): pass #returns k centroids which partition the data optimally into k clusters def cluster(data, k): pass #allows the user to assign character names to each centroid given def label(centroids): pass
from random import randint from copy import deepcopy from parse import parse #In this file, I am assuming that the 6 metadata entries at the front of each # raw data point hae been stripped off during initial parsing. #returns the distance between two data points def distance(X, Y): assert(len(X) == len(Y)) d = 0 for pixel in range(len(X)): if X[pixel] != Y[pixel]: d += 1 return d #Intelligently find some starting centroids, instead of choosing k random points. # Choose one random point to start with, then find the point with largest # sum of distances from all other centroids selected so far and make it a centroid # until k have been chosen. def find_initial_centroids(data, k): assert(len(data) >= k) data = deepcopy(data) centroids = [] i = randint(0, len(data - 1)) if k > 0: centroids.append(data[i]) while (len(centroids) < k): new_i = None max_distance = None for i in range(len(data)): total_distance = 0 for c in centroids: total_distance += distance(data[i], c) if (new_i == None) or (total_distance > max_distance): new_i = i max_distance = total_distance centroids.append(data.pop(i)) return centroids #Finds the representative centroid of a subset of data, based on the most # common pixel in each position def find_centroid(data): assert(len(data) > 0) centroid = [0]*len(data[0]) for i in range(len(centroid)): sum = 0 for point in data: sum += point[i] #Assuming pixel values are either 1 or 0 if (sum / len(data)) >= .5: #If a majority of pixels have value 1 centroid[i] = 1 return centroid #partitions the data into the sets closest to each centroid def fit(data, centroids): pass #returns k centroids which partition the data optimally into k clusters def cluster(data, k): centroids = find_initial_centroids(data, k)
Add helper to find representative centroid of a subset of data, add helper to generate initial k centroid intelligently
Add helper to find representative centroid of a subset of data, add helper to generate initial k centroid intelligently
Python
mit
mkaplan218/clusterverify
+ from random import randint + from copy import deepcopy + + from parse import parse + + #In this file, I am assuming that the 6 metadata entries at the front of each + # raw data point hae been stripped off during initial parsing. + + #returns the distance between two data points + def distance(X, Y): + assert(len(X) == len(Y)) + d = 0 - for row in range(len(X)): + for pixel in range(len(X)): + if X[pixel] != Y[pixel]: - for col in range(len(X[row]): - if X[row][col] != Y[row][col]: - d += 1 + d += 1 return d + #Intelligently find some starting centroids, instead of choosing k random points. + # Choose one random point to start with, then find the point with largest + # sum of distances from all other centroids selected so far and make it a centroid + # until k have been chosen. + + def find_initial_centroids(data, k): + assert(len(data) >= k) + data = deepcopy(data) + + centroids = [] + i = randint(0, len(data - 1)) + + if k > 0: + centroids.append(data[i]) + + while (len(centroids) < k): + new_i = None + max_distance = None + for i in range(len(data)): + total_distance = 0 + for c in centroids: + total_distance += distance(data[i], c) + if (new_i == None) or (total_distance > max_distance): + new_i = i + max_distance = total_distance + centroids.append(data.pop(i)) + + return centroids + + #Finds the representative centroid of a subset of data, based on the most + # common pixel in each position + + def find_centroid(data): + assert(len(data) > 0) + + centroid = [0]*len(data[0]) + for i in range(len(centroid)): + sum = 0 + for point in data: + sum += point[i] #Assuming pixel values are either 1 or 0 + if (sum / len(data)) >= .5: #If a majority of pixels have value 1 + centroid[i] = 1 + + return centroid + #partitions the data into the sets closest to each centroid + def fit(data, centroids): pass #returns k centroids which partition the data optimally into k clusters + def cluster(data, k): - pass + centroids = find_initial_centroids(data, k) + - #allows the user to assign character names to each centroid given - def label(centroids): - pass -
Add helper to find representative centroid of a subset of data, add helper to generate initial k centroid intelligently
## Code Before: def distance(X, Y): d = 0 for row in range(len(X)): for col in range(len(X[row]): if X[row][col] != Y[row][col]: d += 1 return d #partitions the data into the sets closest to each centroid def fit(data, centroids): pass #returns k centroids which partition the data optimally into k clusters def cluster(data, k): pass #allows the user to assign character names to each centroid given def label(centroids): pass ## Instruction: Add helper to find representative centroid of a subset of data, add helper to generate initial k centroid intelligently ## Code After: from random import randint from copy import deepcopy from parse import parse #In this file, I am assuming that the 6 metadata entries at the front of each # raw data point hae been stripped off during initial parsing. #returns the distance between two data points def distance(X, Y): assert(len(X) == len(Y)) d = 0 for pixel in range(len(X)): if X[pixel] != Y[pixel]: d += 1 return d #Intelligently find some starting centroids, instead of choosing k random points. # Choose one random point to start with, then find the point with largest # sum of distances from all other centroids selected so far and make it a centroid # until k have been chosen. def find_initial_centroids(data, k): assert(len(data) >= k) data = deepcopy(data) centroids = [] i = randint(0, len(data - 1)) if k > 0: centroids.append(data[i]) while (len(centroids) < k): new_i = None max_distance = None for i in range(len(data)): total_distance = 0 for c in centroids: total_distance += distance(data[i], c) if (new_i == None) or (total_distance > max_distance): new_i = i max_distance = total_distance centroids.append(data.pop(i)) return centroids #Finds the representative centroid of a subset of data, based on the most # common pixel in each position def find_centroid(data): assert(len(data) > 0) centroid = [0]*len(data[0]) for i in range(len(centroid)): sum = 0 for point in data: sum += point[i] #Assuming pixel values are either 1 or 0 if (sum / len(data)) >= .5: #If a majority of pixels have value 1 centroid[i] = 1 return centroid #partitions the data into the sets closest to each centroid def fit(data, centroids): pass #returns k centroids which partition the data optimally into k clusters def cluster(data, k): centroids = find_initial_centroids(data, k)
# ... existing code ... from random import randint from copy import deepcopy from parse import parse #In this file, I am assuming that the 6 metadata entries at the front of each # raw data point hae been stripped off during initial parsing. #returns the distance between two data points def distance(X, Y): assert(len(X) == len(Y)) d = 0 for pixel in range(len(X)): if X[pixel] != Y[pixel]: d += 1 return d # ... modified code ... #Intelligently find some starting centroids, instead of choosing k random points. # Choose one random point to start with, then find the point with largest # sum of distances from all other centroids selected so far and make it a centroid # until k have been chosen. def find_initial_centroids(data, k): assert(len(data) >= k) data = deepcopy(data) centroids = [] i = randint(0, len(data - 1)) if k > 0: centroids.append(data[i]) while (len(centroids) < k): new_i = None max_distance = None for i in range(len(data)): total_distance = 0 for c in centroids: total_distance += distance(data[i], c) if (new_i == None) or (total_distance > max_distance): new_i = i max_distance = total_distance centroids.append(data.pop(i)) return centroids #Finds the representative centroid of a subset of data, based on the most # common pixel in each position def find_centroid(data): assert(len(data) > 0) centroid = [0]*len(data[0]) for i in range(len(centroid)): sum = 0 for point in data: sum += point[i] #Assuming pixel values are either 1 or 0 if (sum / len(data)) >= .5: #If a majority of pixels have value 1 centroid[i] = 1 return centroid #partitions the data into the sets closest to each centroid def fit(data, centroids): ... #returns k centroids which partition the data optimally into k clusters def cluster(data, k): centroids = find_initial_centroids(data, k) # ... rest of the code ...
5c0bee77329f68ed0b2e3b576747886492007b8c
neovim/tabpage.py
neovim/tabpage.py
from util import RemoteMap class Tabpage(object): @property def windows(self): if not hasattr(self, '_windows'): self._windows = RemoteSequence(self, self.Window, lambda: self.get_windows()) return self._windows @property def vars(self): if not hasattr(self, '_vars'): self._vars = RemoteMap(lambda k: self.get_var(k), lambda k, v: self.set_var(k, v)) return self._vars @property def number(self): return self._handle @property def window(self): return self.get_window() @property def valid(self): return self.is_valid()
from util import RemoteMap, RemoteSequence class Tabpage(object): @property def windows(self): if not hasattr(self, '_windows'): self._windows = RemoteSequence(self, self._vim.Window, lambda: self.get_windows()) return self._windows @property def vars(self): if not hasattr(self, '_vars'): self._vars = RemoteMap(lambda k: self.get_var(k), lambda k, v: self.set_var(k, v)) return self._vars @property def number(self): return self._handle @property def window(self): return self.get_window() @property def valid(self): return self.is_valid()
Fix 'windows' property of Tabpage objects
Fix 'windows' property of Tabpage objects
Python
apache-2.0
bfredl/python-client,fwalch/python-client,Shougo/python-client,neovim/python-client,meitham/python-client,brcolow/python-client,traverseda/python-client,neovim/python-client,Shougo/python-client,meitham/python-client,starcraftman/python-client,brcolow/python-client,0x90sled/python-client,fwalch/python-client,zchee/python-client,justinmk/python-client,bfredl/python-client,justinmk/python-client,zchee/python-client,0x90sled/python-client,timeyyy/python-client,starcraftman/python-client,timeyyy/python-client,traverseda/python-client
- from util import RemoteMap + from util import RemoteMap, RemoteSequence class Tabpage(object): @property def windows(self): if not hasattr(self, '_windows'): self._windows = RemoteSequence(self, - self.Window, + self._vim.Window, lambda: self.get_windows()) return self._windows @property def vars(self): if not hasattr(self, '_vars'): self._vars = RemoteMap(lambda k: self.get_var(k), lambda k, v: self.set_var(k, v)) return self._vars @property def number(self): return self._handle @property def window(self): return self.get_window() @property def valid(self): return self.is_valid()
Fix 'windows' property of Tabpage objects
## Code Before: from util import RemoteMap class Tabpage(object): @property def windows(self): if not hasattr(self, '_windows'): self._windows = RemoteSequence(self, self.Window, lambda: self.get_windows()) return self._windows @property def vars(self): if not hasattr(self, '_vars'): self._vars = RemoteMap(lambda k: self.get_var(k), lambda k, v: self.set_var(k, v)) return self._vars @property def number(self): return self._handle @property def window(self): return self.get_window() @property def valid(self): return self.is_valid() ## Instruction: Fix 'windows' property of Tabpage objects ## Code After: from util import RemoteMap, RemoteSequence class Tabpage(object): @property def windows(self): if not hasattr(self, '_windows'): self._windows = RemoteSequence(self, self._vim.Window, lambda: self.get_windows()) return self._windows @property def vars(self): if not hasattr(self, '_vars'): self._vars = RemoteMap(lambda k: self.get_var(k), lambda k, v: self.set_var(k, v)) return self._vars @property def number(self): return self._handle @property def window(self): return self.get_window() @property def valid(self): return self.is_valid()
// ... existing code ... from util import RemoteMap, RemoteSequence // ... modified code ... self._windows = RemoteSequence(self, self._vim.Window, lambda: self.get_windows()) // ... rest of the code ...
d0c284139fe475a62fa53cde7e3e20cf2cc2d977
plugins/FileHandlers/STLWriter/__init__.py
plugins/FileHandlers/STLWriter/__init__.py
from . import STLWriter def getMetaData(): return { 'type': 'mesh_writer', 'plugin': { "name": "STL Writer" } } def register(app): return STLWriter.STLWriter()
from . import STLWriter def getMetaData(): return { 'type': 'mesh_writer', 'plugin': { "name": "STL Writer" }, 'mesh_writer': { 'extension': 'stl', 'description': 'STL File' } } def register(app): return STLWriter.STLWriter()
Add writer metadata to the STL writer plugin so it can be used in Cura
Add writer metadata to the STL writer plugin so it can be used in Cura
Python
agpl-3.0
onitake/Uranium,onitake/Uranium
from . import STLWriter def getMetaData(): return { 'type': 'mesh_writer', 'plugin': { "name": "STL Writer" + }, + 'mesh_writer': { + 'extension': 'stl', + 'description': 'STL File' } } def register(app): return STLWriter.STLWriter()
Add writer metadata to the STL writer plugin so it can be used in Cura
## Code Before: from . import STLWriter def getMetaData(): return { 'type': 'mesh_writer', 'plugin': { "name": "STL Writer" } } def register(app): return STLWriter.STLWriter() ## Instruction: Add writer metadata to the STL writer plugin so it can be used in Cura ## Code After: from . import STLWriter def getMetaData(): return { 'type': 'mesh_writer', 'plugin': { "name": "STL Writer" }, 'mesh_writer': { 'extension': 'stl', 'description': 'STL File' } } def register(app): return STLWriter.STLWriter()
// ... existing code ... "name": "STL Writer" }, 'mesh_writer': { 'extension': 'stl', 'description': 'STL File' } // ... rest of the code ...
5c41286666290c2a067c51b7ab9ea171e4657d69
fb/models.py
fb/models.py
from django.db import models # Create your models here.
from django.db import models class UserPost(models.Model): text = models.TextField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) author = models.CharField(default='Eau De Web', max_length=20) def __unicode__(self): return '{} @ {}'.format(self.author, self.date_added)
Write a model class for user posts.
Write a model class for user posts.
Python
apache-2.0
pure-python/brainmate
from django.db import models - # Create your models here. + class UserPost(models.Model): + text = models.TextField(max_length=200) + date_added = models.DateTimeField(auto_now_add=True) + author = models.CharField(default='Eau De Web', max_length=20) + + def __unicode__(self): + return '{} @ {}'.format(self.author, self.date_added) +
Write a model class for user posts.
## Code Before: from django.db import models # Create your models here. ## Instruction: Write a model class for user posts. ## Code After: from django.db import models class UserPost(models.Model): text = models.TextField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) author = models.CharField(default='Eau De Web', max_length=20) def __unicode__(self): return '{} @ {}'.format(self.author, self.date_added)
// ... existing code ... class UserPost(models.Model): text = models.TextField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) author = models.CharField(default='Eau De Web', max_length=20) def __unicode__(self): return '{} @ {}'.format(self.author, self.date_added) // ... rest of the code ...
b836b2c39299cc6dbcbdbc8bcffe046f25909edc
test_portend.py
test_portend.py
import socket import pytest import portend def socket_infos(): """ Generate addr infos for connections to localhost """ host = '' port = portend.find_available_local_port() return socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM) def id_for_info(info): af, = info[:1] return str(af) def build_listening_infos(): params = list(socket_infos()) ids = list(map(id_for_info, params)) return locals() @pytest.fixture(**build_listening_infos()) def listening_addr(request): af, socktype, proto, canonname, sa = request.param sock = socket.socket(af, socktype, proto) sock.bind(sa) sock.listen(5) try: yield sa finally: sock.close() class TestCheckPort: def test_check_port_listening(self, listening_addr): with pytest.raises(IOError): portend._check_port(*listening_addr[:2])
import socket import pytest import portend def socket_infos(): """ Generate addr infos for connections to localhost """ host = '' port = portend.find_available_local_port() return socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM) def id_for_info(info): af, = info[:1] return str(af) def build_addr_infos(): params = list(socket_infos()) ids = list(map(id_for_info, params)) return locals() @pytest.fixture(**build_addr_infos()) def listening_addr(request): af, socktype, proto, canonname, sa = request.param sock = socket.socket(af, socktype, proto) sock.bind(sa) sock.listen(5) try: yield sa finally: sock.close() @pytest.fixture(**build_addr_infos()) def nonlistening_addr(request): af, socktype, proto, canonname, sa = request.param return sa class TestCheckPort: def test_check_port_listening(self, listening_addr): with pytest.raises(IOError): portend._check_port(*listening_addr[:2]) def test_check_port_nonlistening(self, nonlistening_addr): portend._check_port(*nonlistening_addr[:2])
Add tests for nonlistening addresses as well.
Add tests for nonlistening addresses as well.
Python
mit
jaraco/portend
import socket import pytest import portend def socket_infos(): """ Generate addr infos for connections to localhost """ host = '' port = portend.find_available_local_port() return socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM) def id_for_info(info): af, = info[:1] return str(af) - def build_listening_infos(): + def build_addr_infos(): params = list(socket_infos()) ids = list(map(id_for_info, params)) return locals() - @pytest.fixture(**build_listening_infos()) + @pytest.fixture(**build_addr_infos()) def listening_addr(request): af, socktype, proto, canonname, sa = request.param sock = socket.socket(af, socktype, proto) sock.bind(sa) sock.listen(5) try: yield sa finally: sock.close() + @pytest.fixture(**build_addr_infos()) + def nonlistening_addr(request): + af, socktype, proto, canonname, sa = request.param + return sa + + class TestCheckPort: def test_check_port_listening(self, listening_addr): with pytest.raises(IOError): portend._check_port(*listening_addr[:2]) + def test_check_port_nonlistening(self, nonlistening_addr): + portend._check_port(*nonlistening_addr[:2]) +
Add tests for nonlistening addresses as well.
## Code Before: import socket import pytest import portend def socket_infos(): """ Generate addr infos for connections to localhost """ host = '' port = portend.find_available_local_port() return socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM) def id_for_info(info): af, = info[:1] return str(af) def build_listening_infos(): params = list(socket_infos()) ids = list(map(id_for_info, params)) return locals() @pytest.fixture(**build_listening_infos()) def listening_addr(request): af, socktype, proto, canonname, sa = request.param sock = socket.socket(af, socktype, proto) sock.bind(sa) sock.listen(5) try: yield sa finally: sock.close() class TestCheckPort: def test_check_port_listening(self, listening_addr): with pytest.raises(IOError): portend._check_port(*listening_addr[:2]) ## Instruction: Add tests for nonlistening addresses as well. ## Code After: import socket import pytest import portend def socket_infos(): """ Generate addr infos for connections to localhost """ host = '' port = portend.find_available_local_port() return socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM) def id_for_info(info): af, = info[:1] return str(af) def build_addr_infos(): params = list(socket_infos()) ids = list(map(id_for_info, params)) return locals() @pytest.fixture(**build_addr_infos()) def listening_addr(request): af, socktype, proto, canonname, sa = request.param sock = socket.socket(af, socktype, proto) sock.bind(sa) sock.listen(5) try: yield sa finally: sock.close() @pytest.fixture(**build_addr_infos()) def nonlistening_addr(request): af, socktype, proto, canonname, sa = request.param return sa class TestCheckPort: def test_check_port_listening(self, listening_addr): with pytest.raises(IOError): portend._check_port(*listening_addr[:2]) def test_check_port_nonlistening(self, nonlistening_addr): portend._check_port(*nonlistening_addr[:2])
... def build_addr_infos(): params = list(socket_infos()) ... @pytest.fixture(**build_addr_infos()) def listening_addr(request): ... @pytest.fixture(**build_addr_infos()) def nonlistening_addr(request): af, socktype, proto, canonname, sa = request.param return sa class TestCheckPort: ... portend._check_port(*listening_addr[:2]) def test_check_port_nonlistening(self, nonlistening_addr): portend._check_port(*nonlistening_addr[:2]) ...
5b215758adab39923399db98b5975fc76d389472
__init__.py
__init__.py
import configparser import optparse from blo import Blo if __name__ == '__main__': parser = optparse.OptionParser("usage: %prog [option] markdown_file.md") parser.add_option("-c", "--config", dest="config_file", default="./blo.cfg", type="string", help="specify configuration file path to run on") (options, args) = parser.parse_args() if len(args) != 1: parser.error("incorrect number of arguments") cfg_file = options.config_file B = Blo() # TODO: implement main routine of Blo. # blo [-c config_file] markdown_file.md # -- if no -c option then load config file from default path (current directory). # ---- if no configuration file on current directory blo said error. # 1. init database (database name from environment variable or configuration file) # 2. parse markdown file from command line argument. # -- if command line argument path is directory then it will do recursive in directory. # 3. generate html and commit to database pass
import optparse from blo import Blo if __name__ == '__main__': parser = optparse.OptionParser("usage: %prog [options] markdown_file.md") parser.add_option("-c", "--config", dest="config_file", default="./blo.cfg", type="string", help="specify configuration file path to run on") (options, args) = parser.parse_args() if len(args) != 1: parser.error("incorrect number of arguments") cfg_file = options.config_file blo_main = Blo(cfg_file) blo_main.insert_article(args[0]) print('%s complete process.'%('blo',))
Implement main section of blo package.
Implement main section of blo package.
Python
mit
10nin/blo,10nin/blo
- import configparser import optparse from blo import Blo if __name__ == '__main__': - parser = optparse.OptionParser("usage: %prog [option] markdown_file.md") + parser = optparse.OptionParser("usage: %prog [options] markdown_file.md") parser.add_option("-c", "--config", dest="config_file", default="./blo.cfg", type="string", help="specify configuration file path to run on") (options, args) = parser.parse_args() if len(args) != 1: parser.error("incorrect number of arguments") cfg_file = options.config_file - B = Blo() + blo_main = Blo(cfg_file) + blo_main.insert_article(args[0]) + print('%s complete process.'%('blo',)) - # TODO: implement main routine of Blo. - # blo [-c config_file] markdown_file.md - # -- if no -c option then load config file from default path (current directory). - # ---- if no configuration file on current directory blo said error. - # 1. init database (database name from environment variable or configuration file) - # 2. parse markdown file from command line argument. - # -- if command line argument path is directory then it will do recursive in directory. - # 3. generate html and commit to database - pass
Implement main section of blo package.
## Code Before: import configparser import optparse from blo import Blo if __name__ == '__main__': parser = optparse.OptionParser("usage: %prog [option] markdown_file.md") parser.add_option("-c", "--config", dest="config_file", default="./blo.cfg", type="string", help="specify configuration file path to run on") (options, args) = parser.parse_args() if len(args) != 1: parser.error("incorrect number of arguments") cfg_file = options.config_file B = Blo() # TODO: implement main routine of Blo. # blo [-c config_file] markdown_file.md # -- if no -c option then load config file from default path (current directory). # ---- if no configuration file on current directory blo said error. # 1. init database (database name from environment variable or configuration file) # 2. parse markdown file from command line argument. # -- if command line argument path is directory then it will do recursive in directory. # 3. generate html and commit to database pass ## Instruction: Implement main section of blo package. ## Code After: import optparse from blo import Blo if __name__ == '__main__': parser = optparse.OptionParser("usage: %prog [options] markdown_file.md") parser.add_option("-c", "--config", dest="config_file", default="./blo.cfg", type="string", help="specify configuration file path to run on") (options, args) = parser.parse_args() if len(args) != 1: parser.error("incorrect number of arguments") cfg_file = options.config_file blo_main = Blo(cfg_file) blo_main.insert_article(args[0]) print('%s complete process.'%('blo',))
// ... existing code ... import optparse // ... modified code ... if __name__ == '__main__': parser = optparse.OptionParser("usage: %prog [options] markdown_file.md") parser.add_option("-c", "--config", dest="config_file", ... blo_main = Blo(cfg_file) blo_main.insert_article(args[0]) print('%s complete process.'%('blo',)) // ... rest of the code ...
2201aaeffb93713adcdf20f5868b5a90b562efda
pages/models.py
pages/models.py
from django.db import models class Page(models.Model): def __str__(self): return self.name name = models.CharField(max_length=64, blank=False) name.help_text='Internal name of page' title = models.CharField(max_length=64, blank=True) title.help_text='Page title to display in titlebar of browser/tab' body = models.TextField(max_length=8192, blank=True) body.help_text='Page contents' head = models.TextField(max_length=1024, blank=True) head.help_text='Custom HTML to go in the <head> of the page' css = models.TextField(max_length=1024, blank=True) css.help_text='Custom CSS styles for the page' leftbar = models.TextField(max_length=1024, blank=True) leftbar.help_text='Left sidebar contents (use panels)' rightbar = models.TextField(max_length=1024, blank=True) rightbar.help_text='Right sidebar contents (use panels)'
from django.db import models class Page(models.Model): def __str__(self): return self.name name = models.CharField(max_length=64, blank=False) name.help_text='Internal name of page' title = models.CharField(max_length=64, blank=True) title.help_text='Page title to display in titlebar of browser/tab' body = models.TextField(max_length=16384, blank=True) body.help_text='Page contents' head = models.TextField(max_length=16384, blank=True) head.help_text='Custom HTML to go in the <head> of the page' css = models.TextField(max_length=16384, blank=True) css.help_text='Custom CSS styles for the page' leftbar = models.TextField(max_length=16384, blank=True) leftbar.help_text='Left sidebar contents (use panels)' rightbar = models.TextField(max_length=16384, blank=True) rightbar.help_text='Right sidebar contents (use panels)'
Increase character limit for pages
Increase character limit for pages Closes #70.
Python
isc
ashbc/tgrsite,ashbc/tgrsite,ashbc/tgrsite
from django.db import models class Page(models.Model): def __str__(self): return self.name name = models.CharField(max_length=64, blank=False) name.help_text='Internal name of page' title = models.CharField(max_length=64, blank=True) title.help_text='Page title to display in titlebar of browser/tab' - body = models.TextField(max_length=8192, blank=True) + body = models.TextField(max_length=16384, blank=True) body.help_text='Page contents' - head = models.TextField(max_length=1024, blank=True) + head = models.TextField(max_length=16384, blank=True) head.help_text='Custom HTML to go in the <head> of the page' - css = models.TextField(max_length=1024, blank=True) + css = models.TextField(max_length=16384, blank=True) css.help_text='Custom CSS styles for the page' - leftbar = models.TextField(max_length=1024, blank=True) + leftbar = models.TextField(max_length=16384, blank=True) leftbar.help_text='Left sidebar contents (use panels)' - rightbar = models.TextField(max_length=1024, blank=True) + rightbar = models.TextField(max_length=16384, blank=True) rightbar.help_text='Right sidebar contents (use panels)'
Increase character limit for pages
## Code Before: from django.db import models class Page(models.Model): def __str__(self): return self.name name = models.CharField(max_length=64, blank=False) name.help_text='Internal name of page' title = models.CharField(max_length=64, blank=True) title.help_text='Page title to display in titlebar of browser/tab' body = models.TextField(max_length=8192, blank=True) body.help_text='Page contents' head = models.TextField(max_length=1024, blank=True) head.help_text='Custom HTML to go in the <head> of the page' css = models.TextField(max_length=1024, blank=True) css.help_text='Custom CSS styles for the page' leftbar = models.TextField(max_length=1024, blank=True) leftbar.help_text='Left sidebar contents (use panels)' rightbar = models.TextField(max_length=1024, blank=True) rightbar.help_text='Right sidebar contents (use panels)' ## Instruction: Increase character limit for pages ## Code After: from django.db import models class Page(models.Model): def __str__(self): return self.name name = models.CharField(max_length=64, blank=False) name.help_text='Internal name of page' title = models.CharField(max_length=64, blank=True) title.help_text='Page title to display in titlebar of browser/tab' body = models.TextField(max_length=16384, blank=True) body.help_text='Page contents' head = models.TextField(max_length=16384, blank=True) head.help_text='Custom HTML to go in the <head> of the page' css = models.TextField(max_length=16384, blank=True) css.help_text='Custom CSS styles for the page' leftbar = models.TextField(max_length=16384, blank=True) leftbar.help_text='Left sidebar contents (use panels)' rightbar = models.TextField(max_length=16384, blank=True) rightbar.help_text='Right sidebar contents (use panels)'
# ... existing code ... body = models.TextField(max_length=16384, blank=True) body.help_text='Page contents' # ... modified code ... head = models.TextField(max_length=16384, blank=True) head.help_text='Custom HTML to go in the <head> of the page' ... css = models.TextField(max_length=16384, blank=True) css.help_text='Custom CSS styles for the page' ... leftbar = models.TextField(max_length=16384, blank=True) leftbar.help_text='Left sidebar contents (use panels)' rightbar = models.TextField(max_length=16384, blank=True) rightbar.help_text='Right sidebar contents (use panels)' # ... rest of the code ...
354af0bd82da57e718e9612ffb11e3b56d335fbf
projects/search_indexes.py
projects/search_indexes.py
import datetime import os from haystack.indexes import * from haystack import site from projects.models import File, ImportedFile from projects import constants class FileIndex(SearchIndex): text = CharField(document=True, use_template=True) author = CharField(model_attr='project__user') project = CharField(model_attr='project__name') title = CharField(model_attr='heading') def get_queryset(self): return File.objects.filter(project__status=constants.LIVE_STATUS) class ImportedFileIndex(SearchIndex): text = CharField(document=True) author = CharField(model_attr='project__user') project = CharField(model_attr='project__name') title = CharField(model_attr='name') def prepare_text(self, obj): full_path = obj.project.full_html_path to_read = os.path.join(full_path, obj.path.lstrip('/')) content = open(to_read, 'r').read() return content site.register(File, FileIndex) site.register(ImportedFile, ImportedFileIndex)
import datetime import os import codecs from haystack.indexes import * from haystack import site from projects.models import File, ImportedFile from projects import constants class FileIndex(SearchIndex): text = CharField(document=True, use_template=True) author = CharField(model_attr='project__user') project = CharField(model_attr='project__name') title = CharField(model_attr='heading') def get_queryset(self): return File.objects.filter(project__status=constants.LIVE_STATUS) class ImportedFileIndex(SearchIndex): text = CharField(document=True) author = CharField(model_attr='project__user') project = CharField(model_attr='project__name') title = CharField(model_attr='name') def prepare_text(self, obj): full_path = obj.project.full_html_path to_read = os.path.join(full_path, obj.path.lstrip('/')) content = codecs.open(to_read, encoding="utf-8", mode='r').read() return content site.register(File, FileIndex) site.register(ImportedFile, ImportedFileIndex)
Fix unicode fail in search indexing.
Fix unicode fail in search indexing.
Python
mit
atsuyim/readthedocs.org,tddv/readthedocs.org,singingwolfboy/readthedocs.org,raven47git/readthedocs.org,LukasBoersma/readthedocs.org,stevepiercy/readthedocs.org,johncosta/private-readthedocs.org,michaelmcandrew/readthedocs.org,espdev/readthedocs.org,wijerasa/readthedocs.org,Tazer/readthedocs.org,sid-kap/readthedocs.org,takluyver/readthedocs.org,stevepiercy/readthedocs.org,mhils/readthedocs.org,VishvajitP/readthedocs.org,cgourlay/readthedocs.org,agjohnson/readthedocs.org,sils1297/readthedocs.org,rtfd/readthedocs.org,dirn/readthedocs.org,mrshoki/readthedocs.org,soulshake/readthedocs.org,emawind84/readthedocs.org,emawind84/readthedocs.org,espdev/readthedocs.org,alex/readthedocs.org,istresearch/readthedocs.org,GovReady/readthedocs.org,soulshake/readthedocs.org,attakei/readthedocs-oauth,rtfd/readthedocs.org,rtfd/readthedocs.org,fujita-shintaro/readthedocs.org,gjtorikian/readthedocs.org,kenshinthebattosai/readthedocs.org,davidfischer/readthedocs.org,asampat3090/readthedocs.org,GovReady/readthedocs.org,pombredanne/readthedocs.org,SteveViss/readthedocs.org,attakei/readthedocs-oauth,agjohnson/readthedocs.org,sils1297/readthedocs.org,CedarLogic/readthedocs.org,laplaceliu/readthedocs.org,ojii/readthedocs.org,sid-kap/readthedocs.org,wanghaven/readthedocs.org,atsuyim/readthedocs.org,sunnyzwh/readthedocs.org,soulshake/readthedocs.org,kenwang76/readthedocs.org,Tazer/readthedocs.org,michaelmcandrew/readthedocs.org,asampat3090/readthedocs.org,agjohnson/readthedocs.org,Tazer/readthedocs.org,atsuyim/readthedocs.org,nyergler/pythonslides,jerel/readthedocs.org,atsuyim/readthedocs.org,nikolas/readthedocs.org,wanghaven/readthedocs.org,emawind84/readthedocs.org,wijerasa/readthedocs.org,safwanrahman/readthedocs.org,fujita-shintaro/readthedocs.org,mhils/readthedocs.org,mrshoki/readthedocs.org,mrshoki/readthedocs.org,istresearch/readthedocs.org,davidfischer/readthedocs.org,jerel/readthedocs.org,singingwolfboy/readthedocs.org,VishvajitP/readthedocs.org,davidfischer/readthedocs.org,istresearch/readthedocs.org,attakei/readthedocs-oauth,laplaceliu/readthedocs.org,tddv/readthedocs.org,nikolas/readthedocs.org,Tazer/readthedocs.org,sunnyzwh/readthedocs.org,techtonik/readthedocs.org,takluyver/readthedocs.org,attakei/readthedocs-oauth,titiushko/readthedocs.org,jerel/readthedocs.org,hach-que/readthedocs.org,kdkeyser/readthedocs.org,pombredanne/readthedocs.org,cgourlay/readthedocs.org,kenshinthebattosai/readthedocs.org,kdkeyser/readthedocs.org,royalwang/readthedocs.org,johncosta/private-readthedocs.org,safwanrahman/readthedocs.org,alex/readthedocs.org,dirn/readthedocs.org,michaelmcandrew/readthedocs.org,alex/readthedocs.org,techtonik/readthedocs.org,clarkperkins/readthedocs.org,kenwang76/readthedocs.org,sunnyzwh/readthedocs.org,asampat3090/readthedocs.org,titiushko/readthedocs.org,clarkperkins/readthedocs.org,sils1297/readthedocs.org,kenshinthebattosai/readthedocs.org,davidfischer/readthedocs.org,espdev/readthedocs.org,VishvajitP/readthedocs.org,GovReady/readthedocs.org,clarkperkins/readthedocs.org,d0ugal/readthedocs.org,nikolas/readthedocs.org,raven47git/readthedocs.org,hach-que/readthedocs.org,wanghaven/readthedocs.org,espdev/readthedocs.org,michaelmcandrew/readthedocs.org,nyergler/pythonslides,kdkeyser/readthedocs.org,sid-kap/readthedocs.org,titiushko/readthedocs.org,ojii/readthedocs.org,raven47git/readthedocs.org,KamranMackey/readthedocs.org,laplaceliu/readthedocs.org,takluyver/readthedocs.org,espdev/readthedocs.org,SteveViss/readthedocs.org,laplaceliu/readthedocs.org,alex/readthedocs.org,safwanrahman/readthedocs.org,royalwang/readthedocs.org,takluyver/readthedocs.org,ojii/readthedocs.org,tddv/readthedocs.org,jerel/readthedocs.org,gjtorikian/readthedocs.org,johncosta/private-readthedocs.org,Carreau/readthedocs.org,LukasBoersma/readthedocs.org,Carreau/readthedocs.org,raven47git/readthedocs.org,d0ugal/readthedocs.org,mhils/readthedocs.org,nyergler/pythonslides,techtonik/readthedocs.org,nikolas/readthedocs.org,royalwang/readthedocs.org,dirn/readthedocs.org,gjtorikian/readthedocs.org,kenwang76/readthedocs.org,CedarLogic/readthedocs.org,singingwolfboy/readthedocs.org,GovReady/readthedocs.org,Carreau/readthedocs.org,sid-kap/readthedocs.org,mrshoki/readthedocs.org,hach-que/readthedocs.org,ojii/readthedocs.org,LukasBoersma/readthedocs.org,titiushko/readthedocs.org,d0ugal/readthedocs.org,Carreau/readthedocs.org,soulshake/readthedocs.org,sunnyzwh/readthedocs.org,pombredanne/readthedocs.org,VishvajitP/readthedocs.org,cgourlay/readthedocs.org,sils1297/readthedocs.org,cgourlay/readthedocs.org,wijerasa/readthedocs.org,kenshinthebattosai/readthedocs.org,safwanrahman/readthedocs.org,asampat3090/readthedocs.org,CedarLogic/readthedocs.org,nyergler/pythonslides,agjohnson/readthedocs.org,kdkeyser/readthedocs.org,istresearch/readthedocs.org,d0ugal/readthedocs.org,KamranMackey/readthedocs.org,kenwang76/readthedocs.org,fujita-shintaro/readthedocs.org,SteveViss/readthedocs.org,SteveViss/readthedocs.org,CedarLogic/readthedocs.org,emawind84/readthedocs.org,dirn/readthedocs.org,rtfd/readthedocs.org,singingwolfboy/readthedocs.org,LukasBoersma/readthedocs.org,wijerasa/readthedocs.org,royalwang/readthedocs.org,stevepiercy/readthedocs.org,KamranMackey/readthedocs.org,wanghaven/readthedocs.org,stevepiercy/readthedocs.org,gjtorikian/readthedocs.org,mhils/readthedocs.org,clarkperkins/readthedocs.org,KamranMackey/readthedocs.org,fujita-shintaro/readthedocs.org,hach-que/readthedocs.org,techtonik/readthedocs.org
import datetime import os + import codecs + from haystack.indexes import * from haystack import site from projects.models import File, ImportedFile from projects import constants class FileIndex(SearchIndex): text = CharField(document=True, use_template=True) author = CharField(model_attr='project__user') project = CharField(model_attr='project__name') title = CharField(model_attr='heading') def get_queryset(self): return File.objects.filter(project__status=constants.LIVE_STATUS) class ImportedFileIndex(SearchIndex): text = CharField(document=True) author = CharField(model_attr='project__user') project = CharField(model_attr='project__name') title = CharField(model_attr='name') def prepare_text(self, obj): full_path = obj.project.full_html_path to_read = os.path.join(full_path, obj.path.lstrip('/')) - content = open(to_read, 'r').read() + content = codecs.open(to_read, encoding="utf-8", mode='r').read() return content site.register(File, FileIndex) site.register(ImportedFile, ImportedFileIndex)
Fix unicode fail in search indexing.
## Code Before: import datetime import os from haystack.indexes import * from haystack import site from projects.models import File, ImportedFile from projects import constants class FileIndex(SearchIndex): text = CharField(document=True, use_template=True) author = CharField(model_attr='project__user') project = CharField(model_attr='project__name') title = CharField(model_attr='heading') def get_queryset(self): return File.objects.filter(project__status=constants.LIVE_STATUS) class ImportedFileIndex(SearchIndex): text = CharField(document=True) author = CharField(model_attr='project__user') project = CharField(model_attr='project__name') title = CharField(model_attr='name') def prepare_text(self, obj): full_path = obj.project.full_html_path to_read = os.path.join(full_path, obj.path.lstrip('/')) content = open(to_read, 'r').read() return content site.register(File, FileIndex) site.register(ImportedFile, ImportedFileIndex) ## Instruction: Fix unicode fail in search indexing. ## Code After: import datetime import os import codecs from haystack.indexes import * from haystack import site from projects.models import File, ImportedFile from projects import constants class FileIndex(SearchIndex): text = CharField(document=True, use_template=True) author = CharField(model_attr='project__user') project = CharField(model_attr='project__name') title = CharField(model_attr='heading') def get_queryset(self): return File.objects.filter(project__status=constants.LIVE_STATUS) class ImportedFileIndex(SearchIndex): text = CharField(document=True) author = CharField(model_attr='project__user') project = CharField(model_attr='project__name') title = CharField(model_attr='name') def prepare_text(self, obj): full_path = obj.project.full_html_path to_read = os.path.join(full_path, obj.path.lstrip('/')) content = codecs.open(to_read, encoding="utf-8", mode='r').read() return content site.register(File, FileIndex) site.register(ImportedFile, ImportedFileIndex)
// ... existing code ... import os import codecs from haystack.indexes import * // ... modified code ... to_read = os.path.join(full_path, obj.path.lstrip('/')) content = codecs.open(to_read, encoding="utf-8", mode='r').read() return content // ... rest of the code ...
b73b8797c3c9c6c9aa92bd6873e15a5b717f4142
test/test_nap.py
test/test_nap.py
import unittest import requests from nap.api import Api class TestNap(unittest.TestCase): def test_unallowed_method(self): """Tries to use non-existent HTTP method""" api = Api('') # lambda trickery is necessary, because otherwise it would raise # AttributeError uncontrolled self.assertRaises(AttributeError, lambda: api.resource.nonexisting) def test_requests_raises_error(self): """Test that requests properly raises its own errors >>> requests.get('/kk') requests.exceptions.MissingSchema: Invalid URL u'/kk': No schema supplied. Perhaps you meant http:///kk? """ api = Api('') self.assertRaises(requests.exceptions.MissingSchema, api.resource.get) def test_resource_not_callable(self): """Make sure resource can't be called directly""" api = Api('') self.assertRaises(TypeError, api.resource)
from mock import MagicMock, patch import unittest import requests from nap.api import Api class TestNap(unittest.TestCase): def test_unallowed_method(self): """Tries to use non-existent HTTP method""" api = Api('') # lambda trickery is necessary, because otherwise it would raise # AttributeError uncontrolled self.assertRaises(AttributeError, lambda: api.resource.nonexisting) def test_requests_raises_error(self): """Test that requests properly raises its own errors >>> requests.get('/kk') requests.exceptions.MissingSchema: Invalid URL u'/kk': No schema supplied. Perhaps you meant http:///kk? """ api = Api('') self.assertRaises(requests.exceptions.MissingSchema, api.resource.get) def test_resource_not_callable(self): """Make sure resource can't be called directly""" api = Api('') self.assertRaises(TypeError, api.resource) @patch('requests.get') def test_default_parameters(self, requests_get): """Test default parameter behavior""" api = Api('', auth=('user', 'password')) requests.get = MagicMock(return_value=None) # Make sure defaults are passed for each request api.resource.get() requests.get.assert_called_with('/resource', auth=('user', 'password')) # Make sure single calls can override defaults api.resource.get(auth=('defaults', 'overriden')) requests.get.assert_called_with( '/resource', auth=('defaults', 'overriden') )
Add tests which test default parameters for nap api
Add tests which test default parameters for nap api
Python
mit
kimmobrunfeldt/nap
+ from mock import MagicMock, patch import unittest import requests from nap.api import Api class TestNap(unittest.TestCase): def test_unallowed_method(self): """Tries to use non-existent HTTP method""" api = Api('') # lambda trickery is necessary, because otherwise it would raise # AttributeError uncontrolled self.assertRaises(AttributeError, lambda: api.resource.nonexisting) def test_requests_raises_error(self): """Test that requests properly raises its own errors >>> requests.get('/kk') requests.exceptions.MissingSchema: Invalid URL u'/kk': No schema supplied. Perhaps you meant http:///kk? """ api = Api('') self.assertRaises(requests.exceptions.MissingSchema, api.resource.get) def test_resource_not_callable(self): """Make sure resource can't be called directly""" api = Api('') self.assertRaises(TypeError, api.resource) + @patch('requests.get') + def test_default_parameters(self, requests_get): + """Test default parameter behavior""" + api = Api('', auth=('user', 'password')) + requests.get = MagicMock(return_value=None) + + # Make sure defaults are passed for each request + api.resource.get() + requests.get.assert_called_with('/resource', auth=('user', 'password')) + + # Make sure single calls can override defaults + api.resource.get(auth=('defaults', 'overriden')) + requests.get.assert_called_with( + '/resource', + auth=('defaults', 'overriden') + ) +
Add tests which test default parameters for nap api
## Code Before: import unittest import requests from nap.api import Api class TestNap(unittest.TestCase): def test_unallowed_method(self): """Tries to use non-existent HTTP method""" api = Api('') # lambda trickery is necessary, because otherwise it would raise # AttributeError uncontrolled self.assertRaises(AttributeError, lambda: api.resource.nonexisting) def test_requests_raises_error(self): """Test that requests properly raises its own errors >>> requests.get('/kk') requests.exceptions.MissingSchema: Invalid URL u'/kk': No schema supplied. Perhaps you meant http:///kk? """ api = Api('') self.assertRaises(requests.exceptions.MissingSchema, api.resource.get) def test_resource_not_callable(self): """Make sure resource can't be called directly""" api = Api('') self.assertRaises(TypeError, api.resource) ## Instruction: Add tests which test default parameters for nap api ## Code After: from mock import MagicMock, patch import unittest import requests from nap.api import Api class TestNap(unittest.TestCase): def test_unallowed_method(self): """Tries to use non-existent HTTP method""" api = Api('') # lambda trickery is necessary, because otherwise it would raise # AttributeError uncontrolled self.assertRaises(AttributeError, lambda: api.resource.nonexisting) def test_requests_raises_error(self): """Test that requests properly raises its own errors >>> requests.get('/kk') requests.exceptions.MissingSchema: Invalid URL u'/kk': No schema supplied. Perhaps you meant http:///kk? """ api = Api('') self.assertRaises(requests.exceptions.MissingSchema, api.resource.get) def test_resource_not_callable(self): """Make sure resource can't be called directly""" api = Api('') self.assertRaises(TypeError, api.resource) @patch('requests.get') def test_default_parameters(self, requests_get): """Test default parameter behavior""" api = Api('', auth=('user', 'password')) requests.get = MagicMock(return_value=None) # Make sure defaults are passed for each request api.resource.get() requests.get.assert_called_with('/resource', auth=('user', 'password')) # Make sure single calls can override defaults api.resource.get(auth=('defaults', 'overriden')) requests.get.assert_called_with( '/resource', auth=('defaults', 'overriden') )
// ... existing code ... from mock import MagicMock, patch import unittest // ... modified code ... self.assertRaises(TypeError, api.resource) @patch('requests.get') def test_default_parameters(self, requests_get): """Test default parameter behavior""" api = Api('', auth=('user', 'password')) requests.get = MagicMock(return_value=None) # Make sure defaults are passed for each request api.resource.get() requests.get.assert_called_with('/resource', auth=('user', 'password')) # Make sure single calls can override defaults api.resource.get(auth=('defaults', 'overriden')) requests.get.assert_called_with( '/resource', auth=('defaults', 'overriden') ) // ... rest of the code ...
74a78fc5a48ce834390590031d3d054214609ec0
djangocms_blog/cms_app.py
djangocms_blog/cms_app.py
from cms.app_base import CMSApp from cms.apphook_pool import apphook_pool from django.utils.translation import ugettext_lazy as _, get_language from .menu import BlogCategoryMenu class BlogApp(CMSApp): name = _('Blog') urls = ['djangocms_blog.urls'] app_name = 'djangocms_blog' menus = [BlogCategoryMenu] apphook_pool.register(BlogApp)
from cms.app_base import CMSApp from cms.apphook_pool import apphook_pool from cms.menu_bases import CMSAttachMenu from menus.base import NavigationNode from menus.menu_pool import menu_pool from django.core.urlresolvers import reverse from django.utils.translation import ugettext_lazy as _, get_language from .models import BlogCategory class BlogCategoryMenu(CMSAttachMenu): name = _('Blog Category menu') def get_nodes(self, request): nodes = [] qs = BlogCategory.objects.translated(get_language()) qs = qs.order_by('parent_id', 'translations__name').distinct() for category in qs: kwargs = { 'category': category.slug } node = NavigationNode( category.name, reverse('djangocms_blog:posts-category', kwargs=kwargs), category.pk, category.parent_id ) nodes.append(node) return nodes menu_pool.register_menu(BlogCategoryMenu) class BlogApp(CMSApp): name = _('Blog') urls = ['djangocms_blog.urls'] app_name = 'djangocms_blog' menus = [BlogCategoryMenu] apphook_pool.register(BlogApp)
Attach category menu to CMSApp
Attach category menu to CMSApp
Python
bsd-3-clause
motleytech/djangocms-blog,vnavascues/djangocms-blog,mistalaba/djangocms-blog,marty3d/djangocms-blog,EnglishConnection/djangocms-blog,jedie/djangocms-blog,kriwil/djangocms-blog,skirsdeda/djangocms-blog,nephila/djangocms-blog,mistalaba/djangocms-blog,sephii/djangocms-blog,dapeng0802/djangocms-blog,nephila/djangocms-blog,ImaginaryLandscape/djangocms-blog,britny/djangocms-blog,ImaginaryLandscape/djangocms-blog,jedie/djangocms-blog,skirsdeda/djangocms-blog,nephila/djangocms-blog,skirsdeda/djangocms-blog,EnglishConnection/djangocms-blog,dapeng0802/djangocms-blog,kriwil/djangocms-blog,sephii/djangocms-blog,vnavascues/djangocms-blog,britny/djangocms-blog,motleytech/djangocms-blog,marty3d/djangocms-blog
from cms.app_base import CMSApp from cms.apphook_pool import apphook_pool + from cms.menu_bases import CMSAttachMenu + from menus.base import NavigationNode + from menus.menu_pool import menu_pool + from django.core.urlresolvers import reverse from django.utils.translation import ugettext_lazy as _, get_language - from .menu import BlogCategoryMenu + from .models import BlogCategory + + class BlogCategoryMenu(CMSAttachMenu): + name = _('Blog Category menu') + + def get_nodes(self, request): + nodes = [] + qs = BlogCategory.objects.translated(get_language()) + qs = qs.order_by('parent_id', 'translations__name').distinct() + for category in qs: + kwargs = { 'category': category.slug } + node = NavigationNode( + category.name, + reverse('djangocms_blog:posts-category', kwargs=kwargs), + category.pk, + category.parent_id + ) + nodes.append(node) + return nodes + + menu_pool.register_menu(BlogCategoryMenu) class BlogApp(CMSApp): name = _('Blog') urls = ['djangocms_blog.urls'] app_name = 'djangocms_blog' menus = [BlogCategoryMenu] apphook_pool.register(BlogApp)
Attach category menu to CMSApp
## Code Before: from cms.app_base import CMSApp from cms.apphook_pool import apphook_pool from django.utils.translation import ugettext_lazy as _, get_language from .menu import BlogCategoryMenu class BlogApp(CMSApp): name = _('Blog') urls = ['djangocms_blog.urls'] app_name = 'djangocms_blog' menus = [BlogCategoryMenu] apphook_pool.register(BlogApp) ## Instruction: Attach category menu to CMSApp ## Code After: from cms.app_base import CMSApp from cms.apphook_pool import apphook_pool from cms.menu_bases import CMSAttachMenu from menus.base import NavigationNode from menus.menu_pool import menu_pool from django.core.urlresolvers import reverse from django.utils.translation import ugettext_lazy as _, get_language from .models import BlogCategory class BlogCategoryMenu(CMSAttachMenu): name = _('Blog Category menu') def get_nodes(self, request): nodes = [] qs = BlogCategory.objects.translated(get_language()) qs = qs.order_by('parent_id', 'translations__name').distinct() for category in qs: kwargs = { 'category': category.slug } node = NavigationNode( category.name, reverse('djangocms_blog:posts-category', kwargs=kwargs), category.pk, category.parent_id ) nodes.append(node) return nodes menu_pool.register_menu(BlogCategoryMenu) class BlogApp(CMSApp): name = _('Blog') urls = ['djangocms_blog.urls'] app_name = 'djangocms_blog' menus = [BlogCategoryMenu] apphook_pool.register(BlogApp)
# ... existing code ... from cms.apphook_pool import apphook_pool from cms.menu_bases import CMSAttachMenu from menus.base import NavigationNode from menus.menu_pool import menu_pool from django.core.urlresolvers import reverse from django.utils.translation import ugettext_lazy as _, get_language from .models import BlogCategory class BlogCategoryMenu(CMSAttachMenu): name = _('Blog Category menu') def get_nodes(self, request): nodes = [] qs = BlogCategory.objects.translated(get_language()) qs = qs.order_by('parent_id', 'translations__name').distinct() for category in qs: kwargs = { 'category': category.slug } node = NavigationNode( category.name, reverse('djangocms_blog:posts-category', kwargs=kwargs), category.pk, category.parent_id ) nodes.append(node) return nodes menu_pool.register_menu(BlogCategoryMenu) # ... rest of the code ...
b0e614ea7ac59b6b869155b9ac8ea370cb56f83d
cardinal/decorators.py
cardinal/decorators.py
import functools def command(triggers): def wrap(f): @functools.wraps(f) def inner(*args, **kwargs): return f(*args, **kwargs) inner.commands = triggers return inner return wrap def help(line): def wrap(f): @functools.wraps(f) def inner(*args, **kwargs): return f(*args, **kwargs) # Create help list or prepend to it if not hasattr(inner, 'help'): inner.help = [line] else: inner.help.insert(0, line) return inner return wrap
import functools def command(triggers): if isinstance(triggers, basestring): triggers = [triggers] def wrap(f): @functools.wraps(f) def inner(*args, **kwargs): return f(*args, **kwargs) inner.commands = triggers return inner return wrap def help(line): def wrap(f): @functools.wraps(f) def inner(*args, **kwargs): return f(*args, **kwargs) # Create help list or prepend to it if not hasattr(inner, 'help'): inner.help = [line] else: inner.help.insert(0, line) return inner return wrap
Allow for single trigger in @command decorator
Allow for single trigger in @command decorator
Python
mit
BiohZn/Cardinal,JohnMaguire/Cardinal
import functools def command(triggers): + if isinstance(triggers, basestring): + triggers = [triggers] + def wrap(f): @functools.wraps(f) def inner(*args, **kwargs): return f(*args, **kwargs) inner.commands = triggers return inner return wrap def help(line): def wrap(f): @functools.wraps(f) def inner(*args, **kwargs): return f(*args, **kwargs) # Create help list or prepend to it if not hasattr(inner, 'help'): inner.help = [line] else: inner.help.insert(0, line) return inner return wrap
Allow for single trigger in @command decorator
## Code Before: import functools def command(triggers): def wrap(f): @functools.wraps(f) def inner(*args, **kwargs): return f(*args, **kwargs) inner.commands = triggers return inner return wrap def help(line): def wrap(f): @functools.wraps(f) def inner(*args, **kwargs): return f(*args, **kwargs) # Create help list or prepend to it if not hasattr(inner, 'help'): inner.help = [line] else: inner.help.insert(0, line) return inner return wrap ## Instruction: Allow for single trigger in @command decorator ## Code After: import functools def command(triggers): if isinstance(triggers, basestring): triggers = [triggers] def wrap(f): @functools.wraps(f) def inner(*args, **kwargs): return f(*args, **kwargs) inner.commands = triggers return inner return wrap def help(line): def wrap(f): @functools.wraps(f) def inner(*args, **kwargs): return f(*args, **kwargs) # Create help list or prepend to it if not hasattr(inner, 'help'): inner.help = [line] else: inner.help.insert(0, line) return inner return wrap
... def command(triggers): if isinstance(triggers, basestring): triggers = [triggers] def wrap(f): ...
8715324d1c466d617fb832841413025b464b7012
onitu/drivers/dropbox/tests/driver.py
onitu/drivers/dropbox/tests/driver.py
import os from path import path from tests.utils.testdriver import TestDriver from tests.utils.tempdirs import dirs from onitu.drivers.dropbox.libDropbox import LibDropbox class Driver(TestDriver): def __init__(self, *args, **options): if 'root' not in options: options['root'] = dirs.create() if 'key' not in options: options['key'] = "38jd72msqedx5n9" if 'secret' not in options: options['secret'] = "g4favy0bgjstt2w" if 'changes_timer' not in options: options['changes_timer'] = 600.0 self.google_drive = LibDrive(options) super(Driver, self).__init__('dropbox', *args, **options) @property def root(self): return path(self.options['root']) def close(self): self.drop.delete_file('/') def mkdir(self, subdirs): self.drop.create_dir(subdirs+"/toto") def write(self, filename, content): metadata = {"size": len(content), "filename": filename} self.drop.upload_chunk(metadata, 0, content, len(content)) def generate(self, filename, size): self.write(filename, os.urandom(size)) def unlink(self, filename): self.drop.delete_file(filename) def checksum(self, filename): return "LOL----LOL"
import os from path import path from tests.utils.testdriver import TestDriver from tests.utils.tempdirs import dirs from onitu.drivers.dropbox.dropboxDriver import dropboxDriver class Driver(TestDriver): def __init__(self, *args, **options): if 'root' not in options: options['root'] = dirs.create() if 'key' not in options: options['key'] = "38jd72msqedx5n9" if 'secret' not in options: options['secret'] = "g4favy0bgjstt2w" if 'changes_timer' not in options: options['changes_timer'] = 600.0 self.dropbox = dropboxDriver(options) super(Driver, self).__init__('dropbox', *args, **options) @property def root(self): return path(self.options['root']) def close(self): self.drop.delete_file('/') def mkdir(self, subdirs): self.drop.create_dir(subdirs+"/toto") def write(self, filename, content): metadata = {"size": len(content), "filename": filename} self.drop.upload_chunk(metadata, 0, content, len(content)) def generate(self, filename, size): self.write(filename, os.urandom(size)) def unlink(self, filename): self.drop.delete_file(filename) def checksum(self, filename): return "LOL----LOL"
Fix the imports in the tests of dropbox
Fix the imports in the tests of dropbox
Python
mit
onitu/onitu,onitu/onitu,onitu/onitu
import os from path import path from tests.utils.testdriver import TestDriver from tests.utils.tempdirs import dirs - from onitu.drivers.dropbox.libDropbox import LibDropbox + from onitu.drivers.dropbox.dropboxDriver import dropboxDriver class Driver(TestDriver): def __init__(self, *args, **options): if 'root' not in options: options['root'] = dirs.create() if 'key' not in options: options['key'] = "38jd72msqedx5n9" if 'secret' not in options: options['secret'] = "g4favy0bgjstt2w" if 'changes_timer' not in options: options['changes_timer'] = 600.0 - self.google_drive = LibDrive(options) + self.dropbox = dropboxDriver(options) super(Driver, self).__init__('dropbox', *args, **options) @property def root(self): return path(self.options['root']) def close(self): self.drop.delete_file('/') def mkdir(self, subdirs): self.drop.create_dir(subdirs+"/toto") def write(self, filename, content): metadata = {"size": len(content), "filename": filename} self.drop.upload_chunk(metadata, 0, content, len(content)) def generate(self, filename, size): self.write(filename, os.urandom(size)) def unlink(self, filename): self.drop.delete_file(filename) def checksum(self, filename): return "LOL----LOL"
Fix the imports in the tests of dropbox
## Code Before: import os from path import path from tests.utils.testdriver import TestDriver from tests.utils.tempdirs import dirs from onitu.drivers.dropbox.libDropbox import LibDropbox class Driver(TestDriver): def __init__(self, *args, **options): if 'root' not in options: options['root'] = dirs.create() if 'key' not in options: options['key'] = "38jd72msqedx5n9" if 'secret' not in options: options['secret'] = "g4favy0bgjstt2w" if 'changes_timer' not in options: options['changes_timer'] = 600.0 self.google_drive = LibDrive(options) super(Driver, self).__init__('dropbox', *args, **options) @property def root(self): return path(self.options['root']) def close(self): self.drop.delete_file('/') def mkdir(self, subdirs): self.drop.create_dir(subdirs+"/toto") def write(self, filename, content): metadata = {"size": len(content), "filename": filename} self.drop.upload_chunk(metadata, 0, content, len(content)) def generate(self, filename, size): self.write(filename, os.urandom(size)) def unlink(self, filename): self.drop.delete_file(filename) def checksum(self, filename): return "LOL----LOL" ## Instruction: Fix the imports in the tests of dropbox ## Code After: import os from path import path from tests.utils.testdriver import TestDriver from tests.utils.tempdirs import dirs from onitu.drivers.dropbox.dropboxDriver import dropboxDriver class Driver(TestDriver): def __init__(self, *args, **options): if 'root' not in options: options['root'] = dirs.create() if 'key' not in options: options['key'] = "38jd72msqedx5n9" if 'secret' not in options: options['secret'] = "g4favy0bgjstt2w" if 'changes_timer' not in options: options['changes_timer'] = 600.0 self.dropbox = dropboxDriver(options) super(Driver, self).__init__('dropbox', *args, **options) @property def root(self): return path(self.options['root']) def close(self): self.drop.delete_file('/') def mkdir(self, subdirs): self.drop.create_dir(subdirs+"/toto") def write(self, filename, content): metadata = {"size": len(content), "filename": filename} self.drop.upload_chunk(metadata, 0, content, len(content)) def generate(self, filename, size): self.write(filename, os.urandom(size)) def unlink(self, filename): self.drop.delete_file(filename) def checksum(self, filename): return "LOL----LOL"
... from tests.utils.tempdirs import dirs from onitu.drivers.dropbox.dropboxDriver import dropboxDriver ... options['changes_timer'] = 600.0 self.dropbox = dropboxDriver(options) super(Driver, self).__init__('dropbox', ...
b016fad5d55993b064a1c4d15fd281f439045491
gateway/camera/device.py
gateway/camera/device.py
from gateway import net class CameraDevice(object): def __init__(self, stream, address): self.resolution = None self.framerate = None self.__stream = stream self.__address = address def send(self, opcode, body=None): packet = net.encode_packet(opcode, body) yield self.__stream.write(packet)
from tornado import gen from gateway import net class CameraDevice(object): def __init__(self, stream, address): self.resolution = None self.framerate = None self.__stream = stream self.__address = address @gen.coroutine def send(self, opcode, body=None): packet = net.encode_packet(opcode, body) yield self.__stream.write(packet)
Fix CameraDevice's send method is not called
Fix CameraDevice's send method is not called Add send method @gen.coroutine decorator
Python
mit
walkover/auto-tracking-cctv-gateway
+ from tornado import gen + from gateway import net class CameraDevice(object): def __init__(self, stream, address): self.resolution = None self.framerate = None self.__stream = stream self.__address = address + @gen.coroutine def send(self, opcode, body=None): packet = net.encode_packet(opcode, body) yield self.__stream.write(packet)
Fix CameraDevice's send method is not called
## Code Before: from gateway import net class CameraDevice(object): def __init__(self, stream, address): self.resolution = None self.framerate = None self.__stream = stream self.__address = address def send(self, opcode, body=None): packet = net.encode_packet(opcode, body) yield self.__stream.write(packet) ## Instruction: Fix CameraDevice's send method is not called ## Code After: from tornado import gen from gateway import net class CameraDevice(object): def __init__(self, stream, address): self.resolution = None self.framerate = None self.__stream = stream self.__address = address @gen.coroutine def send(self, opcode, body=None): packet = net.encode_packet(opcode, body) yield self.__stream.write(packet)
# ... existing code ... from tornado import gen from gateway import net # ... modified code ... @gen.coroutine def send(self, opcode, body=None): # ... rest of the code ...
de613623c638b923a6bbfb6c33c373794d654000
setup.py
setup.py
from distutils.core import setup setup( name='django_dust', description='Distributed Upload STorage for Django. A file backend that mirrors all incoming media files to several servers', packages=[ 'django_dust', 'django_dust.management', 'django_dust.management.commands', 'django_dust.backends' ], )
from distutils.core import setup import os.path with open(os.path.join(os.path.dirname(__file__), 'README.md')) as f: long_description = f.read().partition('\n\n\n')[0].partition('\n\n')[2] setup( name='django_dust', version='0.1', description='Distributed Upload STorage for Django, a file backend ' 'that mirrors all incoming media files to several servers', long_description=long_description, packages=[ 'django_dust', 'django_dust.backends', 'django_dust.management', 'django_dust.management.commands', ], classifiers = [ "Development Status :: 3 - Alpha", "Environment :: Web Environment", "Framework :: Django", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Programming Language :: Python", "Topic :: Internet :: WWW/HTTP :: Site Management", ], )
Add version, long description and classifiers.
Add version, long description and classifiers.
Python
bsd-3-clause
aaugustin/django-resto
from distutils.core import setup + import os.path + + with open(os.path.join(os.path.dirname(__file__), 'README.md')) as f: + long_description = f.read().partition('\n\n\n')[0].partition('\n\n')[2] setup( - name='django_dust', + name='django_dust', - description='Distributed Upload STorage for Django. A file backend that mirrors all incoming media files to several servers', + version='0.1', + description='Distributed Upload STorage for Django, a file backend ' + 'that mirrors all incoming media files to several servers', + long_description=long_description, packages=[ 'django_dust', + 'django_dust.backends', 'django_dust.management', 'django_dust.management.commands', - 'django_dust.backends' + ], + classifiers = [ + "Development Status :: 3 - Alpha", + "Environment :: Web Environment", + "Framework :: Django", + "Intended Audience :: Developers", + "License :: OSI Approved :: BSD License", + "Operating System :: OS Independent", + "Programming Language :: Python", + "Topic :: Internet :: WWW/HTTP :: Site Management", ], )
Add version, long description and classifiers.
## Code Before: from distutils.core import setup setup( name='django_dust', description='Distributed Upload STorage for Django. A file backend that mirrors all incoming media files to several servers', packages=[ 'django_dust', 'django_dust.management', 'django_dust.management.commands', 'django_dust.backends' ], ) ## Instruction: Add version, long description and classifiers. ## Code After: from distutils.core import setup import os.path with open(os.path.join(os.path.dirname(__file__), 'README.md')) as f: long_description = f.read().partition('\n\n\n')[0].partition('\n\n')[2] setup( name='django_dust', version='0.1', description='Distributed Upload STorage for Django, a file backend ' 'that mirrors all incoming media files to several servers', long_description=long_description, packages=[ 'django_dust', 'django_dust.backends', 'django_dust.management', 'django_dust.management.commands', ], classifiers = [ "Development Status :: 3 - Alpha", "Environment :: Web Environment", "Framework :: Django", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Programming Language :: Python", "Topic :: Internet :: WWW/HTTP :: Site Management", ], )
# ... existing code ... from distutils.core import setup import os.path with open(os.path.join(os.path.dirname(__file__), 'README.md')) as f: long_description = f.read().partition('\n\n\n')[0].partition('\n\n')[2] # ... modified code ... setup( name='django_dust', version='0.1', description='Distributed Upload STorage for Django, a file backend ' 'that mirrors all incoming media files to several servers', long_description=long_description, packages=[ ... 'django_dust', 'django_dust.backends', 'django_dust.management', ... 'django_dust.management.commands', ], classifiers = [ "Development Status :: 3 - Alpha", "Environment :: Web Environment", "Framework :: Django", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Programming Language :: Python", "Topic :: Internet :: WWW/HTTP :: Site Management", ], # ... rest of the code ...
a6702e839eec2b4d6d75f4126ed975456e9795dc
contacts/middleware.py
contacts/middleware.py
import logging from django.http import Http404 from gargoyle import gargoyle from contacts.models import Book sentry = logging.getLogger('sentry') class ContactBookMiddleware(object): def process_view(self, request, view_func, view_args, view_kwargs): if hasattr(request, 'user'): if request.user.is_authenticated(): books = Book.objects.filter_for_user(request.user) request.current_book = None if gargoyle.is_active('multi_book', request): request.books = books request.current_book = books[0] if 'book' in view_kwargs: current_book = request.books.filter(id=view_kwargs['book']) if current_book: request.current_book = current_book else: return Http404 else: if books: request.current_book = books[0] else: request.current_book = None sentry.error("No book found for user", exc_info=True, extra={"user": user} ) if ( gargoyle.is_active('enable_payments', request) and request.current_book ): request.can_invite = ( request.current_book.plan and not request.current_book.plan.startswith('basic') ) else: request.can_invite = True
import logging from django.http import Http404 from gargoyle import gargoyle from contacts.models import Book sentry = logging.getLogger('sentry') class ContactBookMiddleware(object): def process_view(self, request, view_func, view_args, view_kwargs): # CONTRACT: At the end of this, if the user is authenticate, # request.current_book _must_ be populated with a valid book, and # request.books _must_ be a list of Books with length greater than 1. if hasattr(request, 'user'): if request.user.is_authenticated(): request.books = Book.objects.filter_for_user(request.user) request.current_book = None if request.books: if 'book' in view_kwargs: current_book = request.books.filter(id=view_kwargs['book']) if current_book: request.current_book = current_book else: return Http404 else: request.current_book = request.books[0] else: sentry.error("No book found for user", exc_info=True, extra={"user": user} ) request.current_book = Book.objects.create_for_user(request.user) request.books = Book.objects.filter_for_user(request.user) if ( gargoyle.is_active('enable_payments', request) and request.current_book ): request.can_invite = ( request.current_book.plan and not request.current_book.plan.startswith('basic') ) else: request.can_invite = True
Update ContactBook Middleware to obey contract
Update ContactBook Middleware to obey contract
Python
mit
phildini/logtacts,phildini/logtacts,phildini/logtacts,phildini/logtacts,phildini/logtacts
import logging from django.http import Http404 from gargoyle import gargoyle from contacts.models import Book sentry = logging.getLogger('sentry') class ContactBookMiddleware(object): def process_view(self, request, view_func, view_args, view_kwargs): - + # CONTRACT: At the end of this, if the user is authenticate, + # request.current_book _must_ be populated with a valid book, and + # request.books _must_ be a list of Books with length greater than 1. if hasattr(request, 'user'): if request.user.is_authenticated(): - books = Book.objects.filter_for_user(request.user) + request.books = Book.objects.filter_for_user(request.user) request.current_book = None - if gargoyle.is_active('multi_book', request): - request.books = books + if request.books: - request.current_book = books[0] if 'book' in view_kwargs: current_book = request.books.filter(id=view_kwargs['book']) if current_book: request.current_book = current_book else: return Http404 + else: + request.current_book = request.books[0] else: - if books: - request.current_book = books[0] - else: - request.current_book = None - sentry.error("No book found for user", exc_info=True, + sentry.error("No book found for user", exc_info=True, - extra={"user": user} + extra={"user": user} - ) + ) + request.current_book = Book.objects.create_for_user(request.user) + request.books = Book.objects.filter_for_user(request.user) + if ( gargoyle.is_active('enable_payments', request) and request.current_book ): request.can_invite = ( request.current_book.plan and not request.current_book.plan.startswith('basic') ) else: request.can_invite = True
Update ContactBook Middleware to obey contract
## Code Before: import logging from django.http import Http404 from gargoyle import gargoyle from contacts.models import Book sentry = logging.getLogger('sentry') class ContactBookMiddleware(object): def process_view(self, request, view_func, view_args, view_kwargs): if hasattr(request, 'user'): if request.user.is_authenticated(): books = Book.objects.filter_for_user(request.user) request.current_book = None if gargoyle.is_active('multi_book', request): request.books = books request.current_book = books[0] if 'book' in view_kwargs: current_book = request.books.filter(id=view_kwargs['book']) if current_book: request.current_book = current_book else: return Http404 else: if books: request.current_book = books[0] else: request.current_book = None sentry.error("No book found for user", exc_info=True, extra={"user": user} ) if ( gargoyle.is_active('enable_payments', request) and request.current_book ): request.can_invite = ( request.current_book.plan and not request.current_book.plan.startswith('basic') ) else: request.can_invite = True ## Instruction: Update ContactBook Middleware to obey contract ## Code After: import logging from django.http import Http404 from gargoyle import gargoyle from contacts.models import Book sentry = logging.getLogger('sentry') class ContactBookMiddleware(object): def process_view(self, request, view_func, view_args, view_kwargs): # CONTRACT: At the end of this, if the user is authenticate, # request.current_book _must_ be populated with a valid book, and # request.books _must_ be a list of Books with length greater than 1. if hasattr(request, 'user'): if request.user.is_authenticated(): request.books = Book.objects.filter_for_user(request.user) request.current_book = None if request.books: if 'book' in view_kwargs: current_book = request.books.filter(id=view_kwargs['book']) if current_book: request.current_book = current_book else: return Http404 else: request.current_book = request.books[0] else: sentry.error("No book found for user", exc_info=True, extra={"user": user} ) request.current_book = Book.objects.create_for_user(request.user) request.books = Book.objects.filter_for_user(request.user) if ( gargoyle.is_active('enable_payments', request) and request.current_book ): request.can_invite = ( request.current_book.plan and not request.current_book.plan.startswith('basic') ) else: request.can_invite = True
# ... existing code ... def process_view(self, request, view_func, view_args, view_kwargs): # CONTRACT: At the end of this, if the user is authenticate, # request.current_book _must_ be populated with a valid book, and # request.books _must_ be a list of Books with length greater than 1. if hasattr(request, 'user'): # ... modified code ... if request.user.is_authenticated(): request.books = Book.objects.filter_for_user(request.user) request.current_book = None if request.books: if 'book' in view_kwargs: ... return Http404 else: request.current_book = request.books[0] else: sentry.error("No book found for user", exc_info=True, extra={"user": user} ) request.current_book = Book.objects.create_for_user(request.user) request.books = Book.objects.filter_for_user(request.user) if ( # ... rest of the code ...
f3eb6cbc0f518ed8ec6098d3dfdd205ed734022c
eval_kernel/eval_kernel.py
eval_kernel/eval_kernel.py
from __future__ import print_function from jupyter_kernel import MagicKernel class EvalKernel(MagicKernel): implementation = 'Eval' implementation_version = '1.0' language = 'python' language_version = '0.1' banner = "Eval kernel - evaluates simple Python statements and expressions" env = {} def get_usage(self): return "This is a usage statement." def set_variable(self, name, value): """ Set a variable in the kernel language. """ self.env[name] = value def get_variable(self, name): """ Get a variable from the kernel language. """ return self.env.get(name, None) def do_execute_direct(self, code): python_magic = self.line_magics['python'] resp = python_magic.eval(code.strip()) if not resp is None: self.Print(str(resp)) def get_completions(self, token): python_magic = self.line_magics['python'] return python_magic.get_completions(token) def get_kernel_help_on(self, expr, level=0): python_magic = self.line_magics['python'] return python_magic.get_help_on(expr, level) if __name__ == '__main__': from IPython.kernel.zmq.kernelapp import IPKernelApp IPKernelApp.launch_instance(kernel_class=EvalKernel)
from __future__ import print_function from jupyter_kernel import MagicKernel class EvalKernel(MagicKernel): implementation = 'Eval' implementation_version = '1.0' language = 'python' language_version = '0.1' banner = "Eval kernel - evaluates simple Python statements and expressions" env = {} def get_usage(self): return "This is a usage statement." def set_variable(self, name, value): """ Set a variable in the kernel language. """ self.env[name] = value def get_variable(self, name): """ Get a variable from the kernel language. """ return self.env.get(name, None) def do_execute_direct(self, code): python_magic = self.line_magics['python'] return python_magic.eval(code.strip()) def get_completions(self, token): python_magic = self.line_magics['python'] return python_magic.get_completions(token) def get_kernel_help_on(self, expr, level=0): python_magic = self.line_magics['python'] return python_magic.get_help_on(expr, level) if __name__ == '__main__': from IPython.kernel.zmq.kernelapp import IPKernelApp IPKernelApp.launch_instance(kernel_class=EvalKernel)
Return python eval instead of printing it
Return python eval instead of printing it
Python
bsd-3-clause
Calysto/metakernel
from __future__ import print_function from jupyter_kernel import MagicKernel class EvalKernel(MagicKernel): implementation = 'Eval' implementation_version = '1.0' language = 'python' language_version = '0.1' banner = "Eval kernel - evaluates simple Python statements and expressions" env = {} def get_usage(self): return "This is a usage statement." def set_variable(self, name, value): """ Set a variable in the kernel language. """ self.env[name] = value def get_variable(self, name): """ Get a variable from the kernel language. """ return self.env.get(name, None) def do_execute_direct(self, code): python_magic = self.line_magics['python'] - resp = python_magic.eval(code.strip()) + return python_magic.eval(code.strip()) - if not resp is None: - self.Print(str(resp)) def get_completions(self, token): python_magic = self.line_magics['python'] return python_magic.get_completions(token) def get_kernel_help_on(self, expr, level=0): python_magic = self.line_magics['python'] return python_magic.get_help_on(expr, level) if __name__ == '__main__': from IPython.kernel.zmq.kernelapp import IPKernelApp IPKernelApp.launch_instance(kernel_class=EvalKernel)
Return python eval instead of printing it
## Code Before: from __future__ import print_function from jupyter_kernel import MagicKernel class EvalKernel(MagicKernel): implementation = 'Eval' implementation_version = '1.0' language = 'python' language_version = '0.1' banner = "Eval kernel - evaluates simple Python statements and expressions" env = {} def get_usage(self): return "This is a usage statement." def set_variable(self, name, value): """ Set a variable in the kernel language. """ self.env[name] = value def get_variable(self, name): """ Get a variable from the kernel language. """ return self.env.get(name, None) def do_execute_direct(self, code): python_magic = self.line_magics['python'] resp = python_magic.eval(code.strip()) if not resp is None: self.Print(str(resp)) def get_completions(self, token): python_magic = self.line_magics['python'] return python_magic.get_completions(token) def get_kernel_help_on(self, expr, level=0): python_magic = self.line_magics['python'] return python_magic.get_help_on(expr, level) if __name__ == '__main__': from IPython.kernel.zmq.kernelapp import IPKernelApp IPKernelApp.launch_instance(kernel_class=EvalKernel) ## Instruction: Return python eval instead of printing it ## Code After: from __future__ import print_function from jupyter_kernel import MagicKernel class EvalKernel(MagicKernel): implementation = 'Eval' implementation_version = '1.0' language = 'python' language_version = '0.1' banner = "Eval kernel - evaluates simple Python statements and expressions" env = {} def get_usage(self): return "This is a usage statement." def set_variable(self, name, value): """ Set a variable in the kernel language. """ self.env[name] = value def get_variable(self, name): """ Get a variable from the kernel language. """ return self.env.get(name, None) def do_execute_direct(self, code): python_magic = self.line_magics['python'] return python_magic.eval(code.strip()) def get_completions(self, token): python_magic = self.line_magics['python'] return python_magic.get_completions(token) def get_kernel_help_on(self, expr, level=0): python_magic = self.line_magics['python'] return python_magic.get_help_on(expr, level) if __name__ == '__main__': from IPython.kernel.zmq.kernelapp import IPKernelApp IPKernelApp.launch_instance(kernel_class=EvalKernel)
// ... existing code ... python_magic = self.line_magics['python'] return python_magic.eval(code.strip()) // ... rest of the code ...