commit
stringlengths
40
40
old_file
stringlengths
4
118
new_file
stringlengths
4
118
old_contents
stringlengths
0
2.94k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
444
message
stringlengths
16
3.45k
lang
stringclasses
1 value
license
stringclasses
13 values
repos
stringlengths
5
43.2k
prompt
stringlengths
17
4.58k
response
stringlengths
1
4.43k
prompt_tagged
stringlengths
58
4.62k
response_tagged
stringlengths
1
4.43k
text
stringlengths
132
7.29k
text_tagged
stringlengths
173
7.33k
a5ceaa6401c53fc99a85ef69ee1357996877e141
ocradmin/core/tests/testutils.py
ocradmin/core/tests/testutils.py
""" Functions for performing test setup/teardown etc. """ import os MODELDIR = "etc/defaultmodels" def symlink_model_fixtures(): """ Create symlinks between the files referenced in the OcrModel fixtures and our default model files. Need to do this because they get deleted again at test teardown. """ for fname in os.listdir(MODELDIR): try: os.makedirs("media/test") except OSError, (errno, strerr): if errno == 17: # already exists pass try: os.symlink(os.path.abspath("%s/%s" % (MODELDIR, fname)), "media/test/%s" % fname) except OSError, (errno, strerr): if errno == 17: # already exists pass
""" Functions for performing test setup/teardown etc. """ import os MODELDIR = "etc/defaultmodels" def symlink_model_fixtures(): """ Create symlinks between the files referenced in the OcrModel fixtures and our default model files. Need to do this because they get deleted again at test teardown. """ for fname in os.listdir(MODELDIR): try: os.makedirs("media/test") except OSError, (errno, strerr): if errno == 17: # already exists pass try: os.symlink(os.path.abspath("%s/%s" % (MODELDIR, fname)), "media/test/%s" % fname) except OSError, (errno, strerr): if errno == 17: # already exists pass def symlink_reference_pages(): """ Create a symlink for the reference page images. """ try: os.makedirs("media/test") except OSError, (errno, strerr): if errno == 17: # already exists pass try: os.symlink(os.path.abspath("etc/simple.png"), "media/test/test.png") os.symlink(os.path.abspath("etc/simple.png"), "media/test/test_bin.png") except OSError, (errno, strerr): if errno == 17: # already exists pass
Add a function to symlink reference_page files into existance
Add a function to symlink reference_page files into existance
Python
apache-2.0
vitorio/ocropodium,vitorio/ocropodium,vitorio/ocropodium,vitorio/ocropodium
""" Functions for performing test setup/teardown etc. """ import os MODELDIR = "etc/defaultmodels" def symlink_model_fixtures(): """ Create symlinks between the files referenced in the OcrModel fixtures and our default model files. Need to do this because they get deleted again at test teardown. """ for fname in os.listdir(MODELDIR): try: os.makedirs("media/test") except OSError, (errno, strerr): if errno == 17: # already exists pass try: os.symlink(os.path.abspath("%s/%s" % (MODELDIR, fname)), "media/test/%s" % fname) except OSError, (errno, strerr): if errno == 17: # already exists pass Add a function to symlink reference_page files into existance
""" Functions for performing test setup/teardown etc. """ import os MODELDIR = "etc/defaultmodels" def symlink_model_fixtures(): """ Create symlinks between the files referenced in the OcrModel fixtures and our default model files. Need to do this because they get deleted again at test teardown. """ for fname in os.listdir(MODELDIR): try: os.makedirs("media/test") except OSError, (errno, strerr): if errno == 17: # already exists pass try: os.symlink(os.path.abspath("%s/%s" % (MODELDIR, fname)), "media/test/%s" % fname) except OSError, (errno, strerr): if errno == 17: # already exists pass def symlink_reference_pages(): """ Create a symlink for the reference page images. """ try: os.makedirs("media/test") except OSError, (errno, strerr): if errno == 17: # already exists pass try: os.symlink(os.path.abspath("etc/simple.png"), "media/test/test.png") os.symlink(os.path.abspath("etc/simple.png"), "media/test/test_bin.png") except OSError, (errno, strerr): if errno == 17: # already exists pass
<commit_before>""" Functions for performing test setup/teardown etc. """ import os MODELDIR = "etc/defaultmodels" def symlink_model_fixtures(): """ Create symlinks between the files referenced in the OcrModel fixtures and our default model files. Need to do this because they get deleted again at test teardown. """ for fname in os.listdir(MODELDIR): try: os.makedirs("media/test") except OSError, (errno, strerr): if errno == 17: # already exists pass try: os.symlink(os.path.abspath("%s/%s" % (MODELDIR, fname)), "media/test/%s" % fname) except OSError, (errno, strerr): if errno == 17: # already exists pass <commit_msg>Add a function to symlink reference_page files into existance<commit_after>
""" Functions for performing test setup/teardown etc. """ import os MODELDIR = "etc/defaultmodels" def symlink_model_fixtures(): """ Create symlinks between the files referenced in the OcrModel fixtures and our default model files. Need to do this because they get deleted again at test teardown. """ for fname in os.listdir(MODELDIR): try: os.makedirs("media/test") except OSError, (errno, strerr): if errno == 17: # already exists pass try: os.symlink(os.path.abspath("%s/%s" % (MODELDIR, fname)), "media/test/%s" % fname) except OSError, (errno, strerr): if errno == 17: # already exists pass def symlink_reference_pages(): """ Create a symlink for the reference page images. """ try: os.makedirs("media/test") except OSError, (errno, strerr): if errno == 17: # already exists pass try: os.symlink(os.path.abspath("etc/simple.png"), "media/test/test.png") os.symlink(os.path.abspath("etc/simple.png"), "media/test/test_bin.png") except OSError, (errno, strerr): if errno == 17: # already exists pass
""" Functions for performing test setup/teardown etc. """ import os MODELDIR = "etc/defaultmodels" def symlink_model_fixtures(): """ Create symlinks between the files referenced in the OcrModel fixtures and our default model files. Need to do this because they get deleted again at test teardown. """ for fname in os.listdir(MODELDIR): try: os.makedirs("media/test") except OSError, (errno, strerr): if errno == 17: # already exists pass try: os.symlink(os.path.abspath("%s/%s" % (MODELDIR, fname)), "media/test/%s" % fname) except OSError, (errno, strerr): if errno == 17: # already exists pass Add a function to symlink reference_page files into existance""" Functions for performing test setup/teardown etc. """ import os MODELDIR = "etc/defaultmodels" def symlink_model_fixtures(): """ Create symlinks between the files referenced in the OcrModel fixtures and our default model files. Need to do this because they get deleted again at test teardown. """ for fname in os.listdir(MODELDIR): try: os.makedirs("media/test") except OSError, (errno, strerr): if errno == 17: # already exists pass try: os.symlink(os.path.abspath("%s/%s" % (MODELDIR, fname)), "media/test/%s" % fname) except OSError, (errno, strerr): if errno == 17: # already exists pass def symlink_reference_pages(): """ Create a symlink for the reference page images. """ try: os.makedirs("media/test") except OSError, (errno, strerr): if errno == 17: # already exists pass try: os.symlink(os.path.abspath("etc/simple.png"), "media/test/test.png") os.symlink(os.path.abspath("etc/simple.png"), "media/test/test_bin.png") except OSError, (errno, strerr): if errno == 17: # already exists pass
<commit_before>""" Functions for performing test setup/teardown etc. """ import os MODELDIR = "etc/defaultmodels" def symlink_model_fixtures(): """ Create symlinks between the files referenced in the OcrModel fixtures and our default model files. Need to do this because they get deleted again at test teardown. """ for fname in os.listdir(MODELDIR): try: os.makedirs("media/test") except OSError, (errno, strerr): if errno == 17: # already exists pass try: os.symlink(os.path.abspath("%s/%s" % (MODELDIR, fname)), "media/test/%s" % fname) except OSError, (errno, strerr): if errno == 17: # already exists pass <commit_msg>Add a function to symlink reference_page files into existance<commit_after>""" Functions for performing test setup/teardown etc. """ import os MODELDIR = "etc/defaultmodels" def symlink_model_fixtures(): """ Create symlinks between the files referenced in the OcrModel fixtures and our default model files. Need to do this because they get deleted again at test teardown. """ for fname in os.listdir(MODELDIR): try: os.makedirs("media/test") except OSError, (errno, strerr): if errno == 17: # already exists pass try: os.symlink(os.path.abspath("%s/%s" % (MODELDIR, fname)), "media/test/%s" % fname) except OSError, (errno, strerr): if errno == 17: # already exists pass def symlink_reference_pages(): """ Create a symlink for the reference page images. """ try: os.makedirs("media/test") except OSError, (errno, strerr): if errno == 17: # already exists pass try: os.symlink(os.path.abspath("etc/simple.png"), "media/test/test.png") os.symlink(os.path.abspath("etc/simple.png"), "media/test/test_bin.png") except OSError, (errno, strerr): if errno == 17: # already exists pass
c79bec872f1bd9158d202cade39d5e2351688c22
src/hireme/server.py
src/hireme/server.py
# -*- coding: utf-8 -*- from tasks import task1, task2 import flask def index(): return flask.render_template('index.html', title='index') def app_factory(): app = flask.Flask(import_name=__package__) app.add_url_rule('/', 'index', index) app.add_url_rule('/task1', 'task1', task1.solve) app.add_url_rule('/task2', 'task2', task2.solve) return app def run_local(*args, **kwargs): app = app_factory() app.run()
# -*- coding: utf-8 -*- from tasks import task1, task2 import flask def index(): return flask.render_template('index.html', title='index') def app_factory(): app = flask.Flask(import_name=__package__) app.add_url_rule('/', 'index', index) app.add_url_rule('/task1', 'task1', task1.solve, methods=['GET', 'POST']) app.add_url_rule('/task2', 'task2', task2.solve, methods=['GET', 'POST']) return app def run_local(*args, **kwargs): app = app_factory() app.run()
Allow POST as well as GET
Allow POST as well as GET
Python
bsd-2-clause
cutoffthetop/hireme
# -*- coding: utf-8 -*- from tasks import task1, task2 import flask def index(): return flask.render_template('index.html', title='index') def app_factory(): app = flask.Flask(import_name=__package__) app.add_url_rule('/', 'index', index) app.add_url_rule('/task1', 'task1', task1.solve) app.add_url_rule('/task2', 'task2', task2.solve) return app def run_local(*args, **kwargs): app = app_factory() app.run() Allow POST as well as GET
# -*- coding: utf-8 -*- from tasks import task1, task2 import flask def index(): return flask.render_template('index.html', title='index') def app_factory(): app = flask.Flask(import_name=__package__) app.add_url_rule('/', 'index', index) app.add_url_rule('/task1', 'task1', task1.solve, methods=['GET', 'POST']) app.add_url_rule('/task2', 'task2', task2.solve, methods=['GET', 'POST']) return app def run_local(*args, **kwargs): app = app_factory() app.run()
<commit_before># -*- coding: utf-8 -*- from tasks import task1, task2 import flask def index(): return flask.render_template('index.html', title='index') def app_factory(): app = flask.Flask(import_name=__package__) app.add_url_rule('/', 'index', index) app.add_url_rule('/task1', 'task1', task1.solve) app.add_url_rule('/task2', 'task2', task2.solve) return app def run_local(*args, **kwargs): app = app_factory() app.run() <commit_msg>Allow POST as well as GET<commit_after>
# -*- coding: utf-8 -*- from tasks import task1, task2 import flask def index(): return flask.render_template('index.html', title='index') def app_factory(): app = flask.Flask(import_name=__package__) app.add_url_rule('/', 'index', index) app.add_url_rule('/task1', 'task1', task1.solve, methods=['GET', 'POST']) app.add_url_rule('/task2', 'task2', task2.solve, methods=['GET', 'POST']) return app def run_local(*args, **kwargs): app = app_factory() app.run()
# -*- coding: utf-8 -*- from tasks import task1, task2 import flask def index(): return flask.render_template('index.html', title='index') def app_factory(): app = flask.Flask(import_name=__package__) app.add_url_rule('/', 'index', index) app.add_url_rule('/task1', 'task1', task1.solve) app.add_url_rule('/task2', 'task2', task2.solve) return app def run_local(*args, **kwargs): app = app_factory() app.run() Allow POST as well as GET# -*- coding: utf-8 -*- from tasks import task1, task2 import flask def index(): return flask.render_template('index.html', title='index') def app_factory(): app = flask.Flask(import_name=__package__) app.add_url_rule('/', 'index', index) app.add_url_rule('/task1', 'task1', task1.solve, methods=['GET', 'POST']) app.add_url_rule('/task2', 'task2', task2.solve, methods=['GET', 'POST']) return app def run_local(*args, **kwargs): app = app_factory() app.run()
<commit_before># -*- coding: utf-8 -*- from tasks import task1, task2 import flask def index(): return flask.render_template('index.html', title='index') def app_factory(): app = flask.Flask(import_name=__package__) app.add_url_rule('/', 'index', index) app.add_url_rule('/task1', 'task1', task1.solve) app.add_url_rule('/task2', 'task2', task2.solve) return app def run_local(*args, **kwargs): app = app_factory() app.run() <commit_msg>Allow POST as well as GET<commit_after># -*- coding: utf-8 -*- from tasks import task1, task2 import flask def index(): return flask.render_template('index.html', title='index') def app_factory(): app = flask.Flask(import_name=__package__) app.add_url_rule('/', 'index', index) app.add_url_rule('/task1', 'task1', task1.solve, methods=['GET', 'POST']) app.add_url_rule('/task2', 'task2', task2.solve, methods=['GET', 'POST']) return app def run_local(*args, **kwargs): app = app_factory() app.run()
9ea7e49e11c3e05b86b9eeaffd416285c9a2551a
pushhub/models.py
pushhub/models.py
from persistent.mapping import PersistentMapping class Root(PersistentMapping): __parent__ = __name__ = None def appmaker(zodb_root): if not 'app_root' in zodb_root: app_root = Root() zodb_root['app_root'] = app_root import transaction transaction.commit() return zodb_root['app_root']
from persistent.mapping import PersistentMapping from .subsciber import Subscribers from .topic import Topics class Root(PersistentMapping): __parent__ = __name__ = None def appmaker(zodb_root): if not 'app_root' in zodb_root: app_root = Root() zodb_root['app_root'] = app_root import transaction transaction.commit() subscribers = Subscribers() app_root['subscribers'] = subscribers subscribers.__name__ = 'subscribers' subscribers.__parent__ = app_root transaction.commit() topics = Topics() app_root['topics'] = topics topics.__name__ = 'topics' topics.__parent__ = app_root transaction.commit() return zodb_root['app_root']
Add folder set up to the ZODB on app creation.
Add folder set up to the ZODB on app creation.
Python
bsd-3-clause
ucla/PushHubCore
from persistent.mapping import PersistentMapping class Root(PersistentMapping): __parent__ = __name__ = None def appmaker(zodb_root): if not 'app_root' in zodb_root: app_root = Root() zodb_root['app_root'] = app_root import transaction transaction.commit() return zodb_root['app_root'] Add folder set up to the ZODB on app creation.
from persistent.mapping import PersistentMapping from .subsciber import Subscribers from .topic import Topics class Root(PersistentMapping): __parent__ = __name__ = None def appmaker(zodb_root): if not 'app_root' in zodb_root: app_root = Root() zodb_root['app_root'] = app_root import transaction transaction.commit() subscribers = Subscribers() app_root['subscribers'] = subscribers subscribers.__name__ = 'subscribers' subscribers.__parent__ = app_root transaction.commit() topics = Topics() app_root['topics'] = topics topics.__name__ = 'topics' topics.__parent__ = app_root transaction.commit() return zodb_root['app_root']
<commit_before>from persistent.mapping import PersistentMapping class Root(PersistentMapping): __parent__ = __name__ = None def appmaker(zodb_root): if not 'app_root' in zodb_root: app_root = Root() zodb_root['app_root'] = app_root import transaction transaction.commit() return zodb_root['app_root'] <commit_msg>Add folder set up to the ZODB on app creation.<commit_after>
from persistent.mapping import PersistentMapping from .subsciber import Subscribers from .topic import Topics class Root(PersistentMapping): __parent__ = __name__ = None def appmaker(zodb_root): if not 'app_root' in zodb_root: app_root = Root() zodb_root['app_root'] = app_root import transaction transaction.commit() subscribers = Subscribers() app_root['subscribers'] = subscribers subscribers.__name__ = 'subscribers' subscribers.__parent__ = app_root transaction.commit() topics = Topics() app_root['topics'] = topics topics.__name__ = 'topics' topics.__parent__ = app_root transaction.commit() return zodb_root['app_root']
from persistent.mapping import PersistentMapping class Root(PersistentMapping): __parent__ = __name__ = None def appmaker(zodb_root): if not 'app_root' in zodb_root: app_root = Root() zodb_root['app_root'] = app_root import transaction transaction.commit() return zodb_root['app_root'] Add folder set up to the ZODB on app creation.from persistent.mapping import PersistentMapping from .subsciber import Subscribers from .topic import Topics class Root(PersistentMapping): __parent__ = __name__ = None def appmaker(zodb_root): if not 'app_root' in zodb_root: app_root = Root() zodb_root['app_root'] = app_root import transaction transaction.commit() subscribers = Subscribers() app_root['subscribers'] = subscribers subscribers.__name__ = 'subscribers' subscribers.__parent__ = app_root transaction.commit() topics = Topics() app_root['topics'] = topics topics.__name__ = 'topics' topics.__parent__ = app_root transaction.commit() return zodb_root['app_root']
<commit_before>from persistent.mapping import PersistentMapping class Root(PersistentMapping): __parent__ = __name__ = None def appmaker(zodb_root): if not 'app_root' in zodb_root: app_root = Root() zodb_root['app_root'] = app_root import transaction transaction.commit() return zodb_root['app_root'] <commit_msg>Add folder set up to the ZODB on app creation.<commit_after>from persistent.mapping import PersistentMapping from .subsciber import Subscribers from .topic import Topics class Root(PersistentMapping): __parent__ = __name__ = None def appmaker(zodb_root): if not 'app_root' in zodb_root: app_root = Root() zodb_root['app_root'] = app_root import transaction transaction.commit() subscribers = Subscribers() app_root['subscribers'] = subscribers subscribers.__name__ = 'subscribers' subscribers.__parent__ = app_root transaction.commit() topics = Topics() app_root['topics'] = topics topics.__name__ = 'topics' topics.__parent__ = app_root transaction.commit() return zodb_root['app_root']
d788375843d42d1de3c0143064e905a932394e30
library/tests/test_factories.py
library/tests/test_factories.py
import pytest from .factories import BookFactory, BookSpecimenFactory pytestmark = pytest.mark.django_db def test_it_should_create_a_default_book_from_factory(): book = BookFactory() assert book.pk is not None assert unicode(book) def test_it_should_override_book_fields_passed_to_factory(): book = BookFactory() assert book.title.startswith('Test book') another = BookFactory(title="My custom title") assert another.title == "My custom title" def test_it_should_create_a_default_book_specimen_from_factory(): specimen = BookSpecimenFactory() assert specimen.pk is not None assert unicode(specimen) def test_it_should_override_specimen_fields_passed_to_factory(): book = BookFactory() specimen = BookSpecimenFactory(book=book) assert specimen.book == book
import pytest from .factories import BookFactory, BookSpecimenFactory pytestmark = pytest.mark.django_db def test_it_should_create_a_default_book_from_factory(): book = BookFactory() assert book.pk is not None assert unicode(book) def test_it_should_override_book_fields_passed_to_factory(): book = BookFactory() assert book.title.startswith('Test book') another = BookFactory(title="My custom title") assert another.title == "My custom title" def test_it_should_create_a_default_book_specimen_from_factory(): specimen = BookSpecimenFactory() assert specimen.pk is not None assert specimen.book.pk is not None assert unicode(specimen) def test_it_should_override_specimen_fields_passed_to_factory(): book = BookFactory() specimen = BookSpecimenFactory(book=book) assert specimen.book == book
Test that BookSpecimenFactory also creates the related book
Test that BookSpecimenFactory also creates the related book
Python
agpl-3.0
ideascube/ideascube,ideascube/ideascube,Lcaracol/ideasbox.lan,ideascube/ideascube,Lcaracol/ideasbox.lan,Lcaracol/ideasbox.lan,ideascube/ideascube
import pytest from .factories import BookFactory, BookSpecimenFactory pytestmark = pytest.mark.django_db def test_it_should_create_a_default_book_from_factory(): book = BookFactory() assert book.pk is not None assert unicode(book) def test_it_should_override_book_fields_passed_to_factory(): book = BookFactory() assert book.title.startswith('Test book') another = BookFactory(title="My custom title") assert another.title == "My custom title" def test_it_should_create_a_default_book_specimen_from_factory(): specimen = BookSpecimenFactory() assert specimen.pk is not None assert unicode(specimen) def test_it_should_override_specimen_fields_passed_to_factory(): book = BookFactory() specimen = BookSpecimenFactory(book=book) assert specimen.book == book Test that BookSpecimenFactory also creates the related book
import pytest from .factories import BookFactory, BookSpecimenFactory pytestmark = pytest.mark.django_db def test_it_should_create_a_default_book_from_factory(): book = BookFactory() assert book.pk is not None assert unicode(book) def test_it_should_override_book_fields_passed_to_factory(): book = BookFactory() assert book.title.startswith('Test book') another = BookFactory(title="My custom title") assert another.title == "My custom title" def test_it_should_create_a_default_book_specimen_from_factory(): specimen = BookSpecimenFactory() assert specimen.pk is not None assert specimen.book.pk is not None assert unicode(specimen) def test_it_should_override_specimen_fields_passed_to_factory(): book = BookFactory() specimen = BookSpecimenFactory(book=book) assert specimen.book == book
<commit_before>import pytest from .factories import BookFactory, BookSpecimenFactory pytestmark = pytest.mark.django_db def test_it_should_create_a_default_book_from_factory(): book = BookFactory() assert book.pk is not None assert unicode(book) def test_it_should_override_book_fields_passed_to_factory(): book = BookFactory() assert book.title.startswith('Test book') another = BookFactory(title="My custom title") assert another.title == "My custom title" def test_it_should_create_a_default_book_specimen_from_factory(): specimen = BookSpecimenFactory() assert specimen.pk is not None assert unicode(specimen) def test_it_should_override_specimen_fields_passed_to_factory(): book = BookFactory() specimen = BookSpecimenFactory(book=book) assert specimen.book == book <commit_msg>Test that BookSpecimenFactory also creates the related book<commit_after>
import pytest from .factories import BookFactory, BookSpecimenFactory pytestmark = pytest.mark.django_db def test_it_should_create_a_default_book_from_factory(): book = BookFactory() assert book.pk is not None assert unicode(book) def test_it_should_override_book_fields_passed_to_factory(): book = BookFactory() assert book.title.startswith('Test book') another = BookFactory(title="My custom title") assert another.title == "My custom title" def test_it_should_create_a_default_book_specimen_from_factory(): specimen = BookSpecimenFactory() assert specimen.pk is not None assert specimen.book.pk is not None assert unicode(specimen) def test_it_should_override_specimen_fields_passed_to_factory(): book = BookFactory() specimen = BookSpecimenFactory(book=book) assert specimen.book == book
import pytest from .factories import BookFactory, BookSpecimenFactory pytestmark = pytest.mark.django_db def test_it_should_create_a_default_book_from_factory(): book = BookFactory() assert book.pk is not None assert unicode(book) def test_it_should_override_book_fields_passed_to_factory(): book = BookFactory() assert book.title.startswith('Test book') another = BookFactory(title="My custom title") assert another.title == "My custom title" def test_it_should_create_a_default_book_specimen_from_factory(): specimen = BookSpecimenFactory() assert specimen.pk is not None assert unicode(specimen) def test_it_should_override_specimen_fields_passed_to_factory(): book = BookFactory() specimen = BookSpecimenFactory(book=book) assert specimen.book == book Test that BookSpecimenFactory also creates the related bookimport pytest from .factories import BookFactory, BookSpecimenFactory pytestmark = pytest.mark.django_db def test_it_should_create_a_default_book_from_factory(): book = BookFactory() assert book.pk is not None assert unicode(book) def test_it_should_override_book_fields_passed_to_factory(): book = BookFactory() assert book.title.startswith('Test book') another = BookFactory(title="My custom title") assert another.title == "My custom title" def test_it_should_create_a_default_book_specimen_from_factory(): specimen = BookSpecimenFactory() assert specimen.pk is not None assert specimen.book.pk is not None assert unicode(specimen) def test_it_should_override_specimen_fields_passed_to_factory(): book = BookFactory() specimen = BookSpecimenFactory(book=book) assert specimen.book == book
<commit_before>import pytest from .factories import BookFactory, BookSpecimenFactory pytestmark = pytest.mark.django_db def test_it_should_create_a_default_book_from_factory(): book = BookFactory() assert book.pk is not None assert unicode(book) def test_it_should_override_book_fields_passed_to_factory(): book = BookFactory() assert book.title.startswith('Test book') another = BookFactory(title="My custom title") assert another.title == "My custom title" def test_it_should_create_a_default_book_specimen_from_factory(): specimen = BookSpecimenFactory() assert specimen.pk is not None assert unicode(specimen) def test_it_should_override_specimen_fields_passed_to_factory(): book = BookFactory() specimen = BookSpecimenFactory(book=book) assert specimen.book == book <commit_msg>Test that BookSpecimenFactory also creates the related book<commit_after>import pytest from .factories import BookFactory, BookSpecimenFactory pytestmark = pytest.mark.django_db def test_it_should_create_a_default_book_from_factory(): book = BookFactory() assert book.pk is not None assert unicode(book) def test_it_should_override_book_fields_passed_to_factory(): book = BookFactory() assert book.title.startswith('Test book') another = BookFactory(title="My custom title") assert another.title == "My custom title" def test_it_should_create_a_default_book_specimen_from_factory(): specimen = BookSpecimenFactory() assert specimen.pk is not None assert specimen.book.pk is not None assert unicode(specimen) def test_it_should_override_specimen_fields_passed_to_factory(): book = BookFactory() specimen = BookSpecimenFactory(book=book) assert specimen.book == book
972eaa90d4ffad7f4e74792e2bdc4917e5eb7c3a
puffin/core/compose.py
puffin/core/compose.py
from .applications import get_application_domain, get_application_name from .machine import get_env_vars from .. import app from subprocess import Popen, STDOUT, PIPE from os import environ from os.path import join def init(): pass def compose_start(machine, user, application, **environment): compose_run(machine, user, application, "up", "-d", **environment) def compose_stop(machine, user, application): compose_run(machine, user, application, "down") def compose_run(machine, user, application, *arguments, **environment): name = get_application_name(user, application) args = ["docker-compose", "-f", application.compose, "-p", name] args += arguments domain = get_application_domain(user, application) env = dict(PATH=environ['PATH'], VIRTUAL_HOST=domain, LETSENCRYPT_HOST=domain) env.update(get_env_vars(machine)) env.update(**environment) process = Popen(args, stderr=STDOUT, stdout=PIPE, universal_newlines=True, env=env) process.wait() out, err = process.communicate() print(out) #app.logger.info("Compose:", out)
from .applications import get_application_domain, get_application_name from .machine import get_env_vars from .. import app from subprocess import Popen, STDOUT, PIPE from os import environ from os.path import join def init(): pass def compose_start(machine, user, application, **environment): compose_run(machine, user, application, "up", "-d", **environment) def compose_stop(machine, user, application): compose_run(machine, user, application, "down") def compose_run(machine, user, application, *arguments, **environment): name = get_application_name(user, application) args = ["docker-compose", "-f", application.compose, "-p", name] args += arguments domain = get_application_domain(user, application) env = dict(PATH=environ['PATH'], VIRTUAL_HOST=domain) env.update(LETSENCRYPT_HOST=domain, LETSENCRYPT_EMAIL="pub@loomchild.net") env.update(get_env_vars(machine)) env.update(**environment) process = Popen(args, stderr=STDOUT, stdout=PIPE, universal_newlines=True, env=env) process.wait() out, err = process.communicate() print(out) #app.logger.info("Compose:", out)
Add dummy Let's Encrypt email
Add dummy Let's Encrypt email
Python
agpl-3.0
loomchild/jenca-puffin,loomchild/puffin,puffinrocks/puffin,loomchild/puffin,loomchild/puffin,puffinrocks/puffin,loomchild/puffin,loomchild/puffin,loomchild/jenca-puffin
from .applications import get_application_domain, get_application_name from .machine import get_env_vars from .. import app from subprocess import Popen, STDOUT, PIPE from os import environ from os.path import join def init(): pass def compose_start(machine, user, application, **environment): compose_run(machine, user, application, "up", "-d", **environment) def compose_stop(machine, user, application): compose_run(machine, user, application, "down") def compose_run(machine, user, application, *arguments, **environment): name = get_application_name(user, application) args = ["docker-compose", "-f", application.compose, "-p", name] args += arguments domain = get_application_domain(user, application) env = dict(PATH=environ['PATH'], VIRTUAL_HOST=domain, LETSENCRYPT_HOST=domain) env.update(get_env_vars(machine)) env.update(**environment) process = Popen(args, stderr=STDOUT, stdout=PIPE, universal_newlines=True, env=env) process.wait() out, err = process.communicate() print(out) #app.logger.info("Compose:", out) Add dummy Let's Encrypt email
from .applications import get_application_domain, get_application_name from .machine import get_env_vars from .. import app from subprocess import Popen, STDOUT, PIPE from os import environ from os.path import join def init(): pass def compose_start(machine, user, application, **environment): compose_run(machine, user, application, "up", "-d", **environment) def compose_stop(machine, user, application): compose_run(machine, user, application, "down") def compose_run(machine, user, application, *arguments, **environment): name = get_application_name(user, application) args = ["docker-compose", "-f", application.compose, "-p", name] args += arguments domain = get_application_domain(user, application) env = dict(PATH=environ['PATH'], VIRTUAL_HOST=domain) env.update(LETSENCRYPT_HOST=domain, LETSENCRYPT_EMAIL="pub@loomchild.net") env.update(get_env_vars(machine)) env.update(**environment) process = Popen(args, stderr=STDOUT, stdout=PIPE, universal_newlines=True, env=env) process.wait() out, err = process.communicate() print(out) #app.logger.info("Compose:", out)
<commit_before>from .applications import get_application_domain, get_application_name from .machine import get_env_vars from .. import app from subprocess import Popen, STDOUT, PIPE from os import environ from os.path import join def init(): pass def compose_start(machine, user, application, **environment): compose_run(machine, user, application, "up", "-d", **environment) def compose_stop(machine, user, application): compose_run(machine, user, application, "down") def compose_run(machine, user, application, *arguments, **environment): name = get_application_name(user, application) args = ["docker-compose", "-f", application.compose, "-p", name] args += arguments domain = get_application_domain(user, application) env = dict(PATH=environ['PATH'], VIRTUAL_HOST=domain, LETSENCRYPT_HOST=domain) env.update(get_env_vars(machine)) env.update(**environment) process = Popen(args, stderr=STDOUT, stdout=PIPE, universal_newlines=True, env=env) process.wait() out, err = process.communicate() print(out) #app.logger.info("Compose:", out) <commit_msg>Add dummy Let's Encrypt email<commit_after>
from .applications import get_application_domain, get_application_name from .machine import get_env_vars from .. import app from subprocess import Popen, STDOUT, PIPE from os import environ from os.path import join def init(): pass def compose_start(machine, user, application, **environment): compose_run(machine, user, application, "up", "-d", **environment) def compose_stop(machine, user, application): compose_run(machine, user, application, "down") def compose_run(machine, user, application, *arguments, **environment): name = get_application_name(user, application) args = ["docker-compose", "-f", application.compose, "-p", name] args += arguments domain = get_application_domain(user, application) env = dict(PATH=environ['PATH'], VIRTUAL_HOST=domain) env.update(LETSENCRYPT_HOST=domain, LETSENCRYPT_EMAIL="pub@loomchild.net") env.update(get_env_vars(machine)) env.update(**environment) process = Popen(args, stderr=STDOUT, stdout=PIPE, universal_newlines=True, env=env) process.wait() out, err = process.communicate() print(out) #app.logger.info("Compose:", out)
from .applications import get_application_domain, get_application_name from .machine import get_env_vars from .. import app from subprocess import Popen, STDOUT, PIPE from os import environ from os.path import join def init(): pass def compose_start(machine, user, application, **environment): compose_run(machine, user, application, "up", "-d", **environment) def compose_stop(machine, user, application): compose_run(machine, user, application, "down") def compose_run(machine, user, application, *arguments, **environment): name = get_application_name(user, application) args = ["docker-compose", "-f", application.compose, "-p", name] args += arguments domain = get_application_domain(user, application) env = dict(PATH=environ['PATH'], VIRTUAL_HOST=domain, LETSENCRYPT_HOST=domain) env.update(get_env_vars(machine)) env.update(**environment) process = Popen(args, stderr=STDOUT, stdout=PIPE, universal_newlines=True, env=env) process.wait() out, err = process.communicate() print(out) #app.logger.info("Compose:", out) Add dummy Let's Encrypt emailfrom .applications import get_application_domain, get_application_name from .machine import get_env_vars from .. import app from subprocess import Popen, STDOUT, PIPE from os import environ from os.path import join def init(): pass def compose_start(machine, user, application, **environment): compose_run(machine, user, application, "up", "-d", **environment) def compose_stop(machine, user, application): compose_run(machine, user, application, "down") def compose_run(machine, user, application, *arguments, **environment): name = get_application_name(user, application) args = ["docker-compose", "-f", application.compose, "-p", name] args += arguments domain = get_application_domain(user, application) env = dict(PATH=environ['PATH'], VIRTUAL_HOST=domain) env.update(LETSENCRYPT_HOST=domain, LETSENCRYPT_EMAIL="pub@loomchild.net") env.update(get_env_vars(machine)) env.update(**environment) process = Popen(args, stderr=STDOUT, stdout=PIPE, universal_newlines=True, env=env) process.wait() out, err = process.communicate() print(out) #app.logger.info("Compose:", out)
<commit_before>from .applications import get_application_domain, get_application_name from .machine import get_env_vars from .. import app from subprocess import Popen, STDOUT, PIPE from os import environ from os.path import join def init(): pass def compose_start(machine, user, application, **environment): compose_run(machine, user, application, "up", "-d", **environment) def compose_stop(machine, user, application): compose_run(machine, user, application, "down") def compose_run(machine, user, application, *arguments, **environment): name = get_application_name(user, application) args = ["docker-compose", "-f", application.compose, "-p", name] args += arguments domain = get_application_domain(user, application) env = dict(PATH=environ['PATH'], VIRTUAL_HOST=domain, LETSENCRYPT_HOST=domain) env.update(get_env_vars(machine)) env.update(**environment) process = Popen(args, stderr=STDOUT, stdout=PIPE, universal_newlines=True, env=env) process.wait() out, err = process.communicate() print(out) #app.logger.info("Compose:", out) <commit_msg>Add dummy Let's Encrypt email<commit_after>from .applications import get_application_domain, get_application_name from .machine import get_env_vars from .. import app from subprocess import Popen, STDOUT, PIPE from os import environ from os.path import join def init(): pass def compose_start(machine, user, application, **environment): compose_run(machine, user, application, "up", "-d", **environment) def compose_stop(machine, user, application): compose_run(machine, user, application, "down") def compose_run(machine, user, application, *arguments, **environment): name = get_application_name(user, application) args = ["docker-compose", "-f", application.compose, "-p", name] args += arguments domain = get_application_domain(user, application) env = dict(PATH=environ['PATH'], VIRTUAL_HOST=domain) env.update(LETSENCRYPT_HOST=domain, LETSENCRYPT_EMAIL="pub@loomchild.net") env.update(get_env_vars(machine)) env.update(**environment) process = Popen(args, stderr=STDOUT, stdout=PIPE, universal_newlines=True, env=env) process.wait() out, err = process.communicate() print(out) #app.logger.info("Compose:", out)
a292f2978f07839af07a8963a51fd48b046f0c73
website/addons/mendeley/settings/__init__.py
website/addons/mendeley/settings/__init__.py
import logging from .defaults import * # noqa try: from .local import * # noqa except ImportError as error: logging.warn('No local.py settings file found')
import logging from .defaults import * # noqa logger = logging.getLogger(__name__) try: from .local import * # noqa except ImportError as error: logger.warn('No local.py settings file found')
Use namespaces logger in mendeley settings
Use namespaces logger in mendeley settings h/t Arpita for catching this [skip ci]
Python
apache-2.0
brianjgeiger/osf.io,Johnetordoff/osf.io,samchrisinger/osf.io,KAsante95/osf.io,crcresearch/osf.io,arpitar/osf.io,danielneis/osf.io,cslzchen/osf.io,baylee-d/osf.io,Johnetordoff/osf.io,asanfilippo7/osf.io,kwierman/osf.io,SSJohns/osf.io,GageGaskins/osf.io,GageGaskins/osf.io,danielneis/osf.io,brandonPurvis/osf.io,emetsger/osf.io,brandonPurvis/osf.io,billyhunt/osf.io,chrisseto/osf.io,zamattiac/osf.io,monikagrabowska/osf.io,njantrania/osf.io,cosenal/osf.io,TomHeatwole/osf.io,DanielSBrown/osf.io,chrisseto/osf.io,mfraezz/osf.io,leb2dg/osf.io,CenterForOpenScience/osf.io,billyhunt/osf.io,SSJohns/osf.io,cwisecarver/osf.io,caneruguz/osf.io,rdhyee/osf.io,caseyrollins/osf.io,caseyrollins/osf.io,Nesiehr/osf.io,KAsante95/osf.io,samanehsan/osf.io,aaxelb/osf.io,petermalcolm/osf.io,adlius/osf.io,amyshi188/osf.io,Johnetordoff/osf.io,sloria/osf.io,erinspace/osf.io,hmoco/osf.io,RomanZWang/osf.io,ZobairAlijan/osf.io,haoyuchen1992/osf.io,danielneis/osf.io,mluke93/osf.io,samanehsan/osf.io,brandonPurvis/osf.io,samanehsan/osf.io,ticklemepierce/osf.io,amyshi188/osf.io,billyhunt/osf.io,samchrisinger/osf.io,kch8qx/osf.io,hmoco/osf.io,baylee-d/osf.io,icereval/osf.io,baylee-d/osf.io,caneruguz/osf.io,rdhyee/osf.io,mluo613/osf.io,CenterForOpenScience/osf.io,caseyrygt/osf.io,ticklemepierce/osf.io,chrisseto/osf.io,adlius/osf.io,ticklemepierce/osf.io,mluo613/osf.io,emetsger/osf.io,Ghalko/osf.io,Ghalko/osf.io,HalcyonChimera/osf.io,CenterForOpenScience/osf.io,abought/osf.io,pattisdr/osf.io,RomanZWang/osf.io,chennan47/osf.io,haoyuchen1992/osf.io,alexschiller/osf.io,TomBaxter/osf.io,doublebits/osf.io,mluke93/osf.io,acshi/osf.io,caseyrygt/osf.io,pattisdr/osf.io,brianjgeiger/osf.io,njantrania/osf.io,monikagrabowska/osf.io,RomanZWang/osf.io,samanehsan/osf.io,Nesiehr/osf.io,alexschiller/osf.io,njantrania/osf.io,sloria/osf.io,saradbowman/osf.io,asanfilippo7/osf.io,jnayak1/osf.io,njantrania/osf.io,brandonPurvis/osf.io,sloria/osf.io,mluo613/osf.io,chrisseto/osf.io,felliott/osf.io,SSJohns/osf.io,caseyrygt/osf.io,zachjanicki/osf.io,rdhyee/osf.io,cosenal/osf.io,laurenrevere/osf.io,felliott/osf.io,chennan47/osf.io,kwierman/osf.io,kch8qx/osf.io,abought/osf.io,Ghalko/osf.io,cslzchen/osf.io,KAsante95/osf.io,doublebits/osf.io,caseyrygt/osf.io,HalcyonChimera/osf.io,chennan47/osf.io,arpitar/osf.io,danielneis/osf.io,aaxelb/osf.io,doublebits/osf.io,erinspace/osf.io,brandonPurvis/osf.io,KAsante95/osf.io,felliott/osf.io,mluke93/osf.io,mattclark/osf.io,Johnetordoff/osf.io,ticklemepierce/osf.io,Ghalko/osf.io,arpitar/osf.io,binoculars/osf.io,samchrisinger/osf.io,brianjgeiger/osf.io,Nesiehr/osf.io,kch8qx/osf.io,asanfilippo7/osf.io,jnayak1/osf.io,arpitar/osf.io,brianjgeiger/osf.io,DanielSBrown/osf.io,jnayak1/osf.io,mluke93/osf.io,HalcyonChimera/osf.io,icereval/osf.io,acshi/osf.io,alexschiller/osf.io,aaxelb/osf.io,emetsger/osf.io,TomHeatwole/osf.io,SSJohns/osf.io,petermalcolm/osf.io,monikagrabowska/osf.io,laurenrevere/osf.io,TomBaxter/osf.io,mattclark/osf.io,cosenal/osf.io,DanielSBrown/osf.io,HalcyonChimera/osf.io,caneruguz/osf.io,mluo613/osf.io,wearpants/osf.io,cwisecarver/osf.io,TomHeatwole/osf.io,kwierman/osf.io,GageGaskins/osf.io,billyhunt/osf.io,DanielSBrown/osf.io,aaxelb/osf.io,Nesiehr/osf.io,GageGaskins/osf.io,adlius/osf.io,doublebits/osf.io,zachjanicki/osf.io,RomanZWang/osf.io,felliott/osf.io,hmoco/osf.io,cwisecarver/osf.io,kch8qx/osf.io,mfraezz/osf.io,caneruguz/osf.io,alexschiller/osf.io,asanfilippo7/osf.io,rdhyee/osf.io,TomHeatwole/osf.io,jnayak1/osf.io,mfraezz/osf.io,CenterForOpenScience/osf.io,saradbowman/osf.io,ZobairAlijan/osf.io,cwisecarver/osf.io,emetsger/osf.io,cslzchen/osf.io,TomBaxter/osf.io,crcresearch/osf.io,caseyrollins/osf.io,amyshi188/osf.io,haoyuchen1992/osf.io,binoculars/osf.io,leb2dg/osf.io,zachjanicki/osf.io,acshi/osf.io,zamattiac/osf.io,ZobairAlijan/osf.io,cosenal/osf.io,alexschiller/osf.io,zachjanicki/osf.io,mluo613/osf.io,wearpants/osf.io,petermalcolm/osf.io,doublebits/osf.io,erinspace/osf.io,cslzchen/osf.io,acshi/osf.io,mattclark/osf.io,leb2dg/osf.io,RomanZWang/osf.io,abought/osf.io,acshi/osf.io,pattisdr/osf.io,samchrisinger/osf.io,zamattiac/osf.io,icereval/osf.io,billyhunt/osf.io,kch8qx/osf.io,laurenrevere/osf.io,adlius/osf.io,kwierman/osf.io,monikagrabowska/osf.io,zamattiac/osf.io,abought/osf.io,monikagrabowska/osf.io,wearpants/osf.io,KAsante95/osf.io,GageGaskins/osf.io,petermalcolm/osf.io,leb2dg/osf.io,crcresearch/osf.io,wearpants/osf.io,haoyuchen1992/osf.io,amyshi188/osf.io,hmoco/osf.io,binoculars/osf.io,ZobairAlijan/osf.io,mfraezz/osf.io
import logging from .defaults import * # noqa try: from .local import * # noqa except ImportError as error: logging.warn('No local.py settings file found') Use namespaces logger in mendeley settings h/t Arpita for catching this [skip ci]
import logging from .defaults import * # noqa logger = logging.getLogger(__name__) try: from .local import * # noqa except ImportError as error: logger.warn('No local.py settings file found')
<commit_before>import logging from .defaults import * # noqa try: from .local import * # noqa except ImportError as error: logging.warn('No local.py settings file found') <commit_msg>Use namespaces logger in mendeley settings h/t Arpita for catching this [skip ci]<commit_after>
import logging from .defaults import * # noqa logger = logging.getLogger(__name__) try: from .local import * # noqa except ImportError as error: logger.warn('No local.py settings file found')
import logging from .defaults import * # noqa try: from .local import * # noqa except ImportError as error: logging.warn('No local.py settings file found') Use namespaces logger in mendeley settings h/t Arpita for catching this [skip ci]import logging from .defaults import * # noqa logger = logging.getLogger(__name__) try: from .local import * # noqa except ImportError as error: logger.warn('No local.py settings file found')
<commit_before>import logging from .defaults import * # noqa try: from .local import * # noqa except ImportError as error: logging.warn('No local.py settings file found') <commit_msg>Use namespaces logger in mendeley settings h/t Arpita for catching this [skip ci]<commit_after>import logging from .defaults import * # noqa logger = logging.getLogger(__name__) try: from .local import * # noqa except ImportError as error: logger.warn('No local.py settings file found')
a5ff4c247030559c83a06976fcda062c0c42d810
django_fixmystreet/fixmystreet/tests/__init__.py
django_fixmystreet/fixmystreet/tests/__init__.py
import shutil import os from django.core.files.storage import default_storage from django.test import TestCase class SampleFilesTestCase(TestCase): fixtures = ['sample'] @classmethod def setUpClass(cls): default_storage.location = 'media' # force using source media folder to avoid real data erasing # @classmethod # def setUpClass(cls): # shutil.copytree('media', 'media-tmp') # default_storage.location = 'media-tmp' # # @classmethod # def tearDownClass(self): # shutil.rmtree('media-tmp') def _fixture_setup(self): if os.path.exists('media/photos'): shutil.rmtree('media/photos') shutil.copytree('media/photos-sample', 'media/photos') super(SampleFilesTestCase, self)._fixture_setup() def tearDown(self): shutil.rmtree('media/photos') from django_fixmystreet.fixmystreet.tests.views import * from django_fixmystreet.fixmystreet.tests.reports import * from django_fixmystreet.fixmystreet.tests.users import * from django_fixmystreet.fixmystreet.tests.organisation_entity import * from django_fixmystreet.fixmystreet.tests.mail import * # from django_fixmystreet.fixmystreet.tests.api import *
import shutil import os from django.core.files.storage import default_storage from django.test import TestCase class SampleFilesTestCase(TestCase): fixtures = ['sample'] @classmethod def setUpClass(cls): default_storage.location = 'media' # force using source media folder to avoid real data erasing # @classmethod # def setUpClass(cls): # shutil.copytree('media', 'media-tmp') # default_storage.location = 'media-tmp' # # @classmethod # def tearDownClass(self): # shutil.rmtree('media-tmp') def _fixture_setup(self): if os.path.exists('media/photos'): shutil.rmtree('media/photos') shutil.copytree('media/photos-sample', 'media/photos') super(SampleFilesTestCase, self)._fixture_setup() from django_fixmystreet.fixmystreet.tests.views import * from django_fixmystreet.fixmystreet.tests.reports import * from django_fixmystreet.fixmystreet.tests.users import * from django_fixmystreet.fixmystreet.tests.organisation_entity import * from django_fixmystreet.fixmystreet.tests.mail import * # from django_fixmystreet.fixmystreet.tests.api import *
Fix unit test fixtures files
Fix unit test fixtures files
Python
agpl-3.0
IMIO/django-fixmystreet,IMIO/django-fixmystreet,IMIO/django-fixmystreet,IMIO/django-fixmystreet
import shutil import os from django.core.files.storage import default_storage from django.test import TestCase class SampleFilesTestCase(TestCase): fixtures = ['sample'] @classmethod def setUpClass(cls): default_storage.location = 'media' # force using source media folder to avoid real data erasing # @classmethod # def setUpClass(cls): # shutil.copytree('media', 'media-tmp') # default_storage.location = 'media-tmp' # # @classmethod # def tearDownClass(self): # shutil.rmtree('media-tmp') def _fixture_setup(self): if os.path.exists('media/photos'): shutil.rmtree('media/photos') shutil.copytree('media/photos-sample', 'media/photos') super(SampleFilesTestCase, self)._fixture_setup() def tearDown(self): shutil.rmtree('media/photos') from django_fixmystreet.fixmystreet.tests.views import * from django_fixmystreet.fixmystreet.tests.reports import * from django_fixmystreet.fixmystreet.tests.users import * from django_fixmystreet.fixmystreet.tests.organisation_entity import * from django_fixmystreet.fixmystreet.tests.mail import * # from django_fixmystreet.fixmystreet.tests.api import * Fix unit test fixtures files
import shutil import os from django.core.files.storage import default_storage from django.test import TestCase class SampleFilesTestCase(TestCase): fixtures = ['sample'] @classmethod def setUpClass(cls): default_storage.location = 'media' # force using source media folder to avoid real data erasing # @classmethod # def setUpClass(cls): # shutil.copytree('media', 'media-tmp') # default_storage.location = 'media-tmp' # # @classmethod # def tearDownClass(self): # shutil.rmtree('media-tmp') def _fixture_setup(self): if os.path.exists('media/photos'): shutil.rmtree('media/photos') shutil.copytree('media/photos-sample', 'media/photos') super(SampleFilesTestCase, self)._fixture_setup() from django_fixmystreet.fixmystreet.tests.views import * from django_fixmystreet.fixmystreet.tests.reports import * from django_fixmystreet.fixmystreet.tests.users import * from django_fixmystreet.fixmystreet.tests.organisation_entity import * from django_fixmystreet.fixmystreet.tests.mail import * # from django_fixmystreet.fixmystreet.tests.api import *
<commit_before>import shutil import os from django.core.files.storage import default_storage from django.test import TestCase class SampleFilesTestCase(TestCase): fixtures = ['sample'] @classmethod def setUpClass(cls): default_storage.location = 'media' # force using source media folder to avoid real data erasing # @classmethod # def setUpClass(cls): # shutil.copytree('media', 'media-tmp') # default_storage.location = 'media-tmp' # # @classmethod # def tearDownClass(self): # shutil.rmtree('media-tmp') def _fixture_setup(self): if os.path.exists('media/photos'): shutil.rmtree('media/photos') shutil.copytree('media/photos-sample', 'media/photos') super(SampleFilesTestCase, self)._fixture_setup() def tearDown(self): shutil.rmtree('media/photos') from django_fixmystreet.fixmystreet.tests.views import * from django_fixmystreet.fixmystreet.tests.reports import * from django_fixmystreet.fixmystreet.tests.users import * from django_fixmystreet.fixmystreet.tests.organisation_entity import * from django_fixmystreet.fixmystreet.tests.mail import * # from django_fixmystreet.fixmystreet.tests.api import * <commit_msg>Fix unit test fixtures files<commit_after>
import shutil import os from django.core.files.storage import default_storage from django.test import TestCase class SampleFilesTestCase(TestCase): fixtures = ['sample'] @classmethod def setUpClass(cls): default_storage.location = 'media' # force using source media folder to avoid real data erasing # @classmethod # def setUpClass(cls): # shutil.copytree('media', 'media-tmp') # default_storage.location = 'media-tmp' # # @classmethod # def tearDownClass(self): # shutil.rmtree('media-tmp') def _fixture_setup(self): if os.path.exists('media/photos'): shutil.rmtree('media/photos') shutil.copytree('media/photos-sample', 'media/photos') super(SampleFilesTestCase, self)._fixture_setup() from django_fixmystreet.fixmystreet.tests.views import * from django_fixmystreet.fixmystreet.tests.reports import * from django_fixmystreet.fixmystreet.tests.users import * from django_fixmystreet.fixmystreet.tests.organisation_entity import * from django_fixmystreet.fixmystreet.tests.mail import * # from django_fixmystreet.fixmystreet.tests.api import *
import shutil import os from django.core.files.storage import default_storage from django.test import TestCase class SampleFilesTestCase(TestCase): fixtures = ['sample'] @classmethod def setUpClass(cls): default_storage.location = 'media' # force using source media folder to avoid real data erasing # @classmethod # def setUpClass(cls): # shutil.copytree('media', 'media-tmp') # default_storage.location = 'media-tmp' # # @classmethod # def tearDownClass(self): # shutil.rmtree('media-tmp') def _fixture_setup(self): if os.path.exists('media/photos'): shutil.rmtree('media/photos') shutil.copytree('media/photos-sample', 'media/photos') super(SampleFilesTestCase, self)._fixture_setup() def tearDown(self): shutil.rmtree('media/photos') from django_fixmystreet.fixmystreet.tests.views import * from django_fixmystreet.fixmystreet.tests.reports import * from django_fixmystreet.fixmystreet.tests.users import * from django_fixmystreet.fixmystreet.tests.organisation_entity import * from django_fixmystreet.fixmystreet.tests.mail import * # from django_fixmystreet.fixmystreet.tests.api import * Fix unit test fixtures filesimport shutil import os from django.core.files.storage import default_storage from django.test import TestCase class SampleFilesTestCase(TestCase): fixtures = ['sample'] @classmethod def setUpClass(cls): default_storage.location = 'media' # force using source media folder to avoid real data erasing # @classmethod # def setUpClass(cls): # shutil.copytree('media', 'media-tmp') # default_storage.location = 'media-tmp' # # @classmethod # def tearDownClass(self): # shutil.rmtree('media-tmp') def _fixture_setup(self): if os.path.exists('media/photos'): shutil.rmtree('media/photos') shutil.copytree('media/photos-sample', 'media/photos') super(SampleFilesTestCase, self)._fixture_setup() from django_fixmystreet.fixmystreet.tests.views import * from django_fixmystreet.fixmystreet.tests.reports import * from django_fixmystreet.fixmystreet.tests.users import * from django_fixmystreet.fixmystreet.tests.organisation_entity import * from django_fixmystreet.fixmystreet.tests.mail import * # from django_fixmystreet.fixmystreet.tests.api import *
<commit_before>import shutil import os from django.core.files.storage import default_storage from django.test import TestCase class SampleFilesTestCase(TestCase): fixtures = ['sample'] @classmethod def setUpClass(cls): default_storage.location = 'media' # force using source media folder to avoid real data erasing # @classmethod # def setUpClass(cls): # shutil.copytree('media', 'media-tmp') # default_storage.location = 'media-tmp' # # @classmethod # def tearDownClass(self): # shutil.rmtree('media-tmp') def _fixture_setup(self): if os.path.exists('media/photos'): shutil.rmtree('media/photos') shutil.copytree('media/photos-sample', 'media/photos') super(SampleFilesTestCase, self)._fixture_setup() def tearDown(self): shutil.rmtree('media/photos') from django_fixmystreet.fixmystreet.tests.views import * from django_fixmystreet.fixmystreet.tests.reports import * from django_fixmystreet.fixmystreet.tests.users import * from django_fixmystreet.fixmystreet.tests.organisation_entity import * from django_fixmystreet.fixmystreet.tests.mail import * # from django_fixmystreet.fixmystreet.tests.api import * <commit_msg>Fix unit test fixtures files<commit_after>import shutil import os from django.core.files.storage import default_storage from django.test import TestCase class SampleFilesTestCase(TestCase): fixtures = ['sample'] @classmethod def setUpClass(cls): default_storage.location = 'media' # force using source media folder to avoid real data erasing # @classmethod # def setUpClass(cls): # shutil.copytree('media', 'media-tmp') # default_storage.location = 'media-tmp' # # @classmethod # def tearDownClass(self): # shutil.rmtree('media-tmp') def _fixture_setup(self): if os.path.exists('media/photos'): shutil.rmtree('media/photos') shutil.copytree('media/photos-sample', 'media/photos') super(SampleFilesTestCase, self)._fixture_setup() from django_fixmystreet.fixmystreet.tests.views import * from django_fixmystreet.fixmystreet.tests.reports import * from django_fixmystreet.fixmystreet.tests.users import * from django_fixmystreet.fixmystreet.tests.organisation_entity import * from django_fixmystreet.fixmystreet.tests.mail import * # from django_fixmystreet.fixmystreet.tests.api import *
1020bf478da327ddb805b28c6676c58ccef6675e
{{cookiecutter.repo_name}}/tests/test_cli.py
{{cookiecutter.repo_name}}/tests/test_cli.py
import pytest from click.testing import CliRunner from cli import main @pytest.fixture def runner(): return CliRunner() @pytest.fixture(params=['fr', 'en', 'tlh']) def lang(request): return request.param @pytest.fixture(params=['-l', '--language']) def cli_param(request): return request.param @pytest.fixture def mock_app(mocker): return mocker.patch('{{cookiecutter.repo_name}}.{{cookiecutter.app_class_name}}') def test_language_to_app(runner, mock_app, cli_param, lang): result = runner.invoke(main, [cli_param,lang]) assert result.exit_code == 0 mock_app.assert_called_once_with(lang) def test_abort_with_invalid_lang(runner, mock_app): result = runner.invoke(main, ['-l', 'foobar']) assert result.exit_code != 0 assert not mock_app.called
import pytest from click.testing import CliRunner from cli import main @pytest.fixture def runner(): return CliRunner() @pytest.fixture(params=['fr', 'en', 'tlh']) def lang(request): return request.param @pytest.fixture(params=['-l', '--language']) def cli_param(request): return request.param @pytest.fixture def mock_app(mocker): return mocker.patch('{{cookiecutter.repo_name}}.cli.{{cookiecutter.app_class_name}}') def test_language_to_app(runner, mock_app, cli_param, lang): result = runner.invoke(main, [cli_param,lang]) assert result.exit_code == 0 mock_app.assert_called_once_with(lang) def test_abort_with_invalid_lang(runner, mock_app): result = runner.invoke(main, ['-l', 'foobar']) assert result.exit_code != 0 assert not mock_app.called
Fix mock to import app from cli
Fix mock to import app from cli
Python
mit
hackebrot/cookiedozer,hackebrot/cookiedozer
import pytest from click.testing import CliRunner from cli import main @pytest.fixture def runner(): return CliRunner() @pytest.fixture(params=['fr', 'en', 'tlh']) def lang(request): return request.param @pytest.fixture(params=['-l', '--language']) def cli_param(request): return request.param @pytest.fixture def mock_app(mocker): return mocker.patch('{{cookiecutter.repo_name}}.{{cookiecutter.app_class_name}}') def test_language_to_app(runner, mock_app, cli_param, lang): result = runner.invoke(main, [cli_param,lang]) assert result.exit_code == 0 mock_app.assert_called_once_with(lang) def test_abort_with_invalid_lang(runner, mock_app): result = runner.invoke(main, ['-l', 'foobar']) assert result.exit_code != 0 assert not mock_app.called Fix mock to import app from cli
import pytest from click.testing import CliRunner from cli import main @pytest.fixture def runner(): return CliRunner() @pytest.fixture(params=['fr', 'en', 'tlh']) def lang(request): return request.param @pytest.fixture(params=['-l', '--language']) def cli_param(request): return request.param @pytest.fixture def mock_app(mocker): return mocker.patch('{{cookiecutter.repo_name}}.cli.{{cookiecutter.app_class_name}}') def test_language_to_app(runner, mock_app, cli_param, lang): result = runner.invoke(main, [cli_param,lang]) assert result.exit_code == 0 mock_app.assert_called_once_with(lang) def test_abort_with_invalid_lang(runner, mock_app): result = runner.invoke(main, ['-l', 'foobar']) assert result.exit_code != 0 assert not mock_app.called
<commit_before>import pytest from click.testing import CliRunner from cli import main @pytest.fixture def runner(): return CliRunner() @pytest.fixture(params=['fr', 'en', 'tlh']) def lang(request): return request.param @pytest.fixture(params=['-l', '--language']) def cli_param(request): return request.param @pytest.fixture def mock_app(mocker): return mocker.patch('{{cookiecutter.repo_name}}.{{cookiecutter.app_class_name}}') def test_language_to_app(runner, mock_app, cli_param, lang): result = runner.invoke(main, [cli_param,lang]) assert result.exit_code == 0 mock_app.assert_called_once_with(lang) def test_abort_with_invalid_lang(runner, mock_app): result = runner.invoke(main, ['-l', 'foobar']) assert result.exit_code != 0 assert not mock_app.called <commit_msg>Fix mock to import app from cli<commit_after>
import pytest from click.testing import CliRunner from cli import main @pytest.fixture def runner(): return CliRunner() @pytest.fixture(params=['fr', 'en', 'tlh']) def lang(request): return request.param @pytest.fixture(params=['-l', '--language']) def cli_param(request): return request.param @pytest.fixture def mock_app(mocker): return mocker.patch('{{cookiecutter.repo_name}}.cli.{{cookiecutter.app_class_name}}') def test_language_to_app(runner, mock_app, cli_param, lang): result = runner.invoke(main, [cli_param,lang]) assert result.exit_code == 0 mock_app.assert_called_once_with(lang) def test_abort_with_invalid_lang(runner, mock_app): result = runner.invoke(main, ['-l', 'foobar']) assert result.exit_code != 0 assert not mock_app.called
import pytest from click.testing import CliRunner from cli import main @pytest.fixture def runner(): return CliRunner() @pytest.fixture(params=['fr', 'en', 'tlh']) def lang(request): return request.param @pytest.fixture(params=['-l', '--language']) def cli_param(request): return request.param @pytest.fixture def mock_app(mocker): return mocker.patch('{{cookiecutter.repo_name}}.{{cookiecutter.app_class_name}}') def test_language_to_app(runner, mock_app, cli_param, lang): result = runner.invoke(main, [cli_param,lang]) assert result.exit_code == 0 mock_app.assert_called_once_with(lang) def test_abort_with_invalid_lang(runner, mock_app): result = runner.invoke(main, ['-l', 'foobar']) assert result.exit_code != 0 assert not mock_app.called Fix mock to import app from cliimport pytest from click.testing import CliRunner from cli import main @pytest.fixture def runner(): return CliRunner() @pytest.fixture(params=['fr', 'en', 'tlh']) def lang(request): return request.param @pytest.fixture(params=['-l', '--language']) def cli_param(request): return request.param @pytest.fixture def mock_app(mocker): return mocker.patch('{{cookiecutter.repo_name}}.cli.{{cookiecutter.app_class_name}}') def test_language_to_app(runner, mock_app, cli_param, lang): result = runner.invoke(main, [cli_param,lang]) assert result.exit_code == 0 mock_app.assert_called_once_with(lang) def test_abort_with_invalid_lang(runner, mock_app): result = runner.invoke(main, ['-l', 'foobar']) assert result.exit_code != 0 assert not mock_app.called
<commit_before>import pytest from click.testing import CliRunner from cli import main @pytest.fixture def runner(): return CliRunner() @pytest.fixture(params=['fr', 'en', 'tlh']) def lang(request): return request.param @pytest.fixture(params=['-l', '--language']) def cli_param(request): return request.param @pytest.fixture def mock_app(mocker): return mocker.patch('{{cookiecutter.repo_name}}.{{cookiecutter.app_class_name}}') def test_language_to_app(runner, mock_app, cli_param, lang): result = runner.invoke(main, [cli_param,lang]) assert result.exit_code == 0 mock_app.assert_called_once_with(lang) def test_abort_with_invalid_lang(runner, mock_app): result = runner.invoke(main, ['-l', 'foobar']) assert result.exit_code != 0 assert not mock_app.called <commit_msg>Fix mock to import app from cli<commit_after>import pytest from click.testing import CliRunner from cli import main @pytest.fixture def runner(): return CliRunner() @pytest.fixture(params=['fr', 'en', 'tlh']) def lang(request): return request.param @pytest.fixture(params=['-l', '--language']) def cli_param(request): return request.param @pytest.fixture def mock_app(mocker): return mocker.patch('{{cookiecutter.repo_name}}.cli.{{cookiecutter.app_class_name}}') def test_language_to_app(runner, mock_app, cli_param, lang): result = runner.invoke(main, [cli_param,lang]) assert result.exit_code == 0 mock_app.assert_called_once_with(lang) def test_abort_with_invalid_lang(runner, mock_app): result = runner.invoke(main, ['-l', 'foobar']) assert result.exit_code != 0 assert not mock_app.called
faa4125dd8c491eb360ccfea5609a0dabb3cccda
fluent/apps.py
fluent/apps.py
try: # Configure a generator if the user is using model_mommy from model_mommy import generators def gen_translatablecontent(max_length): from fluent.fields import TranslatableContent return TranslatableContent(text=generators.gen_string(max_length)) gen_translatablecontent.required = ['max_length'] MOMMY_CUSTOM_FIELDS_GEN = { 'fluent.fields.TranslatableField': gen_translatablecontent, } except ImportError: pass from django.apps import AppConfig class FluentAppConfig(AppConfig): pass
try: # Configure a generator if the user is using model_mommy from model_mommy import generators def gen_translatablecontent(max_length): from fluent.fields import TranslatableContent return TranslatableContent(text=generators.gen_string(max_length)) gen_translatablecontent.required = ['max_length'] MOMMY_CUSTOM_FIELDS_GEN = { 'fluent.fields.TranslatableField': gen_translatablecontent, } except ImportError: pass from django.apps import AppConfig class FluentAppConfig(AppConfig): name = "fluent"
Add missing name to the AppConfig
Add missing name to the AppConfig
Python
mit
potatolondon/fluent-2.0,potatolondon/fluent-2.0
try: # Configure a generator if the user is using model_mommy from model_mommy import generators def gen_translatablecontent(max_length): from fluent.fields import TranslatableContent return TranslatableContent(text=generators.gen_string(max_length)) gen_translatablecontent.required = ['max_length'] MOMMY_CUSTOM_FIELDS_GEN = { 'fluent.fields.TranslatableField': gen_translatablecontent, } except ImportError: pass from django.apps import AppConfig class FluentAppConfig(AppConfig): pass Add missing name to the AppConfig
try: # Configure a generator if the user is using model_mommy from model_mommy import generators def gen_translatablecontent(max_length): from fluent.fields import TranslatableContent return TranslatableContent(text=generators.gen_string(max_length)) gen_translatablecontent.required = ['max_length'] MOMMY_CUSTOM_FIELDS_GEN = { 'fluent.fields.TranslatableField': gen_translatablecontent, } except ImportError: pass from django.apps import AppConfig class FluentAppConfig(AppConfig): name = "fluent"
<commit_before> try: # Configure a generator if the user is using model_mommy from model_mommy import generators def gen_translatablecontent(max_length): from fluent.fields import TranslatableContent return TranslatableContent(text=generators.gen_string(max_length)) gen_translatablecontent.required = ['max_length'] MOMMY_CUSTOM_FIELDS_GEN = { 'fluent.fields.TranslatableField': gen_translatablecontent, } except ImportError: pass from django.apps import AppConfig class FluentAppConfig(AppConfig): pass <commit_msg>Add missing name to the AppConfig<commit_after>
try: # Configure a generator if the user is using model_mommy from model_mommy import generators def gen_translatablecontent(max_length): from fluent.fields import TranslatableContent return TranslatableContent(text=generators.gen_string(max_length)) gen_translatablecontent.required = ['max_length'] MOMMY_CUSTOM_FIELDS_GEN = { 'fluent.fields.TranslatableField': gen_translatablecontent, } except ImportError: pass from django.apps import AppConfig class FluentAppConfig(AppConfig): name = "fluent"
try: # Configure a generator if the user is using model_mommy from model_mommy import generators def gen_translatablecontent(max_length): from fluent.fields import TranslatableContent return TranslatableContent(text=generators.gen_string(max_length)) gen_translatablecontent.required = ['max_length'] MOMMY_CUSTOM_FIELDS_GEN = { 'fluent.fields.TranslatableField': gen_translatablecontent, } except ImportError: pass from django.apps import AppConfig class FluentAppConfig(AppConfig): pass Add missing name to the AppConfig try: # Configure a generator if the user is using model_mommy from model_mommy import generators def gen_translatablecontent(max_length): from fluent.fields import TranslatableContent return TranslatableContent(text=generators.gen_string(max_length)) gen_translatablecontent.required = ['max_length'] MOMMY_CUSTOM_FIELDS_GEN = { 'fluent.fields.TranslatableField': gen_translatablecontent, } except ImportError: pass from django.apps import AppConfig class FluentAppConfig(AppConfig): name = "fluent"
<commit_before> try: # Configure a generator if the user is using model_mommy from model_mommy import generators def gen_translatablecontent(max_length): from fluent.fields import TranslatableContent return TranslatableContent(text=generators.gen_string(max_length)) gen_translatablecontent.required = ['max_length'] MOMMY_CUSTOM_FIELDS_GEN = { 'fluent.fields.TranslatableField': gen_translatablecontent, } except ImportError: pass from django.apps import AppConfig class FluentAppConfig(AppConfig): pass <commit_msg>Add missing name to the AppConfig<commit_after> try: # Configure a generator if the user is using model_mommy from model_mommy import generators def gen_translatablecontent(max_length): from fluent.fields import TranslatableContent return TranslatableContent(text=generators.gen_string(max_length)) gen_translatablecontent.required = ['max_length'] MOMMY_CUSTOM_FIELDS_GEN = { 'fluent.fields.TranslatableField': gen_translatablecontent, } except ImportError: pass from django.apps import AppConfig class FluentAppConfig(AppConfig): name = "fluent"
8812341b705e6cec98b2708d0a1481d769f5f476
salt/runners/config.py
salt/runners/config.py
# -*- coding: utf-8 -*- ''' This runner is designed to mirror the execution module config.py, but for master settings ''' from __future__ import absolute_import from __future__ import print_function import salt.utils def get(key, default='', delimiter=':'): ''' Retrieve master config options, with optional nesting via the delimiter argument. **Arguments** default If the key is not found, the default will be returned instead delimiter Override the delimiter used to separate nested levels of a data structure. CLI Example: .. code-block:: bash salt-run config.get gitfs_remotes salt-run config.get file_roots:base salt-run config.get file_roots,base delimiter=',' ''' return salt.utils.traverse_dict_and_list(__opts__, key, delimiter=delimiter)
# -*- coding: utf-8 -*- ''' This runner is designed to mirror the execution module config.py, but for master settings ''' from __future__ import absolute_import from __future__ import print_function import salt.utils import salt.utils.sdb def get(key, default='', delimiter=':'): ''' Retrieve master config options, with optional nesting via the delimiter argument. **Arguments** default If the key is not found, the default will be returned instead delimiter Override the delimiter used to separate nested levels of a data structure. CLI Example: .. code-block:: bash salt-run config.get gitfs_remotes salt-run config.get file_roots:base salt-run config.get file_roots,base delimiter=',' ''' ret = salt.utils.traverse_dict_and_list(__opts__, key, default='_|-', delimiter=delimiter) if ret == '_|-': return default else: return salt.utils.sdb.sdb_get(ret, __opts__)
Add sdb support, and also properly return the default
Add sdb support, and also properly return the default
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
# -*- coding: utf-8 -*- ''' This runner is designed to mirror the execution module config.py, but for master settings ''' from __future__ import absolute_import from __future__ import print_function import salt.utils def get(key, default='', delimiter=':'): ''' Retrieve master config options, with optional nesting via the delimiter argument. **Arguments** default If the key is not found, the default will be returned instead delimiter Override the delimiter used to separate nested levels of a data structure. CLI Example: .. code-block:: bash salt-run config.get gitfs_remotes salt-run config.get file_roots:base salt-run config.get file_roots,base delimiter=',' ''' return salt.utils.traverse_dict_and_list(__opts__, key, delimiter=delimiter) Add sdb support, and also properly return the default
# -*- coding: utf-8 -*- ''' This runner is designed to mirror the execution module config.py, but for master settings ''' from __future__ import absolute_import from __future__ import print_function import salt.utils import salt.utils.sdb def get(key, default='', delimiter=':'): ''' Retrieve master config options, with optional nesting via the delimiter argument. **Arguments** default If the key is not found, the default will be returned instead delimiter Override the delimiter used to separate nested levels of a data structure. CLI Example: .. code-block:: bash salt-run config.get gitfs_remotes salt-run config.get file_roots:base salt-run config.get file_roots,base delimiter=',' ''' ret = salt.utils.traverse_dict_and_list(__opts__, key, default='_|-', delimiter=delimiter) if ret == '_|-': return default else: return salt.utils.sdb.sdb_get(ret, __opts__)
<commit_before># -*- coding: utf-8 -*- ''' This runner is designed to mirror the execution module config.py, but for master settings ''' from __future__ import absolute_import from __future__ import print_function import salt.utils def get(key, default='', delimiter=':'): ''' Retrieve master config options, with optional nesting via the delimiter argument. **Arguments** default If the key is not found, the default will be returned instead delimiter Override the delimiter used to separate nested levels of a data structure. CLI Example: .. code-block:: bash salt-run config.get gitfs_remotes salt-run config.get file_roots:base salt-run config.get file_roots,base delimiter=',' ''' return salt.utils.traverse_dict_and_list(__opts__, key, delimiter=delimiter) <commit_msg>Add sdb support, and also properly return the default<commit_after>
# -*- coding: utf-8 -*- ''' This runner is designed to mirror the execution module config.py, but for master settings ''' from __future__ import absolute_import from __future__ import print_function import salt.utils import salt.utils.sdb def get(key, default='', delimiter=':'): ''' Retrieve master config options, with optional nesting via the delimiter argument. **Arguments** default If the key is not found, the default will be returned instead delimiter Override the delimiter used to separate nested levels of a data structure. CLI Example: .. code-block:: bash salt-run config.get gitfs_remotes salt-run config.get file_roots:base salt-run config.get file_roots,base delimiter=',' ''' ret = salt.utils.traverse_dict_and_list(__opts__, key, default='_|-', delimiter=delimiter) if ret == '_|-': return default else: return salt.utils.sdb.sdb_get(ret, __opts__)
# -*- coding: utf-8 -*- ''' This runner is designed to mirror the execution module config.py, but for master settings ''' from __future__ import absolute_import from __future__ import print_function import salt.utils def get(key, default='', delimiter=':'): ''' Retrieve master config options, with optional nesting via the delimiter argument. **Arguments** default If the key is not found, the default will be returned instead delimiter Override the delimiter used to separate nested levels of a data structure. CLI Example: .. code-block:: bash salt-run config.get gitfs_remotes salt-run config.get file_roots:base salt-run config.get file_roots,base delimiter=',' ''' return salt.utils.traverse_dict_and_list(__opts__, key, delimiter=delimiter) Add sdb support, and also properly return the default# -*- coding: utf-8 -*- ''' This runner is designed to mirror the execution module config.py, but for master settings ''' from __future__ import absolute_import from __future__ import print_function import salt.utils import salt.utils.sdb def get(key, default='', delimiter=':'): ''' Retrieve master config options, with optional nesting via the delimiter argument. **Arguments** default If the key is not found, the default will be returned instead delimiter Override the delimiter used to separate nested levels of a data structure. CLI Example: .. code-block:: bash salt-run config.get gitfs_remotes salt-run config.get file_roots:base salt-run config.get file_roots,base delimiter=',' ''' ret = salt.utils.traverse_dict_and_list(__opts__, key, default='_|-', delimiter=delimiter) if ret == '_|-': return default else: return salt.utils.sdb.sdb_get(ret, __opts__)
<commit_before># -*- coding: utf-8 -*- ''' This runner is designed to mirror the execution module config.py, but for master settings ''' from __future__ import absolute_import from __future__ import print_function import salt.utils def get(key, default='', delimiter=':'): ''' Retrieve master config options, with optional nesting via the delimiter argument. **Arguments** default If the key is not found, the default will be returned instead delimiter Override the delimiter used to separate nested levels of a data structure. CLI Example: .. code-block:: bash salt-run config.get gitfs_remotes salt-run config.get file_roots:base salt-run config.get file_roots,base delimiter=',' ''' return salt.utils.traverse_dict_and_list(__opts__, key, delimiter=delimiter) <commit_msg>Add sdb support, and also properly return the default<commit_after># -*- coding: utf-8 -*- ''' This runner is designed to mirror the execution module config.py, but for master settings ''' from __future__ import absolute_import from __future__ import print_function import salt.utils import salt.utils.sdb def get(key, default='', delimiter=':'): ''' Retrieve master config options, with optional nesting via the delimiter argument. **Arguments** default If the key is not found, the default will be returned instead delimiter Override the delimiter used to separate nested levels of a data structure. CLI Example: .. code-block:: bash salt-run config.get gitfs_remotes salt-run config.get file_roots:base salt-run config.get file_roots,base delimiter=',' ''' ret = salt.utils.traverse_dict_and_list(__opts__, key, default='_|-', delimiter=delimiter) if ret == '_|-': return default else: return salt.utils.sdb.sdb_get(ret, __opts__)
4e9c0cb3cd0d74ce008f0279bc6e9ec353c03fee
senlin_dashboard/api/utils.py
senlin_dashboard/api/utils.py
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import itertools def update_pagination(entities, request_size, page_size, marker, sort_dir, sort_key, reversed_order): has_prev_data = False has_more_data = False entities = list(itertools.islice(entities, request_size)) # first and middle page condition if len(entities) > page_size: entities.pop(-1) has_more_data = True # middle page condition if marker is not None: has_prev_data = True # first page condition when reached via prev back elif reversed_order and marker is not None: has_more_data = True # last page condition elif marker is not None: has_prev_data = True # restore the original ordering here if reversed_order: entities = sorted(entities, key=lambda entity: (getattr(entity, sort_key)), reverse=(sort_dir == sort_dir)) return entities, has_more_data, has_prev_data
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import itertools def update_pagination(entities, request_size, page_size, marker, sort_dir, sort_key, reversed_order): has_prev_data = False has_more_data = False entities = list(itertools.islice(entities, request_size)) # first and middle page condition if len(entities) > page_size: entities.pop(-1) has_more_data = True # middle page condition if marker is not None: has_prev_data = True # first page condition when reached via prev back elif reversed_order and marker is not None: has_more_data = True # last page condition elif marker is not None: has_prev_data = True # restore the original ordering here if reversed_order: entities.reverse() return entities, has_more_data, has_prev_data
Use entities.reverse() rather sorted(.., reverse=True)
Use entities.reverse() rather sorted(.., reverse=True) Change-Id: I33ee5b078e3d27a45bd159be0f0b241c20792f92
Python
apache-2.0
openstack/senlin-dashboard,stackforge/senlin-dashboard,stackforge/senlin-dashboard,openstack/senlin-dashboard,stackforge/senlin-dashboard,openstack/senlin-dashboard,openstack/senlin-dashboard
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import itertools def update_pagination(entities, request_size, page_size, marker, sort_dir, sort_key, reversed_order): has_prev_data = False has_more_data = False entities = list(itertools.islice(entities, request_size)) # first and middle page condition if len(entities) > page_size: entities.pop(-1) has_more_data = True # middle page condition if marker is not None: has_prev_data = True # first page condition when reached via prev back elif reversed_order and marker is not None: has_more_data = True # last page condition elif marker is not None: has_prev_data = True # restore the original ordering here if reversed_order: entities = sorted(entities, key=lambda entity: (getattr(entity, sort_key)), reverse=(sort_dir == sort_dir)) return entities, has_more_data, has_prev_data Use entities.reverse() rather sorted(.., reverse=True) Change-Id: I33ee5b078e3d27a45bd159be0f0b241c20792f92
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import itertools def update_pagination(entities, request_size, page_size, marker, sort_dir, sort_key, reversed_order): has_prev_data = False has_more_data = False entities = list(itertools.islice(entities, request_size)) # first and middle page condition if len(entities) > page_size: entities.pop(-1) has_more_data = True # middle page condition if marker is not None: has_prev_data = True # first page condition when reached via prev back elif reversed_order and marker is not None: has_more_data = True # last page condition elif marker is not None: has_prev_data = True # restore the original ordering here if reversed_order: entities.reverse() return entities, has_more_data, has_prev_data
<commit_before># Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import itertools def update_pagination(entities, request_size, page_size, marker, sort_dir, sort_key, reversed_order): has_prev_data = False has_more_data = False entities = list(itertools.islice(entities, request_size)) # first and middle page condition if len(entities) > page_size: entities.pop(-1) has_more_data = True # middle page condition if marker is not None: has_prev_data = True # first page condition when reached via prev back elif reversed_order and marker is not None: has_more_data = True # last page condition elif marker is not None: has_prev_data = True # restore the original ordering here if reversed_order: entities = sorted(entities, key=lambda entity: (getattr(entity, sort_key)), reverse=(sort_dir == sort_dir)) return entities, has_more_data, has_prev_data <commit_msg>Use entities.reverse() rather sorted(.., reverse=True) Change-Id: I33ee5b078e3d27a45bd159be0f0b241c20792f92<commit_after>
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import itertools def update_pagination(entities, request_size, page_size, marker, sort_dir, sort_key, reversed_order): has_prev_data = False has_more_data = False entities = list(itertools.islice(entities, request_size)) # first and middle page condition if len(entities) > page_size: entities.pop(-1) has_more_data = True # middle page condition if marker is not None: has_prev_data = True # first page condition when reached via prev back elif reversed_order and marker is not None: has_more_data = True # last page condition elif marker is not None: has_prev_data = True # restore the original ordering here if reversed_order: entities.reverse() return entities, has_more_data, has_prev_data
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import itertools def update_pagination(entities, request_size, page_size, marker, sort_dir, sort_key, reversed_order): has_prev_data = False has_more_data = False entities = list(itertools.islice(entities, request_size)) # first and middle page condition if len(entities) > page_size: entities.pop(-1) has_more_data = True # middle page condition if marker is not None: has_prev_data = True # first page condition when reached via prev back elif reversed_order and marker is not None: has_more_data = True # last page condition elif marker is not None: has_prev_data = True # restore the original ordering here if reversed_order: entities = sorted(entities, key=lambda entity: (getattr(entity, sort_key)), reverse=(sort_dir == sort_dir)) return entities, has_more_data, has_prev_data Use entities.reverse() rather sorted(.., reverse=True) Change-Id: I33ee5b078e3d27a45bd159be0f0b241c20792f92# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import itertools def update_pagination(entities, request_size, page_size, marker, sort_dir, sort_key, reversed_order): has_prev_data = False has_more_data = False entities = list(itertools.islice(entities, request_size)) # first and middle page condition if len(entities) > page_size: entities.pop(-1) has_more_data = True # middle page condition if marker is not None: has_prev_data = True # first page condition when reached via prev back elif reversed_order and marker is not None: has_more_data = True # last page condition elif marker is not None: has_prev_data = True # restore the original ordering here if reversed_order: entities.reverse() return entities, has_more_data, has_prev_data
<commit_before># Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import itertools def update_pagination(entities, request_size, page_size, marker, sort_dir, sort_key, reversed_order): has_prev_data = False has_more_data = False entities = list(itertools.islice(entities, request_size)) # first and middle page condition if len(entities) > page_size: entities.pop(-1) has_more_data = True # middle page condition if marker is not None: has_prev_data = True # first page condition when reached via prev back elif reversed_order and marker is not None: has_more_data = True # last page condition elif marker is not None: has_prev_data = True # restore the original ordering here if reversed_order: entities = sorted(entities, key=lambda entity: (getattr(entity, sort_key)), reverse=(sort_dir == sort_dir)) return entities, has_more_data, has_prev_data <commit_msg>Use entities.reverse() rather sorted(.., reverse=True) Change-Id: I33ee5b078e3d27a45bd159be0f0b241c20792f92<commit_after># Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import itertools def update_pagination(entities, request_size, page_size, marker, sort_dir, sort_key, reversed_order): has_prev_data = False has_more_data = False entities = list(itertools.islice(entities, request_size)) # first and middle page condition if len(entities) > page_size: entities.pop(-1) has_more_data = True # middle page condition if marker is not None: has_prev_data = True # first page condition when reached via prev back elif reversed_order and marker is not None: has_more_data = True # last page condition elif marker is not None: has_prev_data = True # restore the original ordering here if reversed_order: entities.reverse() return entities, has_more_data, has_prev_data
5812aae9059ede1a3cb19be9033ebc435d5ebb94
scripts/create_user.py
scripts/create_user.py
#!/usr/bin/env python # -*- coding: utf-8 -*- #============================================================================== # Script for creating MySQL user #============================================================================== import os import sys import mysql.connector from mysql.connector import errorcode sys.path.insert(1, '../src') from config import config from sql.tables import TABLES if __name__ == '__main__': if len(sys.argv) < 3: print('There is not enough arguments.') print('Use following arguments:') print('\tpython {} config.ini MYSQL_ROOT_PASSWORD'.format( os.path.basename(__file__))) sys.exit(1) # Open connection to MySQL server and get cursor cnx = mysql.connector.connect( host=config['mysql_host'], user='root', password=config['mysql_root_pass']) cursor = cnx.cursor() # Create MySql user command = ''' CREATE USER '{}'@'{}' IDENTIFIED BY '{}'; GRANT ALL PRIVILEGES ON *.* TO '{}'@'{}'; FLUSH PRIVILEGES; '''.format(config['mysql_user'], config['mysql_host'], config['mysql_pass'], config['mysql_user'], config['mysql_host']) try: print("Creating user '{}' identified by {}: ".format( config['mysql_user'], config['mysql_pass']), end='') cursor.execute(command, multi=True) except mysql.connector.Error as err: print(err.msg) else: print("OK") # Close connection and database cursor.close() cnx.close()
#!/usr/bin/env python # -*- coding: utf-8 -*- #============================================================================== # Script for creating MySQL user #============================================================================== import os import sys import mysql.connector from mysql.connector import errorcode sys.path.insert(1, '../src') from config import config from sql.tables import TABLES if __name__ == '__main__': if len(sys.argv) < 3: print('There is not enough arguments.') print('Use following arguments:') print('\tpython {} config.ini MYSQL_ROOT_PASSWORD'.format( os.path.basename(__file__))) sys.exit(1) # Open connection to MySQL server and get cursor cnx = mysql.connector.connect( host=config['mysql_host'], user='root', password=sys.argv[2]) cursor = cnx.cursor() # Create MySql user command = ''' CREATE USER '{}'@'{}' IDENTIFIED BY '{}'; GRANT ALL PRIVILEGES ON *.* TO '{}'@'{}'; FLUSH PRIVILEGES; '''.format(config['mysql_user'], config['mysql_host'], config['mysql_pass'], config['mysql_user'], config['mysql_host']) try: print("Creating user '{}' identified by {}: ".format( config['mysql_user'], config['mysql_pass']), end='') cursor.execute(command, multi=True) except mysql.connector.Error as err: print(err.msg) else: print("OK") cnx.commit() # Close connection and database cursor.close() cnx.close()
Fix MySQL command executing (MySQL commit).
scripts: Fix MySQL command executing (MySQL commit).
Python
mit
alberand/tserver,alberand/tserver,alberand/tserver,alberand/tserver
#!/usr/bin/env python # -*- coding: utf-8 -*- #============================================================================== # Script for creating MySQL user #============================================================================== import os import sys import mysql.connector from mysql.connector import errorcode sys.path.insert(1, '../src') from config import config from sql.tables import TABLES if __name__ == '__main__': if len(sys.argv) < 3: print('There is not enough arguments.') print('Use following arguments:') print('\tpython {} config.ini MYSQL_ROOT_PASSWORD'.format( os.path.basename(__file__))) sys.exit(1) # Open connection to MySQL server and get cursor cnx = mysql.connector.connect( host=config['mysql_host'], user='root', password=config['mysql_root_pass']) cursor = cnx.cursor() # Create MySql user command = ''' CREATE USER '{}'@'{}' IDENTIFIED BY '{}'; GRANT ALL PRIVILEGES ON *.* TO '{}'@'{}'; FLUSH PRIVILEGES; '''.format(config['mysql_user'], config['mysql_host'], config['mysql_pass'], config['mysql_user'], config['mysql_host']) try: print("Creating user '{}' identified by {}: ".format( config['mysql_user'], config['mysql_pass']), end='') cursor.execute(command, multi=True) except mysql.connector.Error as err: print(err.msg) else: print("OK") # Close connection and database cursor.close() cnx.close() scripts: Fix MySQL command executing (MySQL commit).
#!/usr/bin/env python # -*- coding: utf-8 -*- #============================================================================== # Script for creating MySQL user #============================================================================== import os import sys import mysql.connector from mysql.connector import errorcode sys.path.insert(1, '../src') from config import config from sql.tables import TABLES if __name__ == '__main__': if len(sys.argv) < 3: print('There is not enough arguments.') print('Use following arguments:') print('\tpython {} config.ini MYSQL_ROOT_PASSWORD'.format( os.path.basename(__file__))) sys.exit(1) # Open connection to MySQL server and get cursor cnx = mysql.connector.connect( host=config['mysql_host'], user='root', password=sys.argv[2]) cursor = cnx.cursor() # Create MySql user command = ''' CREATE USER '{}'@'{}' IDENTIFIED BY '{}'; GRANT ALL PRIVILEGES ON *.* TO '{}'@'{}'; FLUSH PRIVILEGES; '''.format(config['mysql_user'], config['mysql_host'], config['mysql_pass'], config['mysql_user'], config['mysql_host']) try: print("Creating user '{}' identified by {}: ".format( config['mysql_user'], config['mysql_pass']), end='') cursor.execute(command, multi=True) except mysql.connector.Error as err: print(err.msg) else: print("OK") cnx.commit() # Close connection and database cursor.close() cnx.close()
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- #============================================================================== # Script for creating MySQL user #============================================================================== import os import sys import mysql.connector from mysql.connector import errorcode sys.path.insert(1, '../src') from config import config from sql.tables import TABLES if __name__ == '__main__': if len(sys.argv) < 3: print('There is not enough arguments.') print('Use following arguments:') print('\tpython {} config.ini MYSQL_ROOT_PASSWORD'.format( os.path.basename(__file__))) sys.exit(1) # Open connection to MySQL server and get cursor cnx = mysql.connector.connect( host=config['mysql_host'], user='root', password=config['mysql_root_pass']) cursor = cnx.cursor() # Create MySql user command = ''' CREATE USER '{}'@'{}' IDENTIFIED BY '{}'; GRANT ALL PRIVILEGES ON *.* TO '{}'@'{}'; FLUSH PRIVILEGES; '''.format(config['mysql_user'], config['mysql_host'], config['mysql_pass'], config['mysql_user'], config['mysql_host']) try: print("Creating user '{}' identified by {}: ".format( config['mysql_user'], config['mysql_pass']), end='') cursor.execute(command, multi=True) except mysql.connector.Error as err: print(err.msg) else: print("OK") # Close connection and database cursor.close() cnx.close() <commit_msg>scripts: Fix MySQL command executing (MySQL commit).<commit_after>
#!/usr/bin/env python # -*- coding: utf-8 -*- #============================================================================== # Script for creating MySQL user #============================================================================== import os import sys import mysql.connector from mysql.connector import errorcode sys.path.insert(1, '../src') from config import config from sql.tables import TABLES if __name__ == '__main__': if len(sys.argv) < 3: print('There is not enough arguments.') print('Use following arguments:') print('\tpython {} config.ini MYSQL_ROOT_PASSWORD'.format( os.path.basename(__file__))) sys.exit(1) # Open connection to MySQL server and get cursor cnx = mysql.connector.connect( host=config['mysql_host'], user='root', password=sys.argv[2]) cursor = cnx.cursor() # Create MySql user command = ''' CREATE USER '{}'@'{}' IDENTIFIED BY '{}'; GRANT ALL PRIVILEGES ON *.* TO '{}'@'{}'; FLUSH PRIVILEGES; '''.format(config['mysql_user'], config['mysql_host'], config['mysql_pass'], config['mysql_user'], config['mysql_host']) try: print("Creating user '{}' identified by {}: ".format( config['mysql_user'], config['mysql_pass']), end='') cursor.execute(command, multi=True) except mysql.connector.Error as err: print(err.msg) else: print("OK") cnx.commit() # Close connection and database cursor.close() cnx.close()
#!/usr/bin/env python # -*- coding: utf-8 -*- #============================================================================== # Script for creating MySQL user #============================================================================== import os import sys import mysql.connector from mysql.connector import errorcode sys.path.insert(1, '../src') from config import config from sql.tables import TABLES if __name__ == '__main__': if len(sys.argv) < 3: print('There is not enough arguments.') print('Use following arguments:') print('\tpython {} config.ini MYSQL_ROOT_PASSWORD'.format( os.path.basename(__file__))) sys.exit(1) # Open connection to MySQL server and get cursor cnx = mysql.connector.connect( host=config['mysql_host'], user='root', password=config['mysql_root_pass']) cursor = cnx.cursor() # Create MySql user command = ''' CREATE USER '{}'@'{}' IDENTIFIED BY '{}'; GRANT ALL PRIVILEGES ON *.* TO '{}'@'{}'; FLUSH PRIVILEGES; '''.format(config['mysql_user'], config['mysql_host'], config['mysql_pass'], config['mysql_user'], config['mysql_host']) try: print("Creating user '{}' identified by {}: ".format( config['mysql_user'], config['mysql_pass']), end='') cursor.execute(command, multi=True) except mysql.connector.Error as err: print(err.msg) else: print("OK") # Close connection and database cursor.close() cnx.close() scripts: Fix MySQL command executing (MySQL commit).#!/usr/bin/env python # -*- coding: utf-8 -*- #============================================================================== # Script for creating MySQL user #============================================================================== import os import sys import mysql.connector from mysql.connector import errorcode sys.path.insert(1, '../src') from config import config from sql.tables import TABLES if __name__ == '__main__': if len(sys.argv) < 3: print('There is not enough arguments.') print('Use following arguments:') print('\tpython {} config.ini MYSQL_ROOT_PASSWORD'.format( os.path.basename(__file__))) sys.exit(1) # Open connection to MySQL server and get cursor cnx = mysql.connector.connect( host=config['mysql_host'], user='root', password=sys.argv[2]) cursor = cnx.cursor() # Create MySql user command = ''' CREATE USER '{}'@'{}' IDENTIFIED BY '{}'; GRANT ALL PRIVILEGES ON *.* TO '{}'@'{}'; FLUSH PRIVILEGES; '''.format(config['mysql_user'], config['mysql_host'], config['mysql_pass'], config['mysql_user'], config['mysql_host']) try: print("Creating user '{}' identified by {}: ".format( config['mysql_user'], config['mysql_pass']), end='') cursor.execute(command, multi=True) except mysql.connector.Error as err: print(err.msg) else: print("OK") cnx.commit() # Close connection and database cursor.close() cnx.close()
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- #============================================================================== # Script for creating MySQL user #============================================================================== import os import sys import mysql.connector from mysql.connector import errorcode sys.path.insert(1, '../src') from config import config from sql.tables import TABLES if __name__ == '__main__': if len(sys.argv) < 3: print('There is not enough arguments.') print('Use following arguments:') print('\tpython {} config.ini MYSQL_ROOT_PASSWORD'.format( os.path.basename(__file__))) sys.exit(1) # Open connection to MySQL server and get cursor cnx = mysql.connector.connect( host=config['mysql_host'], user='root', password=config['mysql_root_pass']) cursor = cnx.cursor() # Create MySql user command = ''' CREATE USER '{}'@'{}' IDENTIFIED BY '{}'; GRANT ALL PRIVILEGES ON *.* TO '{}'@'{}'; FLUSH PRIVILEGES; '''.format(config['mysql_user'], config['mysql_host'], config['mysql_pass'], config['mysql_user'], config['mysql_host']) try: print("Creating user '{}' identified by {}: ".format( config['mysql_user'], config['mysql_pass']), end='') cursor.execute(command, multi=True) except mysql.connector.Error as err: print(err.msg) else: print("OK") # Close connection and database cursor.close() cnx.close() <commit_msg>scripts: Fix MySQL command executing (MySQL commit).<commit_after>#!/usr/bin/env python # -*- coding: utf-8 -*- #============================================================================== # Script for creating MySQL user #============================================================================== import os import sys import mysql.connector from mysql.connector import errorcode sys.path.insert(1, '../src') from config import config from sql.tables import TABLES if __name__ == '__main__': if len(sys.argv) < 3: print('There is not enough arguments.') print('Use following arguments:') print('\tpython {} config.ini MYSQL_ROOT_PASSWORD'.format( os.path.basename(__file__))) sys.exit(1) # Open connection to MySQL server and get cursor cnx = mysql.connector.connect( host=config['mysql_host'], user='root', password=sys.argv[2]) cursor = cnx.cursor() # Create MySql user command = ''' CREATE USER '{}'@'{}' IDENTIFIED BY '{}'; GRANT ALL PRIVILEGES ON *.* TO '{}'@'{}'; FLUSH PRIVILEGES; '''.format(config['mysql_user'], config['mysql_host'], config['mysql_pass'], config['mysql_user'], config['mysql_host']) try: print("Creating user '{}' identified by {}: ".format( config['mysql_user'], config['mysql_pass']), end='') cursor.execute(command, multi=True) except mysql.connector.Error as err: print(err.msg) else: print("OK") cnx.commit() # Close connection and database cursor.close() cnx.close()
d187a8434c9d64171f76efa3055bdc06afbc8981
scripts/pystart.py
scripts/pystart.py
import os,sys,re from time import sleep from pprint import pprint home = os.path.expanduser('~') from math import log,ceil def clog2(num): return int(ceil(log(num,2))) if (sys.version_info > (3, 0)): # Python 3 code in this block exec(open(home+'/homedir/scripts/hexecho.py').read()) else: # Python 2 code in this block execfile(home+'/homedir/scripts/hexecho.py') hexoff print ("Imported os,sys,re,sleep,pprint. Defined clog2,hexon/hexoff")
import os,sys,re from time import sleep from pprint import pprint home = os.path.expanduser('~') from math import log,ceil sys.ps1 = '\001\033[96m\002>>> \001\033[0m\002' sys.ps2 = '\001\033[96m\002... \001\033[0m\002' def clog2(num): return int(ceil(log(num,2))) if (sys.version_info > (3, 0)): # Python 3 code in this block exec(open(home+'/homedir/scripts/hexecho.py').read()) else: # Python 2 code in this block execfile(home+'/homedir/scripts/hexecho.py') hexoff print ("Imported os,sys,re,sleep,pprint. Defined clog2,hexon/hexoff")
Add color to python prompt
Add color to python prompt
Python
mit
jdanders/homedir,jdanders/homedir,jdanders/homedir,jdanders/homedir
import os,sys,re from time import sleep from pprint import pprint home = os.path.expanduser('~') from math import log,ceil def clog2(num): return int(ceil(log(num,2))) if (sys.version_info > (3, 0)): # Python 3 code in this block exec(open(home+'/homedir/scripts/hexecho.py').read()) else: # Python 2 code in this block execfile(home+'/homedir/scripts/hexecho.py') hexoff print ("Imported os,sys,re,sleep,pprint. Defined clog2,hexon/hexoff") Add color to python prompt
import os,sys,re from time import sleep from pprint import pprint home = os.path.expanduser('~') from math import log,ceil sys.ps1 = '\001\033[96m\002>>> \001\033[0m\002' sys.ps2 = '\001\033[96m\002... \001\033[0m\002' def clog2(num): return int(ceil(log(num,2))) if (sys.version_info > (3, 0)): # Python 3 code in this block exec(open(home+'/homedir/scripts/hexecho.py').read()) else: # Python 2 code in this block execfile(home+'/homedir/scripts/hexecho.py') hexoff print ("Imported os,sys,re,sleep,pprint. Defined clog2,hexon/hexoff")
<commit_before>import os,sys,re from time import sleep from pprint import pprint home = os.path.expanduser('~') from math import log,ceil def clog2(num): return int(ceil(log(num,2))) if (sys.version_info > (3, 0)): # Python 3 code in this block exec(open(home+'/homedir/scripts/hexecho.py').read()) else: # Python 2 code in this block execfile(home+'/homedir/scripts/hexecho.py') hexoff print ("Imported os,sys,re,sleep,pprint. Defined clog2,hexon/hexoff") <commit_msg>Add color to python prompt<commit_after>
import os,sys,re from time import sleep from pprint import pprint home = os.path.expanduser('~') from math import log,ceil sys.ps1 = '\001\033[96m\002>>> \001\033[0m\002' sys.ps2 = '\001\033[96m\002... \001\033[0m\002' def clog2(num): return int(ceil(log(num,2))) if (sys.version_info > (3, 0)): # Python 3 code in this block exec(open(home+'/homedir/scripts/hexecho.py').read()) else: # Python 2 code in this block execfile(home+'/homedir/scripts/hexecho.py') hexoff print ("Imported os,sys,re,sleep,pprint. Defined clog2,hexon/hexoff")
import os,sys,re from time import sleep from pprint import pprint home = os.path.expanduser('~') from math import log,ceil def clog2(num): return int(ceil(log(num,2))) if (sys.version_info > (3, 0)): # Python 3 code in this block exec(open(home+'/homedir/scripts/hexecho.py').read()) else: # Python 2 code in this block execfile(home+'/homedir/scripts/hexecho.py') hexoff print ("Imported os,sys,re,sleep,pprint. Defined clog2,hexon/hexoff") Add color to python promptimport os,sys,re from time import sleep from pprint import pprint home = os.path.expanduser('~') from math import log,ceil sys.ps1 = '\001\033[96m\002>>> \001\033[0m\002' sys.ps2 = '\001\033[96m\002... \001\033[0m\002' def clog2(num): return int(ceil(log(num,2))) if (sys.version_info > (3, 0)): # Python 3 code in this block exec(open(home+'/homedir/scripts/hexecho.py').read()) else: # Python 2 code in this block execfile(home+'/homedir/scripts/hexecho.py') hexoff print ("Imported os,sys,re,sleep,pprint. Defined clog2,hexon/hexoff")
<commit_before>import os,sys,re from time import sleep from pprint import pprint home = os.path.expanduser('~') from math import log,ceil def clog2(num): return int(ceil(log(num,2))) if (sys.version_info > (3, 0)): # Python 3 code in this block exec(open(home+'/homedir/scripts/hexecho.py').read()) else: # Python 2 code in this block execfile(home+'/homedir/scripts/hexecho.py') hexoff print ("Imported os,sys,re,sleep,pprint. Defined clog2,hexon/hexoff") <commit_msg>Add color to python prompt<commit_after>import os,sys,re from time import sleep from pprint import pprint home = os.path.expanduser('~') from math import log,ceil sys.ps1 = '\001\033[96m\002>>> \001\033[0m\002' sys.ps2 = '\001\033[96m\002... \001\033[0m\002' def clog2(num): return int(ceil(log(num,2))) if (sys.version_info > (3, 0)): # Python 3 code in this block exec(open(home+'/homedir/scripts/hexecho.py').read()) else: # Python 2 code in this block execfile(home+'/homedir/scripts/hexecho.py') hexoff print ("Imported os,sys,re,sleep,pprint. Defined clog2,hexon/hexoff")
d8b13dcb884046ee43d54fcf27f1bbfd0ff3263a
sentrylogs/parsers/__init__.py
sentrylogs/parsers/__init__.py
""" Log file parsers provided by Sentry Logs """ import tailer # same functionality as UNIX tail in python from ..helpers import send_message class Parser(object): """Abstract base class for any parser""" def __init__(self, filepath): self.filepath = filepath self.logger = self.__doc__.strip() self.message = None self.extended_message = None self.params = None self.site = None def follow_tail(self): """ Read (tail and follow) the log file, parse entries and send messages to Sentry using Raven. """ for line in tailer.follow(open(self.filepath)): self.message = None self.extended_message = None self.params = None self.site = None self.parse(line) send_message(self.message, self.extended_message, self.params, self.site, self.logger) def parse(self, line): """ Parse a line of a log file. Must be overridden by the subclass. The implementation must set these properties: - ``message`` (string) - ``extended_message`` (string) - ``params`` (list of string) - ``site`` (string) """ raise NotImplementedError('parse() method must set: ' 'message, extended_message, params, site')
""" Log file parsers provided by Sentry Logs """ import tailer # same functionality as UNIX tail in python from ..helpers import send_message try: (FileNotFoundError, PermissionError) except NameError: # Python 2.7 FileNotFoundError = IOError # pylint: disable=redefined-builtin PermissionError = IOError # pylint: disable=redefined-builtin class Parser(object): """Abstract base class for any parser""" def __init__(self, filepath): self.filepath = filepath self.logger = self.__doc__.strip() self.message = None self.extended_message = None self.params = None self.site = None def follow_tail(self): """ Read (tail and follow) the log file, parse entries and send messages to Sentry using Raven. """ try: logfile = open(self.filepath) except (FileNotFoundError, PermissionError) as err: exit("Error: Can't read logfile %s (%s)" % (self.filepath, err)) for line in tailer.follow(logfile): self.message = None self.extended_message = None self.params = None self.site = None self.parse(line) send_message(self.message, self.extended_message, self.params, self.site, self.logger) def parse(self, line): """ Parse a line of a log file. Must be overridden by the subclass. The implementation must set these properties: - ``message`` (string) - ``extended_message`` (string) - ``params`` (list of string) - ``site`` (string) """ raise NotImplementedError('parse() method must set: ' 'message, extended_message, params, site')
Handle FileNotFound and Permission errors gracefully
Handle FileNotFound and Permission errors gracefully
Python
bsd-3-clause
bittner/sentrylogs,mdgart/sentrylogs
""" Log file parsers provided by Sentry Logs """ import tailer # same functionality as UNIX tail in python from ..helpers import send_message class Parser(object): """Abstract base class for any parser""" def __init__(self, filepath): self.filepath = filepath self.logger = self.__doc__.strip() self.message = None self.extended_message = None self.params = None self.site = None def follow_tail(self): """ Read (tail and follow) the log file, parse entries and send messages to Sentry using Raven. """ for line in tailer.follow(open(self.filepath)): self.message = None self.extended_message = None self.params = None self.site = None self.parse(line) send_message(self.message, self.extended_message, self.params, self.site, self.logger) def parse(self, line): """ Parse a line of a log file. Must be overridden by the subclass. The implementation must set these properties: - ``message`` (string) - ``extended_message`` (string) - ``params`` (list of string) - ``site`` (string) """ raise NotImplementedError('parse() method must set: ' 'message, extended_message, params, site') Handle FileNotFound and Permission errors gracefully
""" Log file parsers provided by Sentry Logs """ import tailer # same functionality as UNIX tail in python from ..helpers import send_message try: (FileNotFoundError, PermissionError) except NameError: # Python 2.7 FileNotFoundError = IOError # pylint: disable=redefined-builtin PermissionError = IOError # pylint: disable=redefined-builtin class Parser(object): """Abstract base class for any parser""" def __init__(self, filepath): self.filepath = filepath self.logger = self.__doc__.strip() self.message = None self.extended_message = None self.params = None self.site = None def follow_tail(self): """ Read (tail and follow) the log file, parse entries and send messages to Sentry using Raven. """ try: logfile = open(self.filepath) except (FileNotFoundError, PermissionError) as err: exit("Error: Can't read logfile %s (%s)" % (self.filepath, err)) for line in tailer.follow(logfile): self.message = None self.extended_message = None self.params = None self.site = None self.parse(line) send_message(self.message, self.extended_message, self.params, self.site, self.logger) def parse(self, line): """ Parse a line of a log file. Must be overridden by the subclass. The implementation must set these properties: - ``message`` (string) - ``extended_message`` (string) - ``params`` (list of string) - ``site`` (string) """ raise NotImplementedError('parse() method must set: ' 'message, extended_message, params, site')
<commit_before>""" Log file parsers provided by Sentry Logs """ import tailer # same functionality as UNIX tail in python from ..helpers import send_message class Parser(object): """Abstract base class for any parser""" def __init__(self, filepath): self.filepath = filepath self.logger = self.__doc__.strip() self.message = None self.extended_message = None self.params = None self.site = None def follow_tail(self): """ Read (tail and follow) the log file, parse entries and send messages to Sentry using Raven. """ for line in tailer.follow(open(self.filepath)): self.message = None self.extended_message = None self.params = None self.site = None self.parse(line) send_message(self.message, self.extended_message, self.params, self.site, self.logger) def parse(self, line): """ Parse a line of a log file. Must be overridden by the subclass. The implementation must set these properties: - ``message`` (string) - ``extended_message`` (string) - ``params`` (list of string) - ``site`` (string) """ raise NotImplementedError('parse() method must set: ' 'message, extended_message, params, site') <commit_msg>Handle FileNotFound and Permission errors gracefully<commit_after>
""" Log file parsers provided by Sentry Logs """ import tailer # same functionality as UNIX tail in python from ..helpers import send_message try: (FileNotFoundError, PermissionError) except NameError: # Python 2.7 FileNotFoundError = IOError # pylint: disable=redefined-builtin PermissionError = IOError # pylint: disable=redefined-builtin class Parser(object): """Abstract base class for any parser""" def __init__(self, filepath): self.filepath = filepath self.logger = self.__doc__.strip() self.message = None self.extended_message = None self.params = None self.site = None def follow_tail(self): """ Read (tail and follow) the log file, parse entries and send messages to Sentry using Raven. """ try: logfile = open(self.filepath) except (FileNotFoundError, PermissionError) as err: exit("Error: Can't read logfile %s (%s)" % (self.filepath, err)) for line in tailer.follow(logfile): self.message = None self.extended_message = None self.params = None self.site = None self.parse(line) send_message(self.message, self.extended_message, self.params, self.site, self.logger) def parse(self, line): """ Parse a line of a log file. Must be overridden by the subclass. The implementation must set these properties: - ``message`` (string) - ``extended_message`` (string) - ``params`` (list of string) - ``site`` (string) """ raise NotImplementedError('parse() method must set: ' 'message, extended_message, params, site')
""" Log file parsers provided by Sentry Logs """ import tailer # same functionality as UNIX tail in python from ..helpers import send_message class Parser(object): """Abstract base class for any parser""" def __init__(self, filepath): self.filepath = filepath self.logger = self.__doc__.strip() self.message = None self.extended_message = None self.params = None self.site = None def follow_tail(self): """ Read (tail and follow) the log file, parse entries and send messages to Sentry using Raven. """ for line in tailer.follow(open(self.filepath)): self.message = None self.extended_message = None self.params = None self.site = None self.parse(line) send_message(self.message, self.extended_message, self.params, self.site, self.logger) def parse(self, line): """ Parse a line of a log file. Must be overridden by the subclass. The implementation must set these properties: - ``message`` (string) - ``extended_message`` (string) - ``params`` (list of string) - ``site`` (string) """ raise NotImplementedError('parse() method must set: ' 'message, extended_message, params, site') Handle FileNotFound and Permission errors gracefully""" Log file parsers provided by Sentry Logs """ import tailer # same functionality as UNIX tail in python from ..helpers import send_message try: (FileNotFoundError, PermissionError) except NameError: # Python 2.7 FileNotFoundError = IOError # pylint: disable=redefined-builtin PermissionError = IOError # pylint: disable=redefined-builtin class Parser(object): """Abstract base class for any parser""" def __init__(self, filepath): self.filepath = filepath self.logger = self.__doc__.strip() self.message = None self.extended_message = None self.params = None self.site = None def follow_tail(self): """ Read (tail and follow) the log file, parse entries and send messages to Sentry using Raven. """ try: logfile = open(self.filepath) except (FileNotFoundError, PermissionError) as err: exit("Error: Can't read logfile %s (%s)" % (self.filepath, err)) for line in tailer.follow(logfile): self.message = None self.extended_message = None self.params = None self.site = None self.parse(line) send_message(self.message, self.extended_message, self.params, self.site, self.logger) def parse(self, line): """ Parse a line of a log file. Must be overridden by the subclass. The implementation must set these properties: - ``message`` (string) - ``extended_message`` (string) - ``params`` (list of string) - ``site`` (string) """ raise NotImplementedError('parse() method must set: ' 'message, extended_message, params, site')
<commit_before>""" Log file parsers provided by Sentry Logs """ import tailer # same functionality as UNIX tail in python from ..helpers import send_message class Parser(object): """Abstract base class for any parser""" def __init__(self, filepath): self.filepath = filepath self.logger = self.__doc__.strip() self.message = None self.extended_message = None self.params = None self.site = None def follow_tail(self): """ Read (tail and follow) the log file, parse entries and send messages to Sentry using Raven. """ for line in tailer.follow(open(self.filepath)): self.message = None self.extended_message = None self.params = None self.site = None self.parse(line) send_message(self.message, self.extended_message, self.params, self.site, self.logger) def parse(self, line): """ Parse a line of a log file. Must be overridden by the subclass. The implementation must set these properties: - ``message`` (string) - ``extended_message`` (string) - ``params`` (list of string) - ``site`` (string) """ raise NotImplementedError('parse() method must set: ' 'message, extended_message, params, site') <commit_msg>Handle FileNotFound and Permission errors gracefully<commit_after>""" Log file parsers provided by Sentry Logs """ import tailer # same functionality as UNIX tail in python from ..helpers import send_message try: (FileNotFoundError, PermissionError) except NameError: # Python 2.7 FileNotFoundError = IOError # pylint: disable=redefined-builtin PermissionError = IOError # pylint: disable=redefined-builtin class Parser(object): """Abstract base class for any parser""" def __init__(self, filepath): self.filepath = filepath self.logger = self.__doc__.strip() self.message = None self.extended_message = None self.params = None self.site = None def follow_tail(self): """ Read (tail and follow) the log file, parse entries and send messages to Sentry using Raven. """ try: logfile = open(self.filepath) except (FileNotFoundError, PermissionError) as err: exit("Error: Can't read logfile %s (%s)" % (self.filepath, err)) for line in tailer.follow(logfile): self.message = None self.extended_message = None self.params = None self.site = None self.parse(line) send_message(self.message, self.extended_message, self.params, self.site, self.logger) def parse(self, line): """ Parse a line of a log file. Must be overridden by the subclass. The implementation must set these properties: - ``message`` (string) - ``extended_message`` (string) - ``params`` (list of string) - ``site`` (string) """ raise NotImplementedError('parse() method must set: ' 'message, extended_message, params, site')
a7e87621b3223e0c4df9d417129fcb7da545c629
integration/integration.py
integration/integration.py
# Python Packages import random # External Packages import numpy as np def sin_theta_sum(variables): theta = 0 for var in variables: theta += var return np.sin(theta) def gen_random_list(count, rmin, rmax): variables = [] for i in range(count): value = np.random.uniform(rmin, rmax) variables.append(value) test_range(rmin, rmax, value) return variables def run_monte_carlo(samples): return False def main(): rmax = np.pi/8 variables = gen_random_list(7, 0, rmax) result = sin_theta_sum(variables) print(variables) print(result) def test_range(rmin, rmax, value): if (value <= rmin or value >= rmax): print(False) main()
# Python Packages import random # External Packages import numpy as np def sin_theta_sum(theta): return np.sin(theta) def gen_random_value(count, rmin, rmax): value = 0 for i in range(count): value += np.random.uniform(rmin, rmax) # test_range(rmin, rmax, value) return value def run_monte_carlo(samples, function, func_coeff, func_vars): value = 0 for i in range(samples): if i % 10000 == 0: print(i) value += function(func_vars) value = value*func_coeff/samples return value def sin_monte_element(rmax): value = gen_random_value(8, 0, rmax) result = sin_theta_sum(value) return result def main(): rmax = np.pi/8 samples = 10000000 coefficient = 1000000 volume = np.power(np.pi/8, 8) func_coeff = coefficient*volume func_vars = rmax result = run_monte_carlo(samples, sin_monte_element, func_coeff, func_vars) print(result) def test_range(rmin, rmax, value): if (value <= rmin or value >= rmax): print(False) main()
Add preliminary function to execute monte-carlo approximation.
Add preliminary function to execute monte-carlo approximation. Adjust functions, remove some generality for speed. Implement monte-carlo for the exercise case with initial config. No error calculation or execution for varied N yet. Initial tests with N = 10^7 give a value of ~537.1 and take ~1.20min.
Python
mit
lemming52/white_knight
# Python Packages import random # External Packages import numpy as np def sin_theta_sum(variables): theta = 0 for var in variables: theta += var return np.sin(theta) def gen_random_list(count, rmin, rmax): variables = [] for i in range(count): value = np.random.uniform(rmin, rmax) variables.append(value) test_range(rmin, rmax, value) return variables def run_monte_carlo(samples): return False def main(): rmax = np.pi/8 variables = gen_random_list(7, 0, rmax) result = sin_theta_sum(variables) print(variables) print(result) def test_range(rmin, rmax, value): if (value <= rmin or value >= rmax): print(False) main() Add preliminary function to execute monte-carlo approximation. Adjust functions, remove some generality for speed. Implement monte-carlo for the exercise case with initial config. No error calculation or execution for varied N yet. Initial tests with N = 10^7 give a value of ~537.1 and take ~1.20min.
# Python Packages import random # External Packages import numpy as np def sin_theta_sum(theta): return np.sin(theta) def gen_random_value(count, rmin, rmax): value = 0 for i in range(count): value += np.random.uniform(rmin, rmax) # test_range(rmin, rmax, value) return value def run_monte_carlo(samples, function, func_coeff, func_vars): value = 0 for i in range(samples): if i % 10000 == 0: print(i) value += function(func_vars) value = value*func_coeff/samples return value def sin_monte_element(rmax): value = gen_random_value(8, 0, rmax) result = sin_theta_sum(value) return result def main(): rmax = np.pi/8 samples = 10000000 coefficient = 1000000 volume = np.power(np.pi/8, 8) func_coeff = coefficient*volume func_vars = rmax result = run_monte_carlo(samples, sin_monte_element, func_coeff, func_vars) print(result) def test_range(rmin, rmax, value): if (value <= rmin or value >= rmax): print(False) main()
<commit_before># Python Packages import random # External Packages import numpy as np def sin_theta_sum(variables): theta = 0 for var in variables: theta += var return np.sin(theta) def gen_random_list(count, rmin, rmax): variables = [] for i in range(count): value = np.random.uniform(rmin, rmax) variables.append(value) test_range(rmin, rmax, value) return variables def run_monte_carlo(samples): return False def main(): rmax = np.pi/8 variables = gen_random_list(7, 0, rmax) result = sin_theta_sum(variables) print(variables) print(result) def test_range(rmin, rmax, value): if (value <= rmin or value >= rmax): print(False) main() <commit_msg>Add preliminary function to execute monte-carlo approximation. Adjust functions, remove some generality for speed. Implement monte-carlo for the exercise case with initial config. No error calculation or execution for varied N yet. Initial tests with N = 10^7 give a value of ~537.1 and take ~1.20min.<commit_after>
# Python Packages import random # External Packages import numpy as np def sin_theta_sum(theta): return np.sin(theta) def gen_random_value(count, rmin, rmax): value = 0 for i in range(count): value += np.random.uniform(rmin, rmax) # test_range(rmin, rmax, value) return value def run_monte_carlo(samples, function, func_coeff, func_vars): value = 0 for i in range(samples): if i % 10000 == 0: print(i) value += function(func_vars) value = value*func_coeff/samples return value def sin_monte_element(rmax): value = gen_random_value(8, 0, rmax) result = sin_theta_sum(value) return result def main(): rmax = np.pi/8 samples = 10000000 coefficient = 1000000 volume = np.power(np.pi/8, 8) func_coeff = coefficient*volume func_vars = rmax result = run_monte_carlo(samples, sin_monte_element, func_coeff, func_vars) print(result) def test_range(rmin, rmax, value): if (value <= rmin or value >= rmax): print(False) main()
# Python Packages import random # External Packages import numpy as np def sin_theta_sum(variables): theta = 0 for var in variables: theta += var return np.sin(theta) def gen_random_list(count, rmin, rmax): variables = [] for i in range(count): value = np.random.uniform(rmin, rmax) variables.append(value) test_range(rmin, rmax, value) return variables def run_monte_carlo(samples): return False def main(): rmax = np.pi/8 variables = gen_random_list(7, 0, rmax) result = sin_theta_sum(variables) print(variables) print(result) def test_range(rmin, rmax, value): if (value <= rmin or value >= rmax): print(False) main() Add preliminary function to execute monte-carlo approximation. Adjust functions, remove some generality for speed. Implement monte-carlo for the exercise case with initial config. No error calculation or execution for varied N yet. Initial tests with N = 10^7 give a value of ~537.1 and take ~1.20min.# Python Packages import random # External Packages import numpy as np def sin_theta_sum(theta): return np.sin(theta) def gen_random_value(count, rmin, rmax): value = 0 for i in range(count): value += np.random.uniform(rmin, rmax) # test_range(rmin, rmax, value) return value def run_monte_carlo(samples, function, func_coeff, func_vars): value = 0 for i in range(samples): if i % 10000 == 0: print(i) value += function(func_vars) value = value*func_coeff/samples return value def sin_monte_element(rmax): value = gen_random_value(8, 0, rmax) result = sin_theta_sum(value) return result def main(): rmax = np.pi/8 samples = 10000000 coefficient = 1000000 volume = np.power(np.pi/8, 8) func_coeff = coefficient*volume func_vars = rmax result = run_monte_carlo(samples, sin_monte_element, func_coeff, func_vars) print(result) def test_range(rmin, rmax, value): if (value <= rmin or value >= rmax): print(False) main()
<commit_before># Python Packages import random # External Packages import numpy as np def sin_theta_sum(variables): theta = 0 for var in variables: theta += var return np.sin(theta) def gen_random_list(count, rmin, rmax): variables = [] for i in range(count): value = np.random.uniform(rmin, rmax) variables.append(value) test_range(rmin, rmax, value) return variables def run_monte_carlo(samples): return False def main(): rmax = np.pi/8 variables = gen_random_list(7, 0, rmax) result = sin_theta_sum(variables) print(variables) print(result) def test_range(rmin, rmax, value): if (value <= rmin or value >= rmax): print(False) main() <commit_msg>Add preliminary function to execute monte-carlo approximation. Adjust functions, remove some generality for speed. Implement monte-carlo for the exercise case with initial config. No error calculation or execution for varied N yet. Initial tests with N = 10^7 give a value of ~537.1 and take ~1.20min.<commit_after># Python Packages import random # External Packages import numpy as np def sin_theta_sum(theta): return np.sin(theta) def gen_random_value(count, rmin, rmax): value = 0 for i in range(count): value += np.random.uniform(rmin, rmax) # test_range(rmin, rmax, value) return value def run_monte_carlo(samples, function, func_coeff, func_vars): value = 0 for i in range(samples): if i % 10000 == 0: print(i) value += function(func_vars) value = value*func_coeff/samples return value def sin_monte_element(rmax): value = gen_random_value(8, 0, rmax) result = sin_theta_sum(value) return result def main(): rmax = np.pi/8 samples = 10000000 coefficient = 1000000 volume = np.power(np.pi/8, 8) func_coeff = coefficient*volume func_vars = rmax result = run_monte_carlo(samples, sin_monte_element, func_coeff, func_vars) print(result) def test_range(rmin, rmax, value): if (value <= rmin or value >= rmax): print(False) main()
1b84734f9f016e098fa82e596ae851f3b9d4fe2b
simplecrypto/hashes.py
simplecrypto/hashes.py
""" Module for standard hash algorithms, always returning the hash in hexadecimal string format. """ import hashlib from .formats import to_bytes def md5(message): """ Returns the hexadecimal representation of the MD5 hash digest. """ return hashlib.md5(to_bytes(message)).hexdigest() def sha1(message): """ Returns the hexadecimal representation of the SHA1 hash digest. """ return hashlib.sha1(to_bytes(message)).hexdigest() def sha256(message): """ Returns the hexadecimal representation of the SHA256 hash digest. """ return hashlib.sha256(to_bytes(message)).hexdigest() def sha512(message): """ Returns the hexadecimal representation of the SHA512 hash digest. """ return hashlib.sha512(to_bytes(message)).hexdigest() # Available hash functions. hashes = [sha1, md5, sha256, sha512] # Default hash function. hash = sha1
""" Module for standard hash algorithms, always returning the hash in hexadecimal string format. """ import hashlib from .formats import to_bytes def md5(message): """ Returns the hexadecimal representation of the MD5 hash digest. """ return hashlib.md5(to_bytes(message)).hexdigest() def sha1(message): """ Returns the hexadecimal representation of the SHA1 hash digest. """ return hashlib.sha1(to_bytes(message)).hexdigest() def sha256(message): """ Returns the hexadecimal representation of the SHA256 hash digest. """ return hashlib.sha256(to_bytes(message)).hexdigest() def sha512(message): """ Returns the hexadecimal representation of the SHA512 hash digest. """ return hashlib.sha512(to_bytes(message)).hexdigest() # Available hash functions. hashes = [sha1, md5, sha256, sha512] # Default hash function. hash = sha256
Use SHA-256 as default hash
Use SHA-256 as default hash
Python
mit
boppreh/simplecrypto
""" Module for standard hash algorithms, always returning the hash in hexadecimal string format. """ import hashlib from .formats import to_bytes def md5(message): """ Returns the hexadecimal representation of the MD5 hash digest. """ return hashlib.md5(to_bytes(message)).hexdigest() def sha1(message): """ Returns the hexadecimal representation of the SHA1 hash digest. """ return hashlib.sha1(to_bytes(message)).hexdigest() def sha256(message): """ Returns the hexadecimal representation of the SHA256 hash digest. """ return hashlib.sha256(to_bytes(message)).hexdigest() def sha512(message): """ Returns the hexadecimal representation of the SHA512 hash digest. """ return hashlib.sha512(to_bytes(message)).hexdigest() # Available hash functions. hashes = [sha1, md5, sha256, sha512] # Default hash function. hash = sha1 Use SHA-256 as default hash
""" Module for standard hash algorithms, always returning the hash in hexadecimal string format. """ import hashlib from .formats import to_bytes def md5(message): """ Returns the hexadecimal representation of the MD5 hash digest. """ return hashlib.md5(to_bytes(message)).hexdigest() def sha1(message): """ Returns the hexadecimal representation of the SHA1 hash digest. """ return hashlib.sha1(to_bytes(message)).hexdigest() def sha256(message): """ Returns the hexadecimal representation of the SHA256 hash digest. """ return hashlib.sha256(to_bytes(message)).hexdigest() def sha512(message): """ Returns the hexadecimal representation of the SHA512 hash digest. """ return hashlib.sha512(to_bytes(message)).hexdigest() # Available hash functions. hashes = [sha1, md5, sha256, sha512] # Default hash function. hash = sha256
<commit_before>""" Module for standard hash algorithms, always returning the hash in hexadecimal string format. """ import hashlib from .formats import to_bytes def md5(message): """ Returns the hexadecimal representation of the MD5 hash digest. """ return hashlib.md5(to_bytes(message)).hexdigest() def sha1(message): """ Returns the hexadecimal representation of the SHA1 hash digest. """ return hashlib.sha1(to_bytes(message)).hexdigest() def sha256(message): """ Returns the hexadecimal representation of the SHA256 hash digest. """ return hashlib.sha256(to_bytes(message)).hexdigest() def sha512(message): """ Returns the hexadecimal representation of the SHA512 hash digest. """ return hashlib.sha512(to_bytes(message)).hexdigest() # Available hash functions. hashes = [sha1, md5, sha256, sha512] # Default hash function. hash = sha1 <commit_msg>Use SHA-256 as default hash<commit_after>
""" Module for standard hash algorithms, always returning the hash in hexadecimal string format. """ import hashlib from .formats import to_bytes def md5(message): """ Returns the hexadecimal representation of the MD5 hash digest. """ return hashlib.md5(to_bytes(message)).hexdigest() def sha1(message): """ Returns the hexadecimal representation of the SHA1 hash digest. """ return hashlib.sha1(to_bytes(message)).hexdigest() def sha256(message): """ Returns the hexadecimal representation of the SHA256 hash digest. """ return hashlib.sha256(to_bytes(message)).hexdigest() def sha512(message): """ Returns the hexadecimal representation of the SHA512 hash digest. """ return hashlib.sha512(to_bytes(message)).hexdigest() # Available hash functions. hashes = [sha1, md5, sha256, sha512] # Default hash function. hash = sha256
""" Module for standard hash algorithms, always returning the hash in hexadecimal string format. """ import hashlib from .formats import to_bytes def md5(message): """ Returns the hexadecimal representation of the MD5 hash digest. """ return hashlib.md5(to_bytes(message)).hexdigest() def sha1(message): """ Returns the hexadecimal representation of the SHA1 hash digest. """ return hashlib.sha1(to_bytes(message)).hexdigest() def sha256(message): """ Returns the hexadecimal representation of the SHA256 hash digest. """ return hashlib.sha256(to_bytes(message)).hexdigest() def sha512(message): """ Returns the hexadecimal representation of the SHA512 hash digest. """ return hashlib.sha512(to_bytes(message)).hexdigest() # Available hash functions. hashes = [sha1, md5, sha256, sha512] # Default hash function. hash = sha1 Use SHA-256 as default hash""" Module for standard hash algorithms, always returning the hash in hexadecimal string format. """ import hashlib from .formats import to_bytes def md5(message): """ Returns the hexadecimal representation of the MD5 hash digest. """ return hashlib.md5(to_bytes(message)).hexdigest() def sha1(message): """ Returns the hexadecimal representation of the SHA1 hash digest. """ return hashlib.sha1(to_bytes(message)).hexdigest() def sha256(message): """ Returns the hexadecimal representation of the SHA256 hash digest. """ return hashlib.sha256(to_bytes(message)).hexdigest() def sha512(message): """ Returns the hexadecimal representation of the SHA512 hash digest. """ return hashlib.sha512(to_bytes(message)).hexdigest() # Available hash functions. hashes = [sha1, md5, sha256, sha512] # Default hash function. hash = sha256
<commit_before>""" Module for standard hash algorithms, always returning the hash in hexadecimal string format. """ import hashlib from .formats import to_bytes def md5(message): """ Returns the hexadecimal representation of the MD5 hash digest. """ return hashlib.md5(to_bytes(message)).hexdigest() def sha1(message): """ Returns the hexadecimal representation of the SHA1 hash digest. """ return hashlib.sha1(to_bytes(message)).hexdigest() def sha256(message): """ Returns the hexadecimal representation of the SHA256 hash digest. """ return hashlib.sha256(to_bytes(message)).hexdigest() def sha512(message): """ Returns the hexadecimal representation of the SHA512 hash digest. """ return hashlib.sha512(to_bytes(message)).hexdigest() # Available hash functions. hashes = [sha1, md5, sha256, sha512] # Default hash function. hash = sha1 <commit_msg>Use SHA-256 as default hash<commit_after>""" Module for standard hash algorithms, always returning the hash in hexadecimal string format. """ import hashlib from .formats import to_bytes def md5(message): """ Returns the hexadecimal representation of the MD5 hash digest. """ return hashlib.md5(to_bytes(message)).hexdigest() def sha1(message): """ Returns the hexadecimal representation of the SHA1 hash digest. """ return hashlib.sha1(to_bytes(message)).hexdigest() def sha256(message): """ Returns the hexadecimal representation of the SHA256 hash digest. """ return hashlib.sha256(to_bytes(message)).hexdigest() def sha512(message): """ Returns the hexadecimal representation of the SHA512 hash digest. """ return hashlib.sha512(to_bytes(message)).hexdigest() # Available hash functions. hashes = [sha1, md5, sha256, sha512] # Default hash function. hash = sha256
1c41a79dc46bf717ee43ad46ac499f5310ad792e
invite/urls.py
invite/urls.py
from django.urls import path from invite import views app_name = 'invite' urlpatterns = [ path('', views.index, name='index'), path('invite/', views.invite, name='invite'), path('resend/(<slug:code>)/', views.resend, name='resend'), path('revoke/(<slug:code>)/', views.revoke, name='revoke'), path('login/', views.log_in_user, name='login'), path('logout/', views.log_out_user, name='edit_logout'), path('amnesia/', views.amnesia, name='amnesia'), path('reset/', views.reset, name='reset'), path('signup/', views.signup, name='account_signup'), path('about/', views.about, name='about'), path('check/', views.check, name='check'), ]
from django.urls import path from invite import views app_name = 'invite' urlpatterns = [ path('', views.index, name='index'), path('invite/', views.invite, name='invite'), path('resend/<slug:code>/', views.resend, name='resend'), path('revoke/<slug:code>/', views.revoke, name='revoke'), path('login/', views.log_in_user, name='login'), path('logout/', views.log_out_user, name='edit_logout'), path('amnesia/', views.amnesia, name='amnesia'), path('reset/', views.reset, name='reset'), path('signup/', views.signup, name='account_signup'), path('about/', views.about, name='about'), path('check/', views.check, name='check'), ]
Fix issue with URL patterns adding parentheses around codes.
Fix issue with URL patterns adding parentheses around codes.
Python
bsd-3-clause
unt-libraries/django-invite,unt-libraries/django-invite
from django.urls import path from invite import views app_name = 'invite' urlpatterns = [ path('', views.index, name='index'), path('invite/', views.invite, name='invite'), path('resend/(<slug:code>)/', views.resend, name='resend'), path('revoke/(<slug:code>)/', views.revoke, name='revoke'), path('login/', views.log_in_user, name='login'), path('logout/', views.log_out_user, name='edit_logout'), path('amnesia/', views.amnesia, name='amnesia'), path('reset/', views.reset, name='reset'), path('signup/', views.signup, name='account_signup'), path('about/', views.about, name='about'), path('check/', views.check, name='check'), ] Fix issue with URL patterns adding parentheses around codes.
from django.urls import path from invite import views app_name = 'invite' urlpatterns = [ path('', views.index, name='index'), path('invite/', views.invite, name='invite'), path('resend/<slug:code>/', views.resend, name='resend'), path('revoke/<slug:code>/', views.revoke, name='revoke'), path('login/', views.log_in_user, name='login'), path('logout/', views.log_out_user, name='edit_logout'), path('amnesia/', views.amnesia, name='amnesia'), path('reset/', views.reset, name='reset'), path('signup/', views.signup, name='account_signup'), path('about/', views.about, name='about'), path('check/', views.check, name='check'), ]
<commit_before>from django.urls import path from invite import views app_name = 'invite' urlpatterns = [ path('', views.index, name='index'), path('invite/', views.invite, name='invite'), path('resend/(<slug:code>)/', views.resend, name='resend'), path('revoke/(<slug:code>)/', views.revoke, name='revoke'), path('login/', views.log_in_user, name='login'), path('logout/', views.log_out_user, name='edit_logout'), path('amnesia/', views.amnesia, name='amnesia'), path('reset/', views.reset, name='reset'), path('signup/', views.signup, name='account_signup'), path('about/', views.about, name='about'), path('check/', views.check, name='check'), ] <commit_msg>Fix issue with URL patterns adding parentheses around codes.<commit_after>
from django.urls import path from invite import views app_name = 'invite' urlpatterns = [ path('', views.index, name='index'), path('invite/', views.invite, name='invite'), path('resend/<slug:code>/', views.resend, name='resend'), path('revoke/<slug:code>/', views.revoke, name='revoke'), path('login/', views.log_in_user, name='login'), path('logout/', views.log_out_user, name='edit_logout'), path('amnesia/', views.amnesia, name='amnesia'), path('reset/', views.reset, name='reset'), path('signup/', views.signup, name='account_signup'), path('about/', views.about, name='about'), path('check/', views.check, name='check'), ]
from django.urls import path from invite import views app_name = 'invite' urlpatterns = [ path('', views.index, name='index'), path('invite/', views.invite, name='invite'), path('resend/(<slug:code>)/', views.resend, name='resend'), path('revoke/(<slug:code>)/', views.revoke, name='revoke'), path('login/', views.log_in_user, name='login'), path('logout/', views.log_out_user, name='edit_logout'), path('amnesia/', views.amnesia, name='amnesia'), path('reset/', views.reset, name='reset'), path('signup/', views.signup, name='account_signup'), path('about/', views.about, name='about'), path('check/', views.check, name='check'), ] Fix issue with URL patterns adding parentheses around codes.from django.urls import path from invite import views app_name = 'invite' urlpatterns = [ path('', views.index, name='index'), path('invite/', views.invite, name='invite'), path('resend/<slug:code>/', views.resend, name='resend'), path('revoke/<slug:code>/', views.revoke, name='revoke'), path('login/', views.log_in_user, name='login'), path('logout/', views.log_out_user, name='edit_logout'), path('amnesia/', views.amnesia, name='amnesia'), path('reset/', views.reset, name='reset'), path('signup/', views.signup, name='account_signup'), path('about/', views.about, name='about'), path('check/', views.check, name='check'), ]
<commit_before>from django.urls import path from invite import views app_name = 'invite' urlpatterns = [ path('', views.index, name='index'), path('invite/', views.invite, name='invite'), path('resend/(<slug:code>)/', views.resend, name='resend'), path('revoke/(<slug:code>)/', views.revoke, name='revoke'), path('login/', views.log_in_user, name='login'), path('logout/', views.log_out_user, name='edit_logout'), path('amnesia/', views.amnesia, name='amnesia'), path('reset/', views.reset, name='reset'), path('signup/', views.signup, name='account_signup'), path('about/', views.about, name='about'), path('check/', views.check, name='check'), ] <commit_msg>Fix issue with URL patterns adding parentheses around codes.<commit_after>from django.urls import path from invite import views app_name = 'invite' urlpatterns = [ path('', views.index, name='index'), path('invite/', views.invite, name='invite'), path('resend/<slug:code>/', views.resend, name='resend'), path('revoke/<slug:code>/', views.revoke, name='revoke'), path('login/', views.log_in_user, name='login'), path('logout/', views.log_out_user, name='edit_logout'), path('amnesia/', views.amnesia, name='amnesia'), path('reset/', views.reset, name='reset'), path('signup/', views.signup, name='account_signup'), path('about/', views.about, name='about'), path('check/', views.check, name='check'), ]
bfd8ac40bed4535a91bfd645cbe80b47c827a8de
librarian/embeds/mathml.py
librarian/embeds/mathml.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from lxml import etree import six from librarian import get_resource from . import TreeEmbed, create_embed, downgrades_to class MathML(TreeEmbed): @downgrades_to('application/x-latex') def to_latex(self): xslt = etree.parse(get_resource('res/embeds/mathml/mathml2latex.xslt')) output = self.tree.xslt(xslt) return create_embed('application/x-latex', data=six.text_type(output))
# -*- coding: utf-8 -*- from __future__ import unicode_literals from lxml import etree import six from librarian import get_resource from . import TreeEmbed, create_embed, downgrades_to class MathML(TreeEmbed): @downgrades_to('application/x-latex') def to_latex(self): """ >>> print(MathML(etree.fromstring('<mat>a &lt; b</mat>')).to_latex().data.strip()) a < b >>> print(MathML(etree.fromstring('<mat>&lt; &amp; &amp;lt; &#65;</mat>')).to_latex().data.strip()) < & &lt; A """ xslt = etree.parse(get_resource('res/embeds/mathml/mathml2latex.xslt')) output = self.tree.xslt(xslt) text = six.text_type(output) # Workaround for entities being preserved in output. But there should be a better way. text = text.replace('&lt;', '<').replace('&amp;', '&') return create_embed('application/x-latex', data=text)
Fix XML entities left from MathML.
Fix XML entities left from MathML.
Python
agpl-3.0
fnp/librarian,fnp/librarian
# -*- coding: utf-8 -*- from __future__ import unicode_literals from lxml import etree import six from librarian import get_resource from . import TreeEmbed, create_embed, downgrades_to class MathML(TreeEmbed): @downgrades_to('application/x-latex') def to_latex(self): xslt = etree.parse(get_resource('res/embeds/mathml/mathml2latex.xslt')) output = self.tree.xslt(xslt) return create_embed('application/x-latex', data=six.text_type(output)) Fix XML entities left from MathML.
# -*- coding: utf-8 -*- from __future__ import unicode_literals from lxml import etree import six from librarian import get_resource from . import TreeEmbed, create_embed, downgrades_to class MathML(TreeEmbed): @downgrades_to('application/x-latex') def to_latex(self): """ >>> print(MathML(etree.fromstring('<mat>a &lt; b</mat>')).to_latex().data.strip()) a < b >>> print(MathML(etree.fromstring('<mat>&lt; &amp; &amp;lt; &#65;</mat>')).to_latex().data.strip()) < & &lt; A """ xslt = etree.parse(get_resource('res/embeds/mathml/mathml2latex.xslt')) output = self.tree.xslt(xslt) text = six.text_type(output) # Workaround for entities being preserved in output. But there should be a better way. text = text.replace('&lt;', '<').replace('&amp;', '&') return create_embed('application/x-latex', data=text)
<commit_before># -*- coding: utf-8 -*- from __future__ import unicode_literals from lxml import etree import six from librarian import get_resource from . import TreeEmbed, create_embed, downgrades_to class MathML(TreeEmbed): @downgrades_to('application/x-latex') def to_latex(self): xslt = etree.parse(get_resource('res/embeds/mathml/mathml2latex.xslt')) output = self.tree.xslt(xslt) return create_embed('application/x-latex', data=six.text_type(output)) <commit_msg>Fix XML entities left from MathML.<commit_after>
# -*- coding: utf-8 -*- from __future__ import unicode_literals from lxml import etree import six from librarian import get_resource from . import TreeEmbed, create_embed, downgrades_to class MathML(TreeEmbed): @downgrades_to('application/x-latex') def to_latex(self): """ >>> print(MathML(etree.fromstring('<mat>a &lt; b</mat>')).to_latex().data.strip()) a < b >>> print(MathML(etree.fromstring('<mat>&lt; &amp; &amp;lt; &#65;</mat>')).to_latex().data.strip()) < & &lt; A """ xslt = etree.parse(get_resource('res/embeds/mathml/mathml2latex.xslt')) output = self.tree.xslt(xslt) text = six.text_type(output) # Workaround for entities being preserved in output. But there should be a better way. text = text.replace('&lt;', '<').replace('&amp;', '&') return create_embed('application/x-latex', data=text)
# -*- coding: utf-8 -*- from __future__ import unicode_literals from lxml import etree import six from librarian import get_resource from . import TreeEmbed, create_embed, downgrades_to class MathML(TreeEmbed): @downgrades_to('application/x-latex') def to_latex(self): xslt = etree.parse(get_resource('res/embeds/mathml/mathml2latex.xslt')) output = self.tree.xslt(xslt) return create_embed('application/x-latex', data=six.text_type(output)) Fix XML entities left from MathML.# -*- coding: utf-8 -*- from __future__ import unicode_literals from lxml import etree import six from librarian import get_resource from . import TreeEmbed, create_embed, downgrades_to class MathML(TreeEmbed): @downgrades_to('application/x-latex') def to_latex(self): """ >>> print(MathML(etree.fromstring('<mat>a &lt; b</mat>')).to_latex().data.strip()) a < b >>> print(MathML(etree.fromstring('<mat>&lt; &amp; &amp;lt; &#65;</mat>')).to_latex().data.strip()) < & &lt; A """ xslt = etree.parse(get_resource('res/embeds/mathml/mathml2latex.xslt')) output = self.tree.xslt(xslt) text = six.text_type(output) # Workaround for entities being preserved in output. But there should be a better way. text = text.replace('&lt;', '<').replace('&amp;', '&') return create_embed('application/x-latex', data=text)
<commit_before># -*- coding: utf-8 -*- from __future__ import unicode_literals from lxml import etree import six from librarian import get_resource from . import TreeEmbed, create_embed, downgrades_to class MathML(TreeEmbed): @downgrades_to('application/x-latex') def to_latex(self): xslt = etree.parse(get_resource('res/embeds/mathml/mathml2latex.xslt')) output = self.tree.xslt(xslt) return create_embed('application/x-latex', data=six.text_type(output)) <commit_msg>Fix XML entities left from MathML.<commit_after># -*- coding: utf-8 -*- from __future__ import unicode_literals from lxml import etree import six from librarian import get_resource from . import TreeEmbed, create_embed, downgrades_to class MathML(TreeEmbed): @downgrades_to('application/x-latex') def to_latex(self): """ >>> print(MathML(etree.fromstring('<mat>a &lt; b</mat>')).to_latex().data.strip()) a < b >>> print(MathML(etree.fromstring('<mat>&lt; &amp; &amp;lt; &#65;</mat>')).to_latex().data.strip()) < & &lt; A """ xslt = etree.parse(get_resource('res/embeds/mathml/mathml2latex.xslt')) output = self.tree.xslt(xslt) text = six.text_type(output) # Workaround for entities being preserved in output. But there should be a better way. text = text.replace('&lt;', '<').replace('&amp;', '&') return create_embed('application/x-latex', data=text)
ac55f6936551a0927b25aa520ab49649a6b4a904
plugins/basic_info_plugin.py
plugins/basic_info_plugin.py
import string import textwrap from veryprettytable import VeryPrettyTable from plugins import BasePlugin __author__ = 'peter' class BasicInfoPlugin(BasePlugin): short_description = 'Basic info:' default = True description = textwrap.dedent('''\ This plugin provides some basic info about the string such as: - Length - Presence of alpha/digits/raw bytes''') def handle(self): result = '' for s in self.args['STRING']: if len(self.args['STRING']) > 1: result += '{0}:\n'.format(s) table = VeryPrettyTable() table.field_names = ['Length', '# Digits', '# Alpha', '# Punct.', '# Control'] table.add_row((len(s), sum(x.isdigit() for x in s), sum(x.isalpha() for x in s), sum(x in string.punctuation for x in s), sum(x not in string.printable for x in s))) result += str(table) + '\n' return result
import string import textwrap from veryprettytable import VeryPrettyTable from plugins import BasePlugin __author__ = 'peter' class BasicInfoPlugin(BasePlugin): short_description = 'Basic info:' default = True description = textwrap.dedent('''\ This plugin provides some basic info about the string such as: - Length - Presence of alpha/digits/raw bytes''') def handle(self): table = VeryPrettyTable() table.field_names = ['String', 'Length', '# Digits', '# Alpha', '# Punct.', '# Control'] for s in self.args['STRING']: table.add_row((s, len(s), sum(x.isdigit() for x in s), sum(x.isalpha() for x in s), sum(x in string.punctuation for x in s), sum(x not in string.printable for x in s))) return str(table) + '\n'
Put basic info in one table
Put basic info in one table
Python
mit
Sakartu/stringinfo
import string import textwrap from veryprettytable import VeryPrettyTable from plugins import BasePlugin __author__ = 'peter' class BasicInfoPlugin(BasePlugin): short_description = 'Basic info:' default = True description = textwrap.dedent('''\ This plugin provides some basic info about the string such as: - Length - Presence of alpha/digits/raw bytes''') def handle(self): result = '' for s in self.args['STRING']: if len(self.args['STRING']) > 1: result += '{0}:\n'.format(s) table = VeryPrettyTable() table.field_names = ['Length', '# Digits', '# Alpha', '# Punct.', '# Control'] table.add_row((len(s), sum(x.isdigit() for x in s), sum(x.isalpha() for x in s), sum(x in string.punctuation for x in s), sum(x not in string.printable for x in s))) result += str(table) + '\n' return resultPut basic info in one table
import string import textwrap from veryprettytable import VeryPrettyTable from plugins import BasePlugin __author__ = 'peter' class BasicInfoPlugin(BasePlugin): short_description = 'Basic info:' default = True description = textwrap.dedent('''\ This plugin provides some basic info about the string such as: - Length - Presence of alpha/digits/raw bytes''') def handle(self): table = VeryPrettyTable() table.field_names = ['String', 'Length', '# Digits', '# Alpha', '# Punct.', '# Control'] for s in self.args['STRING']: table.add_row((s, len(s), sum(x.isdigit() for x in s), sum(x.isalpha() for x in s), sum(x in string.punctuation for x in s), sum(x not in string.printable for x in s))) return str(table) + '\n'
<commit_before>import string import textwrap from veryprettytable import VeryPrettyTable from plugins import BasePlugin __author__ = 'peter' class BasicInfoPlugin(BasePlugin): short_description = 'Basic info:' default = True description = textwrap.dedent('''\ This plugin provides some basic info about the string such as: - Length - Presence of alpha/digits/raw bytes''') def handle(self): result = '' for s in self.args['STRING']: if len(self.args['STRING']) > 1: result += '{0}:\n'.format(s) table = VeryPrettyTable() table.field_names = ['Length', '# Digits', '# Alpha', '# Punct.', '# Control'] table.add_row((len(s), sum(x.isdigit() for x in s), sum(x.isalpha() for x in s), sum(x in string.punctuation for x in s), sum(x not in string.printable for x in s))) result += str(table) + '\n' return result<commit_msg>Put basic info in one table<commit_after>
import string import textwrap from veryprettytable import VeryPrettyTable from plugins import BasePlugin __author__ = 'peter' class BasicInfoPlugin(BasePlugin): short_description = 'Basic info:' default = True description = textwrap.dedent('''\ This plugin provides some basic info about the string such as: - Length - Presence of alpha/digits/raw bytes''') def handle(self): table = VeryPrettyTable() table.field_names = ['String', 'Length', '# Digits', '# Alpha', '# Punct.', '# Control'] for s in self.args['STRING']: table.add_row((s, len(s), sum(x.isdigit() for x in s), sum(x.isalpha() for x in s), sum(x in string.punctuation for x in s), sum(x not in string.printable for x in s))) return str(table) + '\n'
import string import textwrap from veryprettytable import VeryPrettyTable from plugins import BasePlugin __author__ = 'peter' class BasicInfoPlugin(BasePlugin): short_description = 'Basic info:' default = True description = textwrap.dedent('''\ This plugin provides some basic info about the string such as: - Length - Presence of alpha/digits/raw bytes''') def handle(self): result = '' for s in self.args['STRING']: if len(self.args['STRING']) > 1: result += '{0}:\n'.format(s) table = VeryPrettyTable() table.field_names = ['Length', '# Digits', '# Alpha', '# Punct.', '# Control'] table.add_row((len(s), sum(x.isdigit() for x in s), sum(x.isalpha() for x in s), sum(x in string.punctuation for x in s), sum(x not in string.printable for x in s))) result += str(table) + '\n' return resultPut basic info in one tableimport string import textwrap from veryprettytable import VeryPrettyTable from plugins import BasePlugin __author__ = 'peter' class BasicInfoPlugin(BasePlugin): short_description = 'Basic info:' default = True description = textwrap.dedent('''\ This plugin provides some basic info about the string such as: - Length - Presence of alpha/digits/raw bytes''') def handle(self): table = VeryPrettyTable() table.field_names = ['String', 'Length', '# Digits', '# Alpha', '# Punct.', '# Control'] for s in self.args['STRING']: table.add_row((s, len(s), sum(x.isdigit() for x in s), sum(x.isalpha() for x in s), sum(x in string.punctuation for x in s), sum(x not in string.printable for x in s))) return str(table) + '\n'
<commit_before>import string import textwrap from veryprettytable import VeryPrettyTable from plugins import BasePlugin __author__ = 'peter' class BasicInfoPlugin(BasePlugin): short_description = 'Basic info:' default = True description = textwrap.dedent('''\ This plugin provides some basic info about the string such as: - Length - Presence of alpha/digits/raw bytes''') def handle(self): result = '' for s in self.args['STRING']: if len(self.args['STRING']) > 1: result += '{0}:\n'.format(s) table = VeryPrettyTable() table.field_names = ['Length', '# Digits', '# Alpha', '# Punct.', '# Control'] table.add_row((len(s), sum(x.isdigit() for x in s), sum(x.isalpha() for x in s), sum(x in string.punctuation for x in s), sum(x not in string.printable for x in s))) result += str(table) + '\n' return result<commit_msg>Put basic info in one table<commit_after>import string import textwrap from veryprettytable import VeryPrettyTable from plugins import BasePlugin __author__ = 'peter' class BasicInfoPlugin(BasePlugin): short_description = 'Basic info:' default = True description = textwrap.dedent('''\ This plugin provides some basic info about the string such as: - Length - Presence of alpha/digits/raw bytes''') def handle(self): table = VeryPrettyTable() table.field_names = ['String', 'Length', '# Digits', '# Alpha', '# Punct.', '# Control'] for s in self.args['STRING']: table.add_row((s, len(s), sum(x.isdigit() for x in s), sum(x.isalpha() for x in s), sum(x in string.punctuation for x in s), sum(x not in string.printable for x in s))) return str(table) + '\n'
a922c8ed94670a70d9c3351ac7fa59e4d4a8ae65
polyaxon/libs/repos/utils.py
polyaxon/libs/repos/utils.py
from django.core.exceptions import ObjectDoesNotExist from db.models.repos import CodeReference def get_internal_code_reference(instance, commit=None): project = instance.project if not project.has_code: return None repo = project.repo if commit: try: return CodeReference.objects.get(repo=repo, commit=commit) except ObjectDoesNotExist: return None # If no commit is provided we get the last commit, and save new ref if not found last_commit = repo.last_commit if not last_commit: return None code_reference, _ = CodeReference.objects.get_or_create(repo=repo, commit=last_commit[0]) return code_reference def get_external_code_reference(git_url, commit=None): code_reference, _ = CodeReference.objects.get_or_create(git_url=git_url, commit=commit) return code_reference def assign_code_reference(instance, commit=None): if instance.code_reference is not None or instance.specification is None: return build = instance.specification.build if instance.specification else None if not commit and build: commit = build.commit git_url = build.git if build and build.git else None if git_url: code_reference = get_external_code_reference(git_url=git_url, commit=commit) else: code_reference = get_internal_code_reference(instance=instance, commit=commit) if code_reference: instance.code_reference = code_reference return instance
from django.core.exceptions import ObjectDoesNotExist from db.models.repos import CodeReference def get_internal_code_reference(instance, commit=None): project = instance.project if not project.has_code: return None repo = project.repo if commit: try: return CodeReference.objects.get(repo=repo, commit=commit) except ObjectDoesNotExist: return None # If no commit is provided we get the last commit, and save new ref if not found last_commit = repo.last_commit if not last_commit: return None code_reference, _ = CodeReference.objects.get_or_create(repo=repo, commit=last_commit[0]) return code_reference def get_external_code_reference(git_url, commit=None): code_reference, _ = CodeReference.objects.get_or_create(git_url=git_url, commit=commit) return code_reference def assign_code_reference(instance, commit=None): if instance.code_reference is not None or instance.specification is None: return build = instance.specification.build if instance.specification else None if not commit and build: commit = build.ref git_url = build.git if build and build.git else None if git_url: code_reference = get_external_code_reference(git_url=git_url, commit=commit) else: code_reference = get_internal_code_reference(instance=instance, commit=commit) if code_reference: instance.code_reference = code_reference return instance
Use latest build schema commit -> ref
Use latest build schema commit -> ref
Python
apache-2.0
polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon
from django.core.exceptions import ObjectDoesNotExist from db.models.repos import CodeReference def get_internal_code_reference(instance, commit=None): project = instance.project if not project.has_code: return None repo = project.repo if commit: try: return CodeReference.objects.get(repo=repo, commit=commit) except ObjectDoesNotExist: return None # If no commit is provided we get the last commit, and save new ref if not found last_commit = repo.last_commit if not last_commit: return None code_reference, _ = CodeReference.objects.get_or_create(repo=repo, commit=last_commit[0]) return code_reference def get_external_code_reference(git_url, commit=None): code_reference, _ = CodeReference.objects.get_or_create(git_url=git_url, commit=commit) return code_reference def assign_code_reference(instance, commit=None): if instance.code_reference is not None or instance.specification is None: return build = instance.specification.build if instance.specification else None if not commit and build: commit = build.commit git_url = build.git if build and build.git else None if git_url: code_reference = get_external_code_reference(git_url=git_url, commit=commit) else: code_reference = get_internal_code_reference(instance=instance, commit=commit) if code_reference: instance.code_reference = code_reference return instance Use latest build schema commit -> ref
from django.core.exceptions import ObjectDoesNotExist from db.models.repos import CodeReference def get_internal_code_reference(instance, commit=None): project = instance.project if not project.has_code: return None repo = project.repo if commit: try: return CodeReference.objects.get(repo=repo, commit=commit) except ObjectDoesNotExist: return None # If no commit is provided we get the last commit, and save new ref if not found last_commit = repo.last_commit if not last_commit: return None code_reference, _ = CodeReference.objects.get_or_create(repo=repo, commit=last_commit[0]) return code_reference def get_external_code_reference(git_url, commit=None): code_reference, _ = CodeReference.objects.get_or_create(git_url=git_url, commit=commit) return code_reference def assign_code_reference(instance, commit=None): if instance.code_reference is not None or instance.specification is None: return build = instance.specification.build if instance.specification else None if not commit and build: commit = build.ref git_url = build.git if build and build.git else None if git_url: code_reference = get_external_code_reference(git_url=git_url, commit=commit) else: code_reference = get_internal_code_reference(instance=instance, commit=commit) if code_reference: instance.code_reference = code_reference return instance
<commit_before>from django.core.exceptions import ObjectDoesNotExist from db.models.repos import CodeReference def get_internal_code_reference(instance, commit=None): project = instance.project if not project.has_code: return None repo = project.repo if commit: try: return CodeReference.objects.get(repo=repo, commit=commit) except ObjectDoesNotExist: return None # If no commit is provided we get the last commit, and save new ref if not found last_commit = repo.last_commit if not last_commit: return None code_reference, _ = CodeReference.objects.get_or_create(repo=repo, commit=last_commit[0]) return code_reference def get_external_code_reference(git_url, commit=None): code_reference, _ = CodeReference.objects.get_or_create(git_url=git_url, commit=commit) return code_reference def assign_code_reference(instance, commit=None): if instance.code_reference is not None or instance.specification is None: return build = instance.specification.build if instance.specification else None if not commit and build: commit = build.commit git_url = build.git if build and build.git else None if git_url: code_reference = get_external_code_reference(git_url=git_url, commit=commit) else: code_reference = get_internal_code_reference(instance=instance, commit=commit) if code_reference: instance.code_reference = code_reference return instance <commit_msg>Use latest build schema commit -> ref<commit_after>
from django.core.exceptions import ObjectDoesNotExist from db.models.repos import CodeReference def get_internal_code_reference(instance, commit=None): project = instance.project if not project.has_code: return None repo = project.repo if commit: try: return CodeReference.objects.get(repo=repo, commit=commit) except ObjectDoesNotExist: return None # If no commit is provided we get the last commit, and save new ref if not found last_commit = repo.last_commit if not last_commit: return None code_reference, _ = CodeReference.objects.get_or_create(repo=repo, commit=last_commit[0]) return code_reference def get_external_code_reference(git_url, commit=None): code_reference, _ = CodeReference.objects.get_or_create(git_url=git_url, commit=commit) return code_reference def assign_code_reference(instance, commit=None): if instance.code_reference is not None or instance.specification is None: return build = instance.specification.build if instance.specification else None if not commit and build: commit = build.ref git_url = build.git if build and build.git else None if git_url: code_reference = get_external_code_reference(git_url=git_url, commit=commit) else: code_reference = get_internal_code_reference(instance=instance, commit=commit) if code_reference: instance.code_reference = code_reference return instance
from django.core.exceptions import ObjectDoesNotExist from db.models.repos import CodeReference def get_internal_code_reference(instance, commit=None): project = instance.project if not project.has_code: return None repo = project.repo if commit: try: return CodeReference.objects.get(repo=repo, commit=commit) except ObjectDoesNotExist: return None # If no commit is provided we get the last commit, and save new ref if not found last_commit = repo.last_commit if not last_commit: return None code_reference, _ = CodeReference.objects.get_or_create(repo=repo, commit=last_commit[0]) return code_reference def get_external_code_reference(git_url, commit=None): code_reference, _ = CodeReference.objects.get_or_create(git_url=git_url, commit=commit) return code_reference def assign_code_reference(instance, commit=None): if instance.code_reference is not None or instance.specification is None: return build = instance.specification.build if instance.specification else None if not commit and build: commit = build.commit git_url = build.git if build and build.git else None if git_url: code_reference = get_external_code_reference(git_url=git_url, commit=commit) else: code_reference = get_internal_code_reference(instance=instance, commit=commit) if code_reference: instance.code_reference = code_reference return instance Use latest build schema commit -> reffrom django.core.exceptions import ObjectDoesNotExist from db.models.repos import CodeReference def get_internal_code_reference(instance, commit=None): project = instance.project if not project.has_code: return None repo = project.repo if commit: try: return CodeReference.objects.get(repo=repo, commit=commit) except ObjectDoesNotExist: return None # If no commit is provided we get the last commit, and save new ref if not found last_commit = repo.last_commit if not last_commit: return None code_reference, _ = CodeReference.objects.get_or_create(repo=repo, commit=last_commit[0]) return code_reference def get_external_code_reference(git_url, commit=None): code_reference, _ = CodeReference.objects.get_or_create(git_url=git_url, commit=commit) return code_reference def assign_code_reference(instance, commit=None): if instance.code_reference is not None or instance.specification is None: return build = instance.specification.build if instance.specification else None if not commit and build: commit = build.ref git_url = build.git if build and build.git else None if git_url: code_reference = get_external_code_reference(git_url=git_url, commit=commit) else: code_reference = get_internal_code_reference(instance=instance, commit=commit) if code_reference: instance.code_reference = code_reference return instance
<commit_before>from django.core.exceptions import ObjectDoesNotExist from db.models.repos import CodeReference def get_internal_code_reference(instance, commit=None): project = instance.project if not project.has_code: return None repo = project.repo if commit: try: return CodeReference.objects.get(repo=repo, commit=commit) except ObjectDoesNotExist: return None # If no commit is provided we get the last commit, and save new ref if not found last_commit = repo.last_commit if not last_commit: return None code_reference, _ = CodeReference.objects.get_or_create(repo=repo, commit=last_commit[0]) return code_reference def get_external_code_reference(git_url, commit=None): code_reference, _ = CodeReference.objects.get_or_create(git_url=git_url, commit=commit) return code_reference def assign_code_reference(instance, commit=None): if instance.code_reference is not None or instance.specification is None: return build = instance.specification.build if instance.specification else None if not commit and build: commit = build.commit git_url = build.git if build and build.git else None if git_url: code_reference = get_external_code_reference(git_url=git_url, commit=commit) else: code_reference = get_internal_code_reference(instance=instance, commit=commit) if code_reference: instance.code_reference = code_reference return instance <commit_msg>Use latest build schema commit -> ref<commit_after>from django.core.exceptions import ObjectDoesNotExist from db.models.repos import CodeReference def get_internal_code_reference(instance, commit=None): project = instance.project if not project.has_code: return None repo = project.repo if commit: try: return CodeReference.objects.get(repo=repo, commit=commit) except ObjectDoesNotExist: return None # If no commit is provided we get the last commit, and save new ref if not found last_commit = repo.last_commit if not last_commit: return None code_reference, _ = CodeReference.objects.get_or_create(repo=repo, commit=last_commit[0]) return code_reference def get_external_code_reference(git_url, commit=None): code_reference, _ = CodeReference.objects.get_or_create(git_url=git_url, commit=commit) return code_reference def assign_code_reference(instance, commit=None): if instance.code_reference is not None or instance.specification is None: return build = instance.specification.build if instance.specification else None if not commit and build: commit = build.ref git_url = build.git if build and build.git else None if git_url: code_reference = get_external_code_reference(git_url=git_url, commit=commit) else: code_reference = get_internal_code_reference(instance=instance, commit=commit) if code_reference: instance.code_reference = code_reference return instance
98a79f8caf90cfed01f9dceaa70e71892ea42116
parsl/tests/test_staging/test_implicit_staging_ftp.py
parsl/tests/test_staging/test_implicit_staging_ftp.py
import pytest import parsl from parsl.app.app import App from parsl.data_provider.files import File from parsl.tests.configs.local_threads import config parsl.clear() parsl.load(config) @App('python') def sort_strings(inputs=[], outputs=[]): with open(inputs[0].filepath, 'r') as u: strs = u.readlines() strs.sort() with open(outputs[0].filepath, 'w') as s: for e in strs: s.write(e) @pytest.mark.local def test_implicit_staging_ftp(): """Test implicit staging for an ftp file Create a remote input file (ftp) that points to file_test_cpt.txt. """ unsorted_file = File('ftp://ftp.cs.brown.edu/pub/info/README') # Create a local file for output data sorted_file = File('sorted.txt') f = sort_strings(inputs=[unsorted_file], outputs=[sorted_file]) f.result() if __name__ == "__main__": import argparse parser = argparse.ArgumentParser() parser.add_argument("-d", "--debug", action='store_true', help="Count of apps to launch") args = parser.parse_args() if args.debug: parsl.set_stream_logger() test_implicit_staging_ftp()
import pytest import parsl from parsl.app.app import App from parsl.data_provider.files import File from parsl.tests.configs.local_threads import config parsl.clear() parsl.load(config) @App('python') def sort_strings(inputs=[], outputs=[]): with open(inputs[0].filepath, 'r') as u: strs = u.readlines() strs.sort() with open(outputs[0].filepath, 'w') as s: for e in strs: s.write(e) @pytest.mark.local def test_implicit_staging_ftp(): """Test implicit staging for an ftp file Create a remote input file (ftp) that points to file_test_cpt.txt. """ unsorted_file = File('ftp://www.iana.org/pub/mirror/rirstats/arin/ARIN-STATS-FORMAT-CHANGE.txt') # Create a local file for output data sorted_file = File('sorted.txt') f = sort_strings(inputs=[unsorted_file], outputs=[sorted_file]) f.result() if __name__ == "__main__": import argparse parser = argparse.ArgumentParser() parser.add_argument("-d", "--debug", action='store_true', help="Count of apps to launch") args = parser.parse_args() if args.debug: parsl.set_stream_logger() test_implicit_staging_ftp()
Change test FTP server address
Change test FTP server address
Python
apache-2.0
Parsl/parsl,Parsl/parsl,Parsl/parsl,Parsl/parsl,swift-lang/swift-e-lab,swift-lang/swift-e-lab
import pytest import parsl from parsl.app.app import App from parsl.data_provider.files import File from parsl.tests.configs.local_threads import config parsl.clear() parsl.load(config) @App('python') def sort_strings(inputs=[], outputs=[]): with open(inputs[0].filepath, 'r') as u: strs = u.readlines() strs.sort() with open(outputs[0].filepath, 'w') as s: for e in strs: s.write(e) @pytest.mark.local def test_implicit_staging_ftp(): """Test implicit staging for an ftp file Create a remote input file (ftp) that points to file_test_cpt.txt. """ unsorted_file = File('ftp://ftp.cs.brown.edu/pub/info/README') # Create a local file for output data sorted_file = File('sorted.txt') f = sort_strings(inputs=[unsorted_file], outputs=[sorted_file]) f.result() if __name__ == "__main__": import argparse parser = argparse.ArgumentParser() parser.add_argument("-d", "--debug", action='store_true', help="Count of apps to launch") args = parser.parse_args() if args.debug: parsl.set_stream_logger() test_implicit_staging_ftp() Change test FTP server address
import pytest import parsl from parsl.app.app import App from parsl.data_provider.files import File from parsl.tests.configs.local_threads import config parsl.clear() parsl.load(config) @App('python') def sort_strings(inputs=[], outputs=[]): with open(inputs[0].filepath, 'r') as u: strs = u.readlines() strs.sort() with open(outputs[0].filepath, 'w') as s: for e in strs: s.write(e) @pytest.mark.local def test_implicit_staging_ftp(): """Test implicit staging for an ftp file Create a remote input file (ftp) that points to file_test_cpt.txt. """ unsorted_file = File('ftp://www.iana.org/pub/mirror/rirstats/arin/ARIN-STATS-FORMAT-CHANGE.txt') # Create a local file for output data sorted_file = File('sorted.txt') f = sort_strings(inputs=[unsorted_file], outputs=[sorted_file]) f.result() if __name__ == "__main__": import argparse parser = argparse.ArgumentParser() parser.add_argument("-d", "--debug", action='store_true', help="Count of apps to launch") args = parser.parse_args() if args.debug: parsl.set_stream_logger() test_implicit_staging_ftp()
<commit_before>import pytest import parsl from parsl.app.app import App from parsl.data_provider.files import File from parsl.tests.configs.local_threads import config parsl.clear() parsl.load(config) @App('python') def sort_strings(inputs=[], outputs=[]): with open(inputs[0].filepath, 'r') as u: strs = u.readlines() strs.sort() with open(outputs[0].filepath, 'w') as s: for e in strs: s.write(e) @pytest.mark.local def test_implicit_staging_ftp(): """Test implicit staging for an ftp file Create a remote input file (ftp) that points to file_test_cpt.txt. """ unsorted_file = File('ftp://ftp.cs.brown.edu/pub/info/README') # Create a local file for output data sorted_file = File('sorted.txt') f = sort_strings(inputs=[unsorted_file], outputs=[sorted_file]) f.result() if __name__ == "__main__": import argparse parser = argparse.ArgumentParser() parser.add_argument("-d", "--debug", action='store_true', help="Count of apps to launch") args = parser.parse_args() if args.debug: parsl.set_stream_logger() test_implicit_staging_ftp() <commit_msg>Change test FTP server address<commit_after>
import pytest import parsl from parsl.app.app import App from parsl.data_provider.files import File from parsl.tests.configs.local_threads import config parsl.clear() parsl.load(config) @App('python') def sort_strings(inputs=[], outputs=[]): with open(inputs[0].filepath, 'r') as u: strs = u.readlines() strs.sort() with open(outputs[0].filepath, 'w') as s: for e in strs: s.write(e) @pytest.mark.local def test_implicit_staging_ftp(): """Test implicit staging for an ftp file Create a remote input file (ftp) that points to file_test_cpt.txt. """ unsorted_file = File('ftp://www.iana.org/pub/mirror/rirstats/arin/ARIN-STATS-FORMAT-CHANGE.txt') # Create a local file for output data sorted_file = File('sorted.txt') f = sort_strings(inputs=[unsorted_file], outputs=[sorted_file]) f.result() if __name__ == "__main__": import argparse parser = argparse.ArgumentParser() parser.add_argument("-d", "--debug", action='store_true', help="Count of apps to launch") args = parser.parse_args() if args.debug: parsl.set_stream_logger() test_implicit_staging_ftp()
import pytest import parsl from parsl.app.app import App from parsl.data_provider.files import File from parsl.tests.configs.local_threads import config parsl.clear() parsl.load(config) @App('python') def sort_strings(inputs=[], outputs=[]): with open(inputs[0].filepath, 'r') as u: strs = u.readlines() strs.sort() with open(outputs[0].filepath, 'w') as s: for e in strs: s.write(e) @pytest.mark.local def test_implicit_staging_ftp(): """Test implicit staging for an ftp file Create a remote input file (ftp) that points to file_test_cpt.txt. """ unsorted_file = File('ftp://ftp.cs.brown.edu/pub/info/README') # Create a local file for output data sorted_file = File('sorted.txt') f = sort_strings(inputs=[unsorted_file], outputs=[sorted_file]) f.result() if __name__ == "__main__": import argparse parser = argparse.ArgumentParser() parser.add_argument("-d", "--debug", action='store_true', help="Count of apps to launch") args = parser.parse_args() if args.debug: parsl.set_stream_logger() test_implicit_staging_ftp() Change test FTP server addressimport pytest import parsl from parsl.app.app import App from parsl.data_provider.files import File from parsl.tests.configs.local_threads import config parsl.clear() parsl.load(config) @App('python') def sort_strings(inputs=[], outputs=[]): with open(inputs[0].filepath, 'r') as u: strs = u.readlines() strs.sort() with open(outputs[0].filepath, 'w') as s: for e in strs: s.write(e) @pytest.mark.local def test_implicit_staging_ftp(): """Test implicit staging for an ftp file Create a remote input file (ftp) that points to file_test_cpt.txt. """ unsorted_file = File('ftp://www.iana.org/pub/mirror/rirstats/arin/ARIN-STATS-FORMAT-CHANGE.txt') # Create a local file for output data sorted_file = File('sorted.txt') f = sort_strings(inputs=[unsorted_file], outputs=[sorted_file]) f.result() if __name__ == "__main__": import argparse parser = argparse.ArgumentParser() parser.add_argument("-d", "--debug", action='store_true', help="Count of apps to launch") args = parser.parse_args() if args.debug: parsl.set_stream_logger() test_implicit_staging_ftp()
<commit_before>import pytest import parsl from parsl.app.app import App from parsl.data_provider.files import File from parsl.tests.configs.local_threads import config parsl.clear() parsl.load(config) @App('python') def sort_strings(inputs=[], outputs=[]): with open(inputs[0].filepath, 'r') as u: strs = u.readlines() strs.sort() with open(outputs[0].filepath, 'w') as s: for e in strs: s.write(e) @pytest.mark.local def test_implicit_staging_ftp(): """Test implicit staging for an ftp file Create a remote input file (ftp) that points to file_test_cpt.txt. """ unsorted_file = File('ftp://ftp.cs.brown.edu/pub/info/README') # Create a local file for output data sorted_file = File('sorted.txt') f = sort_strings(inputs=[unsorted_file], outputs=[sorted_file]) f.result() if __name__ == "__main__": import argparse parser = argparse.ArgumentParser() parser.add_argument("-d", "--debug", action='store_true', help="Count of apps to launch") args = parser.parse_args() if args.debug: parsl.set_stream_logger() test_implicit_staging_ftp() <commit_msg>Change test FTP server address<commit_after>import pytest import parsl from parsl.app.app import App from parsl.data_provider.files import File from parsl.tests.configs.local_threads import config parsl.clear() parsl.load(config) @App('python') def sort_strings(inputs=[], outputs=[]): with open(inputs[0].filepath, 'r') as u: strs = u.readlines() strs.sort() with open(outputs[0].filepath, 'w') as s: for e in strs: s.write(e) @pytest.mark.local def test_implicit_staging_ftp(): """Test implicit staging for an ftp file Create a remote input file (ftp) that points to file_test_cpt.txt. """ unsorted_file = File('ftp://www.iana.org/pub/mirror/rirstats/arin/ARIN-STATS-FORMAT-CHANGE.txt') # Create a local file for output data sorted_file = File('sorted.txt') f = sort_strings(inputs=[unsorted_file], outputs=[sorted_file]) f.result() if __name__ == "__main__": import argparse parser = argparse.ArgumentParser() parser.add_argument("-d", "--debug", action='store_true', help="Count of apps to launch") args = parser.parse_args() if args.debug: parsl.set_stream_logger() test_implicit_staging_ftp()
aa69ae87a947ee17d72d7881dc61a5091772ff6c
pythainlp/segment/pyicu.py
pythainlp/segment/pyicu.py
from __future__ import absolute_import,print_function from itertools import groupby import PyICU import six # ตัดคำภาษาไทย def segment(txt): """รับค่า ''str'' คืนค่าออกมาเป็น ''list'' ที่ได้มาจากการตัดคำโดย ICU""" bd = PyICU.BreakIterator.createWordInstance(PyICU.Locale("th")) bd.setText(six.u(txt)) breaks = list(bd) return [txt[x[0]:x[1]] for x in zip([0]+breaks, breaks)] if __name__ == "__main__": print(segment('ทดสอบระบบตัดคำด้วยไอซียู')) print(segment('ผมชอบพูดไทยคำ English คำ')) print(segment('ผมชอบพูดไทยคำEnglishคำ'))
from __future__ import absolute_import,print_function from itertools import groupby import PyICU # ตัดคำภาษาไทย def segment(txt): """รับค่า ''str'' คืนค่าออกมาเป็น ''list'' ที่ได้มาจากการตัดคำโดย ICU""" bd = PyICU.BreakIterator.createWordInstance(PyICU.Locale("th")) bd.setText(six.u(txt)) breaks = list(bd) return [txt[x[0]:x[1]] for x in zip([0]+breaks, breaks)] if __name__ == "__main__": print(segment('ทดสอบระบบตัดคำด้วยไอซียู')) print(segment('ผมชอบพูดไทยคำ English คำ')) print(segment('ผมชอบพูดไทยคำEnglishคำ'))
Revert "fix bug import six"
Revert "fix bug import six" This reverts commit a80c1d7c80d68f72d435dbb7ac5c48a6114716fb.
Python
apache-2.0
PyThaiNLP/pythainlp
from __future__ import absolute_import,print_function from itertools import groupby import PyICU import six # ตัดคำภาษาไทย def segment(txt): """รับค่า ''str'' คืนค่าออกมาเป็น ''list'' ที่ได้มาจากการตัดคำโดย ICU""" bd = PyICU.BreakIterator.createWordInstance(PyICU.Locale("th")) bd.setText(six.u(txt)) breaks = list(bd) return [txt[x[0]:x[1]] for x in zip([0]+breaks, breaks)] if __name__ == "__main__": print(segment('ทดสอบระบบตัดคำด้วยไอซียู')) print(segment('ผมชอบพูดไทยคำ English คำ')) print(segment('ผมชอบพูดไทยคำEnglishคำ'))Revert "fix bug import six" This reverts commit a80c1d7c80d68f72d435dbb7ac5c48a6114716fb.
from __future__ import absolute_import,print_function from itertools import groupby import PyICU # ตัดคำภาษาไทย def segment(txt): """รับค่า ''str'' คืนค่าออกมาเป็น ''list'' ที่ได้มาจากการตัดคำโดย ICU""" bd = PyICU.BreakIterator.createWordInstance(PyICU.Locale("th")) bd.setText(six.u(txt)) breaks = list(bd) return [txt[x[0]:x[1]] for x in zip([0]+breaks, breaks)] if __name__ == "__main__": print(segment('ทดสอบระบบตัดคำด้วยไอซียู')) print(segment('ผมชอบพูดไทยคำ English คำ')) print(segment('ผมชอบพูดไทยคำEnglishคำ'))
<commit_before>from __future__ import absolute_import,print_function from itertools import groupby import PyICU import six # ตัดคำภาษาไทย def segment(txt): """รับค่า ''str'' คืนค่าออกมาเป็น ''list'' ที่ได้มาจากการตัดคำโดย ICU""" bd = PyICU.BreakIterator.createWordInstance(PyICU.Locale("th")) bd.setText(six.u(txt)) breaks = list(bd) return [txt[x[0]:x[1]] for x in zip([0]+breaks, breaks)] if __name__ == "__main__": print(segment('ทดสอบระบบตัดคำด้วยไอซียู')) print(segment('ผมชอบพูดไทยคำ English คำ')) print(segment('ผมชอบพูดไทยคำEnglishคำ'))<commit_msg>Revert "fix bug import six" This reverts commit a80c1d7c80d68f72d435dbb7ac5c48a6114716fb.<commit_after>
from __future__ import absolute_import,print_function from itertools import groupby import PyICU # ตัดคำภาษาไทย def segment(txt): """รับค่า ''str'' คืนค่าออกมาเป็น ''list'' ที่ได้มาจากการตัดคำโดย ICU""" bd = PyICU.BreakIterator.createWordInstance(PyICU.Locale("th")) bd.setText(six.u(txt)) breaks = list(bd) return [txt[x[0]:x[1]] for x in zip([0]+breaks, breaks)] if __name__ == "__main__": print(segment('ทดสอบระบบตัดคำด้วยไอซียู')) print(segment('ผมชอบพูดไทยคำ English คำ')) print(segment('ผมชอบพูดไทยคำEnglishคำ'))
from __future__ import absolute_import,print_function from itertools import groupby import PyICU import six # ตัดคำภาษาไทย def segment(txt): """รับค่า ''str'' คืนค่าออกมาเป็น ''list'' ที่ได้มาจากการตัดคำโดย ICU""" bd = PyICU.BreakIterator.createWordInstance(PyICU.Locale("th")) bd.setText(six.u(txt)) breaks = list(bd) return [txt[x[0]:x[1]] for x in zip([0]+breaks, breaks)] if __name__ == "__main__": print(segment('ทดสอบระบบตัดคำด้วยไอซียู')) print(segment('ผมชอบพูดไทยคำ English คำ')) print(segment('ผมชอบพูดไทยคำEnglishคำ'))Revert "fix bug import six" This reverts commit a80c1d7c80d68f72d435dbb7ac5c48a6114716fb.from __future__ import absolute_import,print_function from itertools import groupby import PyICU # ตัดคำภาษาไทย def segment(txt): """รับค่า ''str'' คืนค่าออกมาเป็น ''list'' ที่ได้มาจากการตัดคำโดย ICU""" bd = PyICU.BreakIterator.createWordInstance(PyICU.Locale("th")) bd.setText(six.u(txt)) breaks = list(bd) return [txt[x[0]:x[1]] for x in zip([0]+breaks, breaks)] if __name__ == "__main__": print(segment('ทดสอบระบบตัดคำด้วยไอซียู')) print(segment('ผมชอบพูดไทยคำ English คำ')) print(segment('ผมชอบพูดไทยคำEnglishคำ'))
<commit_before>from __future__ import absolute_import,print_function from itertools import groupby import PyICU import six # ตัดคำภาษาไทย def segment(txt): """รับค่า ''str'' คืนค่าออกมาเป็น ''list'' ที่ได้มาจากการตัดคำโดย ICU""" bd = PyICU.BreakIterator.createWordInstance(PyICU.Locale("th")) bd.setText(six.u(txt)) breaks = list(bd) return [txt[x[0]:x[1]] for x in zip([0]+breaks, breaks)] if __name__ == "__main__": print(segment('ทดสอบระบบตัดคำด้วยไอซียู')) print(segment('ผมชอบพูดไทยคำ English คำ')) print(segment('ผมชอบพูดไทยคำEnglishคำ'))<commit_msg>Revert "fix bug import six" This reverts commit a80c1d7c80d68f72d435dbb7ac5c48a6114716fb.<commit_after>from __future__ import absolute_import,print_function from itertools import groupby import PyICU # ตัดคำภาษาไทย def segment(txt): """รับค่า ''str'' คืนค่าออกมาเป็น ''list'' ที่ได้มาจากการตัดคำโดย ICU""" bd = PyICU.BreakIterator.createWordInstance(PyICU.Locale("th")) bd.setText(six.u(txt)) breaks = list(bd) return [txt[x[0]:x[1]] for x in zip([0]+breaks, breaks)] if __name__ == "__main__": print(segment('ทดสอบระบบตัดคำด้วยไอซียู')) print(segment('ผมชอบพูดไทยคำ English คำ')) print(segment('ผมชอบพูดไทยคำEnglishคำ'))
cbea20e07807df21645c0edd52ccfdef2c5f72f1
modules/dispatcher.py
modules/dispatcher.py
from os import unlink from configobj import ConfigObj from tests.ch_mock import Twitter def Dispatch(channels, msgFile): msgConfig = ConfigObj(msgFile) Topic = msgConfig['Topic'] To_Email = msgConfig['To_Email'] Message = msgConfig['Message'] unlink(msgFile) reply = {} for channel in channels: if channel == 'Twitter': chObj = Twitter() reply['Twitter'] = chObj.SendMsg(Message) return reply
from os import unlink from configobj import ConfigObj from twitter import Twitter def Dispatch(channels, msgFile): msgConfig = ConfigObj(msgFile) Topic = msgConfig['Topic'] To_Email = msgConfig['To_Email'] Message = msgConfig['Message'] unlink(msgFile) reply = {} for channel in channels: if channel == 'Twitter': chObj = Twitter() reply['Twitter'] = chObj.SendMsg(Message) return reply
Replace mock Twitter channel with actual channel
Replace mock Twitter channel with actual channel
Python
mit
alfie-max/Publish
from os import unlink from configobj import ConfigObj from tests.ch_mock import Twitter def Dispatch(channels, msgFile): msgConfig = ConfigObj(msgFile) Topic = msgConfig['Topic'] To_Email = msgConfig['To_Email'] Message = msgConfig['Message'] unlink(msgFile) reply = {} for channel in channels: if channel == 'Twitter': chObj = Twitter() reply['Twitter'] = chObj.SendMsg(Message) return reply Replace mock Twitter channel with actual channel
from os import unlink from configobj import ConfigObj from twitter import Twitter def Dispatch(channels, msgFile): msgConfig = ConfigObj(msgFile) Topic = msgConfig['Topic'] To_Email = msgConfig['To_Email'] Message = msgConfig['Message'] unlink(msgFile) reply = {} for channel in channels: if channel == 'Twitter': chObj = Twitter() reply['Twitter'] = chObj.SendMsg(Message) return reply
<commit_before>from os import unlink from configobj import ConfigObj from tests.ch_mock import Twitter def Dispatch(channels, msgFile): msgConfig = ConfigObj(msgFile) Topic = msgConfig['Topic'] To_Email = msgConfig['To_Email'] Message = msgConfig['Message'] unlink(msgFile) reply = {} for channel in channels: if channel == 'Twitter': chObj = Twitter() reply['Twitter'] = chObj.SendMsg(Message) return reply <commit_msg>Replace mock Twitter channel with actual channel<commit_after>
from os import unlink from configobj import ConfigObj from twitter import Twitter def Dispatch(channels, msgFile): msgConfig = ConfigObj(msgFile) Topic = msgConfig['Topic'] To_Email = msgConfig['To_Email'] Message = msgConfig['Message'] unlink(msgFile) reply = {} for channel in channels: if channel == 'Twitter': chObj = Twitter() reply['Twitter'] = chObj.SendMsg(Message) return reply
from os import unlink from configobj import ConfigObj from tests.ch_mock import Twitter def Dispatch(channels, msgFile): msgConfig = ConfigObj(msgFile) Topic = msgConfig['Topic'] To_Email = msgConfig['To_Email'] Message = msgConfig['Message'] unlink(msgFile) reply = {} for channel in channels: if channel == 'Twitter': chObj = Twitter() reply['Twitter'] = chObj.SendMsg(Message) return reply Replace mock Twitter channel with actual channelfrom os import unlink from configobj import ConfigObj from twitter import Twitter def Dispatch(channels, msgFile): msgConfig = ConfigObj(msgFile) Topic = msgConfig['Topic'] To_Email = msgConfig['To_Email'] Message = msgConfig['Message'] unlink(msgFile) reply = {} for channel in channels: if channel == 'Twitter': chObj = Twitter() reply['Twitter'] = chObj.SendMsg(Message) return reply
<commit_before>from os import unlink from configobj import ConfigObj from tests.ch_mock import Twitter def Dispatch(channels, msgFile): msgConfig = ConfigObj(msgFile) Topic = msgConfig['Topic'] To_Email = msgConfig['To_Email'] Message = msgConfig['Message'] unlink(msgFile) reply = {} for channel in channels: if channel == 'Twitter': chObj = Twitter() reply['Twitter'] = chObj.SendMsg(Message) return reply <commit_msg>Replace mock Twitter channel with actual channel<commit_after>from os import unlink from configobj import ConfigObj from twitter import Twitter def Dispatch(channels, msgFile): msgConfig = ConfigObj(msgFile) Topic = msgConfig['Topic'] To_Email = msgConfig['To_Email'] Message = msgConfig['Message'] unlink(msgFile) reply = {} for channel in channels: if channel == 'Twitter': chObj = Twitter() reply['Twitter'] = chObj.SendMsg(Message) return reply
8cfa861107ae9ed829561300baeab74e7d0dd0f3
mysite/urls.py
mysite/urls.py
from django.conf.urls import patterns, include, url from django.contrib import admin from candidates.views import (ConstituencyPostcodeFinderView, ConstituencyDetailView, CandidacyView, CandidacyDeleteView, NewPersonView) admin.autodiscover() urlpatterns = patterns('', url(r'^$', ConstituencyPostcodeFinderView.as_view(), name='finder'), url(r'^constituency/(?P<constituency_name>.*)$', ConstituencyDetailView.as_view(), name='constituency'), url(r'^candidacy$', CandidacyView.as_view(), name='candidacy-create'), url(r'^candidacy/delete$', CandidacyDeleteView.as_view(), name='candidacy-delete'), url(r'^person$', NewPersonView.as_view(), name='person-create'), url(r'^admin/', include(admin.site.urls)), )
from django.conf.urls import patterns, include, url from django.contrib import admin from candidates.views import (ConstituencyPostcodeFinderView, ConstituencyDetailView, CandidacyView, CandidacyDeleteView, NewPersonView) admin.autodiscover() urlpatterns = patterns('', url(r'^$', ConstituencyPostcodeFinderView.as_view(), name='finder'), url(r'^lookup/postcode$', ConstituencyPostcodeFinderView.as_view(), name='lookup-postcode'), url(r'^constituency/(?P<constituency_name>.*)$', ConstituencyDetailView.as_view(), name='constituency'), url(r'^candidacy$', CandidacyView.as_view(), name='candidacy-create'), url(r'^candidacy/delete$', CandidacyDeleteView.as_view(), name='candidacy-delete'), url(r'^person$', NewPersonView.as_view(), name='person-create'), url(r'^admin/', include(admin.site.urls)), )
Add a separate endpoint for posting postcode lookups to
Add a separate endpoint for posting postcode lookups to
Python
agpl-3.0
mysociety/yournextrepresentative,mysociety/yournextmp-popit,mysociety/yournextmp-popit,DemocracyClub/yournextrepresentative,mysociety/yournextrepresentative,openstate/yournextrepresentative,neavouli/yournextrepresentative,mysociety/yournextmp-popit,neavouli/yournextrepresentative,openstate/yournextrepresentative,openstate/yournextrepresentative,openstate/yournextrepresentative,mhl/yournextmp-popit,mysociety/yournextrepresentative,datamade/yournextmp-popit,YoQuieroSaber/yournextrepresentative,mysociety/yournextmp-popit,openstate/yournextrepresentative,neavouli/yournextrepresentative,YoQuieroSaber/yournextrepresentative,YoQuieroSaber/yournextrepresentative,datamade/yournextmp-popit,mysociety/yournextrepresentative,mysociety/yournextrepresentative,neavouli/yournextrepresentative,datamade/yournextmp-popit,datamade/yournextmp-popit,mhl/yournextmp-popit,mysociety/yournextmp-popit,DemocracyClub/yournextrepresentative,neavouli/yournextrepresentative,datamade/yournextmp-popit,YoQuieroSaber/yournextrepresentative,mhl/yournextmp-popit,DemocracyClub/yournextrepresentative,YoQuieroSaber/yournextrepresentative
from django.conf.urls import patterns, include, url from django.contrib import admin from candidates.views import (ConstituencyPostcodeFinderView, ConstituencyDetailView, CandidacyView, CandidacyDeleteView, NewPersonView) admin.autodiscover() urlpatterns = patterns('', url(r'^$', ConstituencyPostcodeFinderView.as_view(), name='finder'), url(r'^constituency/(?P<constituency_name>.*)$', ConstituencyDetailView.as_view(), name='constituency'), url(r'^candidacy$', CandidacyView.as_view(), name='candidacy-create'), url(r'^candidacy/delete$', CandidacyDeleteView.as_view(), name='candidacy-delete'), url(r'^person$', NewPersonView.as_view(), name='person-create'), url(r'^admin/', include(admin.site.urls)), ) Add a separate endpoint for posting postcode lookups to
from django.conf.urls import patterns, include, url from django.contrib import admin from candidates.views import (ConstituencyPostcodeFinderView, ConstituencyDetailView, CandidacyView, CandidacyDeleteView, NewPersonView) admin.autodiscover() urlpatterns = patterns('', url(r'^$', ConstituencyPostcodeFinderView.as_view(), name='finder'), url(r'^lookup/postcode$', ConstituencyPostcodeFinderView.as_view(), name='lookup-postcode'), url(r'^constituency/(?P<constituency_name>.*)$', ConstituencyDetailView.as_view(), name='constituency'), url(r'^candidacy$', CandidacyView.as_view(), name='candidacy-create'), url(r'^candidacy/delete$', CandidacyDeleteView.as_view(), name='candidacy-delete'), url(r'^person$', NewPersonView.as_view(), name='person-create'), url(r'^admin/', include(admin.site.urls)), )
<commit_before>from django.conf.urls import patterns, include, url from django.contrib import admin from candidates.views import (ConstituencyPostcodeFinderView, ConstituencyDetailView, CandidacyView, CandidacyDeleteView, NewPersonView) admin.autodiscover() urlpatterns = patterns('', url(r'^$', ConstituencyPostcodeFinderView.as_view(), name='finder'), url(r'^constituency/(?P<constituency_name>.*)$', ConstituencyDetailView.as_view(), name='constituency'), url(r'^candidacy$', CandidacyView.as_view(), name='candidacy-create'), url(r'^candidacy/delete$', CandidacyDeleteView.as_view(), name='candidacy-delete'), url(r'^person$', NewPersonView.as_view(), name='person-create'), url(r'^admin/', include(admin.site.urls)), ) <commit_msg>Add a separate endpoint for posting postcode lookups to<commit_after>
from django.conf.urls import patterns, include, url from django.contrib import admin from candidates.views import (ConstituencyPostcodeFinderView, ConstituencyDetailView, CandidacyView, CandidacyDeleteView, NewPersonView) admin.autodiscover() urlpatterns = patterns('', url(r'^$', ConstituencyPostcodeFinderView.as_view(), name='finder'), url(r'^lookup/postcode$', ConstituencyPostcodeFinderView.as_view(), name='lookup-postcode'), url(r'^constituency/(?P<constituency_name>.*)$', ConstituencyDetailView.as_view(), name='constituency'), url(r'^candidacy$', CandidacyView.as_view(), name='candidacy-create'), url(r'^candidacy/delete$', CandidacyDeleteView.as_view(), name='candidacy-delete'), url(r'^person$', NewPersonView.as_view(), name='person-create'), url(r'^admin/', include(admin.site.urls)), )
from django.conf.urls import patterns, include, url from django.contrib import admin from candidates.views import (ConstituencyPostcodeFinderView, ConstituencyDetailView, CandidacyView, CandidacyDeleteView, NewPersonView) admin.autodiscover() urlpatterns = patterns('', url(r'^$', ConstituencyPostcodeFinderView.as_view(), name='finder'), url(r'^constituency/(?P<constituency_name>.*)$', ConstituencyDetailView.as_view(), name='constituency'), url(r'^candidacy$', CandidacyView.as_view(), name='candidacy-create'), url(r'^candidacy/delete$', CandidacyDeleteView.as_view(), name='candidacy-delete'), url(r'^person$', NewPersonView.as_view(), name='person-create'), url(r'^admin/', include(admin.site.urls)), ) Add a separate endpoint for posting postcode lookups tofrom django.conf.urls import patterns, include, url from django.contrib import admin from candidates.views import (ConstituencyPostcodeFinderView, ConstituencyDetailView, CandidacyView, CandidacyDeleteView, NewPersonView) admin.autodiscover() urlpatterns = patterns('', url(r'^$', ConstituencyPostcodeFinderView.as_view(), name='finder'), url(r'^lookup/postcode$', ConstituencyPostcodeFinderView.as_view(), name='lookup-postcode'), url(r'^constituency/(?P<constituency_name>.*)$', ConstituencyDetailView.as_view(), name='constituency'), url(r'^candidacy$', CandidacyView.as_view(), name='candidacy-create'), url(r'^candidacy/delete$', CandidacyDeleteView.as_view(), name='candidacy-delete'), url(r'^person$', NewPersonView.as_view(), name='person-create'), url(r'^admin/', include(admin.site.urls)), )
<commit_before>from django.conf.urls import patterns, include, url from django.contrib import admin from candidates.views import (ConstituencyPostcodeFinderView, ConstituencyDetailView, CandidacyView, CandidacyDeleteView, NewPersonView) admin.autodiscover() urlpatterns = patterns('', url(r'^$', ConstituencyPostcodeFinderView.as_view(), name='finder'), url(r'^constituency/(?P<constituency_name>.*)$', ConstituencyDetailView.as_view(), name='constituency'), url(r'^candidacy$', CandidacyView.as_view(), name='candidacy-create'), url(r'^candidacy/delete$', CandidacyDeleteView.as_view(), name='candidacy-delete'), url(r'^person$', NewPersonView.as_view(), name='person-create'), url(r'^admin/', include(admin.site.urls)), ) <commit_msg>Add a separate endpoint for posting postcode lookups to<commit_after>from django.conf.urls import patterns, include, url from django.contrib import admin from candidates.views import (ConstituencyPostcodeFinderView, ConstituencyDetailView, CandidacyView, CandidacyDeleteView, NewPersonView) admin.autodiscover() urlpatterns = patterns('', url(r'^$', ConstituencyPostcodeFinderView.as_view(), name='finder'), url(r'^lookup/postcode$', ConstituencyPostcodeFinderView.as_view(), name='lookup-postcode'), url(r'^constituency/(?P<constituency_name>.*)$', ConstituencyDetailView.as_view(), name='constituency'), url(r'^candidacy$', CandidacyView.as_view(), name='candidacy-create'), url(r'^candidacy/delete$', CandidacyDeleteView.as_view(), name='candidacy-delete'), url(r'^person$', NewPersonView.as_view(), name='person-create'), url(r'^admin/', include(admin.site.urls)), )
61253510bc859ec1695484d11cbadcd92ad4b107
tests/test_misc.py
tests/test_misc.py
import mistune from unittest import TestCase class TestMiscCases(TestCase): def test_none(self): self.assertEqual(mistune.html(None), '') def test_before_parse_hooks(self): def _add_name(md, s, state): state['name'] = 'test' return s, state md = mistune.create_markdown() md.before_parse_hooks.append(_add_name) state = {} md.parse('', state) self.assertEqual(state['name'], 'test')
import mistune from unittest import TestCase class TestMiscCases(TestCase): def test_none(self): self.assertEqual(mistune.html(None), '') def test_before_parse_hooks(self): def _add_name(md, s, state): state['name'] = 'test' return s, state md = mistune.create_markdown() md.before_parse_hooks.append(_add_name) state = {} md.parse('', state) self.assertEqual(state['name'], 'test') def test_escape_html(self): md = mistune.create_markdown(escape=True) result = md('<div>1</div>') expected = '<p>&lt;div&gt;1&lt;/div&gt;</p>' self.assertEqual(result.strip(), expected) result = md('<em>1</em>') expected = '<p>&lt;em&gt;1&lt;/em&gt;</p>' self.assertEqual(result.strip(), expected) def test_emphasis(self): md = mistune.create_markdown(escape=True) result = md('_em_ **strong**') expected = '<p><em>em</em> <strong>strong</strong></p>' self.assertEqual(result.strip(), expected) def test_allow_harmful_protocols(self): renderer = mistune.HTMLRenderer(allow_harmful_protocols=True) md = mistune.Markdown(renderer) result = md('[h](javascript:alert)') expected = '<p><a href="javascript:alert">h</a></p>' self.assertEqual(result.strip(), expected)
Add test for allow harmful protocols
Add test for allow harmful protocols
Python
bsd-3-clause
lepture/mistune
import mistune from unittest import TestCase class TestMiscCases(TestCase): def test_none(self): self.assertEqual(mistune.html(None), '') def test_before_parse_hooks(self): def _add_name(md, s, state): state['name'] = 'test' return s, state md = mistune.create_markdown() md.before_parse_hooks.append(_add_name) state = {} md.parse('', state) self.assertEqual(state['name'], 'test') Add test for allow harmful protocols
import mistune from unittest import TestCase class TestMiscCases(TestCase): def test_none(self): self.assertEqual(mistune.html(None), '') def test_before_parse_hooks(self): def _add_name(md, s, state): state['name'] = 'test' return s, state md = mistune.create_markdown() md.before_parse_hooks.append(_add_name) state = {} md.parse('', state) self.assertEqual(state['name'], 'test') def test_escape_html(self): md = mistune.create_markdown(escape=True) result = md('<div>1</div>') expected = '<p>&lt;div&gt;1&lt;/div&gt;</p>' self.assertEqual(result.strip(), expected) result = md('<em>1</em>') expected = '<p>&lt;em&gt;1&lt;/em&gt;</p>' self.assertEqual(result.strip(), expected) def test_emphasis(self): md = mistune.create_markdown(escape=True) result = md('_em_ **strong**') expected = '<p><em>em</em> <strong>strong</strong></p>' self.assertEqual(result.strip(), expected) def test_allow_harmful_protocols(self): renderer = mistune.HTMLRenderer(allow_harmful_protocols=True) md = mistune.Markdown(renderer) result = md('[h](javascript:alert)') expected = '<p><a href="javascript:alert">h</a></p>' self.assertEqual(result.strip(), expected)
<commit_before>import mistune from unittest import TestCase class TestMiscCases(TestCase): def test_none(self): self.assertEqual(mistune.html(None), '') def test_before_parse_hooks(self): def _add_name(md, s, state): state['name'] = 'test' return s, state md = mistune.create_markdown() md.before_parse_hooks.append(_add_name) state = {} md.parse('', state) self.assertEqual(state['name'], 'test') <commit_msg>Add test for allow harmful protocols<commit_after>
import mistune from unittest import TestCase class TestMiscCases(TestCase): def test_none(self): self.assertEqual(mistune.html(None), '') def test_before_parse_hooks(self): def _add_name(md, s, state): state['name'] = 'test' return s, state md = mistune.create_markdown() md.before_parse_hooks.append(_add_name) state = {} md.parse('', state) self.assertEqual(state['name'], 'test') def test_escape_html(self): md = mistune.create_markdown(escape=True) result = md('<div>1</div>') expected = '<p>&lt;div&gt;1&lt;/div&gt;</p>' self.assertEqual(result.strip(), expected) result = md('<em>1</em>') expected = '<p>&lt;em&gt;1&lt;/em&gt;</p>' self.assertEqual(result.strip(), expected) def test_emphasis(self): md = mistune.create_markdown(escape=True) result = md('_em_ **strong**') expected = '<p><em>em</em> <strong>strong</strong></p>' self.assertEqual(result.strip(), expected) def test_allow_harmful_protocols(self): renderer = mistune.HTMLRenderer(allow_harmful_protocols=True) md = mistune.Markdown(renderer) result = md('[h](javascript:alert)') expected = '<p><a href="javascript:alert">h</a></p>' self.assertEqual(result.strip(), expected)
import mistune from unittest import TestCase class TestMiscCases(TestCase): def test_none(self): self.assertEqual(mistune.html(None), '') def test_before_parse_hooks(self): def _add_name(md, s, state): state['name'] = 'test' return s, state md = mistune.create_markdown() md.before_parse_hooks.append(_add_name) state = {} md.parse('', state) self.assertEqual(state['name'], 'test') Add test for allow harmful protocolsimport mistune from unittest import TestCase class TestMiscCases(TestCase): def test_none(self): self.assertEqual(mistune.html(None), '') def test_before_parse_hooks(self): def _add_name(md, s, state): state['name'] = 'test' return s, state md = mistune.create_markdown() md.before_parse_hooks.append(_add_name) state = {} md.parse('', state) self.assertEqual(state['name'], 'test') def test_escape_html(self): md = mistune.create_markdown(escape=True) result = md('<div>1</div>') expected = '<p>&lt;div&gt;1&lt;/div&gt;</p>' self.assertEqual(result.strip(), expected) result = md('<em>1</em>') expected = '<p>&lt;em&gt;1&lt;/em&gt;</p>' self.assertEqual(result.strip(), expected) def test_emphasis(self): md = mistune.create_markdown(escape=True) result = md('_em_ **strong**') expected = '<p><em>em</em> <strong>strong</strong></p>' self.assertEqual(result.strip(), expected) def test_allow_harmful_protocols(self): renderer = mistune.HTMLRenderer(allow_harmful_protocols=True) md = mistune.Markdown(renderer) result = md('[h](javascript:alert)') expected = '<p><a href="javascript:alert">h</a></p>' self.assertEqual(result.strip(), expected)
<commit_before>import mistune from unittest import TestCase class TestMiscCases(TestCase): def test_none(self): self.assertEqual(mistune.html(None), '') def test_before_parse_hooks(self): def _add_name(md, s, state): state['name'] = 'test' return s, state md = mistune.create_markdown() md.before_parse_hooks.append(_add_name) state = {} md.parse('', state) self.assertEqual(state['name'], 'test') <commit_msg>Add test for allow harmful protocols<commit_after>import mistune from unittest import TestCase class TestMiscCases(TestCase): def test_none(self): self.assertEqual(mistune.html(None), '') def test_before_parse_hooks(self): def _add_name(md, s, state): state['name'] = 'test' return s, state md = mistune.create_markdown() md.before_parse_hooks.append(_add_name) state = {} md.parse('', state) self.assertEqual(state['name'], 'test') def test_escape_html(self): md = mistune.create_markdown(escape=True) result = md('<div>1</div>') expected = '<p>&lt;div&gt;1&lt;/div&gt;</p>' self.assertEqual(result.strip(), expected) result = md('<em>1</em>') expected = '<p>&lt;em&gt;1&lt;/em&gt;</p>' self.assertEqual(result.strip(), expected) def test_emphasis(self): md = mistune.create_markdown(escape=True) result = md('_em_ **strong**') expected = '<p><em>em</em> <strong>strong</strong></p>' self.assertEqual(result.strip(), expected) def test_allow_harmful_protocols(self): renderer = mistune.HTMLRenderer(allow_harmful_protocols=True) md = mistune.Markdown(renderer) result = md('[h](javascript:alert)') expected = '<p><a href="javascript:alert">h</a></p>' self.assertEqual(result.strip(), expected)
2e187ae5ac2b38b0b704d2d24be56d7ebf529231
alignak_backend/__init__.py
alignak_backend/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Alignak REST backend """ # Application manifest VERSION = (0, 4, 1) __application__ = u"Alignak_Backend" __version__ = '.'.join((str(each) for each in VERSION[:4])) __author__ = u"Alignak team" __copyright__ = u"(c) 2015 - %s" % __author__ __license__ = u"GNU Affero General Public License, version 3" __description__ = u"Alignak REST backend" __releasenotes__ = u"""Alignak REST Backend""" __doc_url__ = "https://github.com/Alignak-monitoring-contrib/alignak-backend" # Application manifest manifest = { 'name': __application__, 'version': __version__, 'author': __author__, 'description': __description__, 'copyright': __copyright__, 'license': __license__, 'release': __releasenotes__, 'doc': __doc_url__ }
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Alignak REST backend """ # Application manifest VERSION = (0, 4, 2) __application__ = u"Alignak_Backend" __version__ = '.'.join((str(each) for each in VERSION[:4])) __author__ = u"Alignak team" __copyright__ = u"(c) 2015 - %s" % __author__ __license__ = u"GNU Affero General Public License, version 3" __description__ = u"Alignak REST backend" __releasenotes__ = u"""Alignak REST Backend""" __doc_url__ = "https://github.com/Alignak-monitoring-contrib/alignak-backend" # Application manifest manifest = { 'name': __application__, 'version': __version__, 'author': __author__, 'description': __description__, 'copyright': __copyright__, 'license': __license__, 'release': __releasenotes__, 'doc': __doc_url__ }
Set package version to 0.4.2
Set package version to 0.4.2
Python
agpl-3.0
Alignak-monitoring-contrib/alignak-backend,Alignak-monitoring-contrib/alignak-backend,Alignak-monitoring-contrib/alignak-backend,Alignak-monitoring-contrib/alignak-backend
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Alignak REST backend """ # Application manifest VERSION = (0, 4, 1) __application__ = u"Alignak_Backend" __version__ = '.'.join((str(each) for each in VERSION[:4])) __author__ = u"Alignak team" __copyright__ = u"(c) 2015 - %s" % __author__ __license__ = u"GNU Affero General Public License, version 3" __description__ = u"Alignak REST backend" __releasenotes__ = u"""Alignak REST Backend""" __doc_url__ = "https://github.com/Alignak-monitoring-contrib/alignak-backend" # Application manifest manifest = { 'name': __application__, 'version': __version__, 'author': __author__, 'description': __description__, 'copyright': __copyright__, 'license': __license__, 'release': __releasenotes__, 'doc': __doc_url__ } Set package version to 0.4.2
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Alignak REST backend """ # Application manifest VERSION = (0, 4, 2) __application__ = u"Alignak_Backend" __version__ = '.'.join((str(each) for each in VERSION[:4])) __author__ = u"Alignak team" __copyright__ = u"(c) 2015 - %s" % __author__ __license__ = u"GNU Affero General Public License, version 3" __description__ = u"Alignak REST backend" __releasenotes__ = u"""Alignak REST Backend""" __doc_url__ = "https://github.com/Alignak-monitoring-contrib/alignak-backend" # Application manifest manifest = { 'name': __application__, 'version': __version__, 'author': __author__, 'description': __description__, 'copyright': __copyright__, 'license': __license__, 'release': __releasenotes__, 'doc': __doc_url__ }
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- """ Alignak REST backend """ # Application manifest VERSION = (0, 4, 1) __application__ = u"Alignak_Backend" __version__ = '.'.join((str(each) for each in VERSION[:4])) __author__ = u"Alignak team" __copyright__ = u"(c) 2015 - %s" % __author__ __license__ = u"GNU Affero General Public License, version 3" __description__ = u"Alignak REST backend" __releasenotes__ = u"""Alignak REST Backend""" __doc_url__ = "https://github.com/Alignak-monitoring-contrib/alignak-backend" # Application manifest manifest = { 'name': __application__, 'version': __version__, 'author': __author__, 'description': __description__, 'copyright': __copyright__, 'license': __license__, 'release': __releasenotes__, 'doc': __doc_url__ } <commit_msg>Set package version to 0.4.2<commit_after>
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Alignak REST backend """ # Application manifest VERSION = (0, 4, 2) __application__ = u"Alignak_Backend" __version__ = '.'.join((str(each) for each in VERSION[:4])) __author__ = u"Alignak team" __copyright__ = u"(c) 2015 - %s" % __author__ __license__ = u"GNU Affero General Public License, version 3" __description__ = u"Alignak REST backend" __releasenotes__ = u"""Alignak REST Backend""" __doc_url__ = "https://github.com/Alignak-monitoring-contrib/alignak-backend" # Application manifest manifest = { 'name': __application__, 'version': __version__, 'author': __author__, 'description': __description__, 'copyright': __copyright__, 'license': __license__, 'release': __releasenotes__, 'doc': __doc_url__ }
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Alignak REST backend """ # Application manifest VERSION = (0, 4, 1) __application__ = u"Alignak_Backend" __version__ = '.'.join((str(each) for each in VERSION[:4])) __author__ = u"Alignak team" __copyright__ = u"(c) 2015 - %s" % __author__ __license__ = u"GNU Affero General Public License, version 3" __description__ = u"Alignak REST backend" __releasenotes__ = u"""Alignak REST Backend""" __doc_url__ = "https://github.com/Alignak-monitoring-contrib/alignak-backend" # Application manifest manifest = { 'name': __application__, 'version': __version__, 'author': __author__, 'description': __description__, 'copyright': __copyright__, 'license': __license__, 'release': __releasenotes__, 'doc': __doc_url__ } Set package version to 0.4.2#!/usr/bin/env python # -*- coding: utf-8 -*- """ Alignak REST backend """ # Application manifest VERSION = (0, 4, 2) __application__ = u"Alignak_Backend" __version__ = '.'.join((str(each) for each in VERSION[:4])) __author__ = u"Alignak team" __copyright__ = u"(c) 2015 - %s" % __author__ __license__ = u"GNU Affero General Public License, version 3" __description__ = u"Alignak REST backend" __releasenotes__ = u"""Alignak REST Backend""" __doc_url__ = "https://github.com/Alignak-monitoring-contrib/alignak-backend" # Application manifest manifest = { 'name': __application__, 'version': __version__, 'author': __author__, 'description': __description__, 'copyright': __copyright__, 'license': __license__, 'release': __releasenotes__, 'doc': __doc_url__ }
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- """ Alignak REST backend """ # Application manifest VERSION = (0, 4, 1) __application__ = u"Alignak_Backend" __version__ = '.'.join((str(each) for each in VERSION[:4])) __author__ = u"Alignak team" __copyright__ = u"(c) 2015 - %s" % __author__ __license__ = u"GNU Affero General Public License, version 3" __description__ = u"Alignak REST backend" __releasenotes__ = u"""Alignak REST Backend""" __doc_url__ = "https://github.com/Alignak-monitoring-contrib/alignak-backend" # Application manifest manifest = { 'name': __application__, 'version': __version__, 'author': __author__, 'description': __description__, 'copyright': __copyright__, 'license': __license__, 'release': __releasenotes__, 'doc': __doc_url__ } <commit_msg>Set package version to 0.4.2<commit_after>#!/usr/bin/env python # -*- coding: utf-8 -*- """ Alignak REST backend """ # Application manifest VERSION = (0, 4, 2) __application__ = u"Alignak_Backend" __version__ = '.'.join((str(each) for each in VERSION[:4])) __author__ = u"Alignak team" __copyright__ = u"(c) 2015 - %s" % __author__ __license__ = u"GNU Affero General Public License, version 3" __description__ = u"Alignak REST backend" __releasenotes__ = u"""Alignak REST Backend""" __doc_url__ = "https://github.com/Alignak-monitoring-contrib/alignak-backend" # Application manifest manifest = { 'name': __application__, 'version': __version__, 'author': __author__, 'description': __description__, 'copyright': __copyright__, 'license': __license__, 'release': __releasenotes__, 'doc': __doc_url__ }
ff14a65284603e27cff9628cd8eec0c4cfd8e81d
pale/arguments/url.py
pale/arguments/url.py
from __future__ import absolute_import import string import urlparse from pale.arguments.string import StringArgument from pale.errors import ArgumentError class URLArgument(StringArgument): def validate_url(self, original_string): """Returns the original string if it was valid, raises an argument error if it's not. """ # nipped from stack overflow: http://stackoverflow.com/questions/827557/how-do-you-validate-a-url-with-a-regular-expression-in-python # I preferred this to the thorough regex approach for simplicity and # readability pieces = urlparse.urlparse(original_string) try: assert all([pieces.scheme, pieces.netloc]) valid_chars = set(string.letters + string.digits + ":-_.") assert set(pieces.netloc) <= valid_chars assert pieces.scheme in ['http', 'https'] except AssertionError as e: raise ArgumentError(self.item_name, "The input you've provided is not a valid URL.") return original_string def validate(self, item, item_name): self.item_name = item_name item = super(URLArgument, self).validate(item, item_name) if item is not None: item = self.validate_url(item) return item
from __future__ import absolute_import import string import urlparse from pale.arguments.string import StringArgument from pale.errors import ArgumentError class URLArgument(StringArgument): path_only = False def validate_url(self, original_string): """Returns the original string if it was valid, raises an argument error if it's not. """ # nipped from stack overflow: http://stackoverflow.com/questions/827557/how-do-you-validate-a-url-with-a-regular-expression-in-python # I preferred this to the thorough regex approach for simplicity and # readability pieces = urlparse.urlparse(original_string) try: if self.path_only: assert not any([pieces.scheme, pieces.netloc]) assert pieces.path else: assert all([pieces.scheme, pieces.netloc]) valid_chars = set(string.letters + string.digits + ":-_.") assert set(pieces.netloc) <= valid_chars assert pieces.scheme in ['http', 'https'] except AssertionError as e: raise ArgumentError(self.item_name, "The input you've provided is not a valid URL.") return original_string def validate(self, item, item_name): self.item_name = item_name item = super(URLArgument, self).validate(item, item_name) if item is not None: item = self.validate_url(item) return item
Add path_only support to URLArgument
Add path_only support to URLArgument
Python
mit
Loudr/pale
from __future__ import absolute_import import string import urlparse from pale.arguments.string import StringArgument from pale.errors import ArgumentError class URLArgument(StringArgument): def validate_url(self, original_string): """Returns the original string if it was valid, raises an argument error if it's not. """ # nipped from stack overflow: http://stackoverflow.com/questions/827557/how-do-you-validate-a-url-with-a-regular-expression-in-python # I preferred this to the thorough regex approach for simplicity and # readability pieces = urlparse.urlparse(original_string) try: assert all([pieces.scheme, pieces.netloc]) valid_chars = set(string.letters + string.digits + ":-_.") assert set(pieces.netloc) <= valid_chars assert pieces.scheme in ['http', 'https'] except AssertionError as e: raise ArgumentError(self.item_name, "The input you've provided is not a valid URL.") return original_string def validate(self, item, item_name): self.item_name = item_name item = super(URLArgument, self).validate(item, item_name) if item is not None: item = self.validate_url(item) return item Add path_only support to URLArgument
from __future__ import absolute_import import string import urlparse from pale.arguments.string import StringArgument from pale.errors import ArgumentError class URLArgument(StringArgument): path_only = False def validate_url(self, original_string): """Returns the original string if it was valid, raises an argument error if it's not. """ # nipped from stack overflow: http://stackoverflow.com/questions/827557/how-do-you-validate-a-url-with-a-regular-expression-in-python # I preferred this to the thorough regex approach for simplicity and # readability pieces = urlparse.urlparse(original_string) try: if self.path_only: assert not any([pieces.scheme, pieces.netloc]) assert pieces.path else: assert all([pieces.scheme, pieces.netloc]) valid_chars = set(string.letters + string.digits + ":-_.") assert set(pieces.netloc) <= valid_chars assert pieces.scheme in ['http', 'https'] except AssertionError as e: raise ArgumentError(self.item_name, "The input you've provided is not a valid URL.") return original_string def validate(self, item, item_name): self.item_name = item_name item = super(URLArgument, self).validate(item, item_name) if item is not None: item = self.validate_url(item) return item
<commit_before>from __future__ import absolute_import import string import urlparse from pale.arguments.string import StringArgument from pale.errors import ArgumentError class URLArgument(StringArgument): def validate_url(self, original_string): """Returns the original string if it was valid, raises an argument error if it's not. """ # nipped from stack overflow: http://stackoverflow.com/questions/827557/how-do-you-validate-a-url-with-a-regular-expression-in-python # I preferred this to the thorough regex approach for simplicity and # readability pieces = urlparse.urlparse(original_string) try: assert all([pieces.scheme, pieces.netloc]) valid_chars = set(string.letters + string.digits + ":-_.") assert set(pieces.netloc) <= valid_chars assert pieces.scheme in ['http', 'https'] except AssertionError as e: raise ArgumentError(self.item_name, "The input you've provided is not a valid URL.") return original_string def validate(self, item, item_name): self.item_name = item_name item = super(URLArgument, self).validate(item, item_name) if item is not None: item = self.validate_url(item) return item <commit_msg>Add path_only support to URLArgument<commit_after>
from __future__ import absolute_import import string import urlparse from pale.arguments.string import StringArgument from pale.errors import ArgumentError class URLArgument(StringArgument): path_only = False def validate_url(self, original_string): """Returns the original string if it was valid, raises an argument error if it's not. """ # nipped from stack overflow: http://stackoverflow.com/questions/827557/how-do-you-validate-a-url-with-a-regular-expression-in-python # I preferred this to the thorough regex approach for simplicity and # readability pieces = urlparse.urlparse(original_string) try: if self.path_only: assert not any([pieces.scheme, pieces.netloc]) assert pieces.path else: assert all([pieces.scheme, pieces.netloc]) valid_chars = set(string.letters + string.digits + ":-_.") assert set(pieces.netloc) <= valid_chars assert pieces.scheme in ['http', 'https'] except AssertionError as e: raise ArgumentError(self.item_name, "The input you've provided is not a valid URL.") return original_string def validate(self, item, item_name): self.item_name = item_name item = super(URLArgument, self).validate(item, item_name) if item is not None: item = self.validate_url(item) return item
from __future__ import absolute_import import string import urlparse from pale.arguments.string import StringArgument from pale.errors import ArgumentError class URLArgument(StringArgument): def validate_url(self, original_string): """Returns the original string if it was valid, raises an argument error if it's not. """ # nipped from stack overflow: http://stackoverflow.com/questions/827557/how-do-you-validate-a-url-with-a-regular-expression-in-python # I preferred this to the thorough regex approach for simplicity and # readability pieces = urlparse.urlparse(original_string) try: assert all([pieces.scheme, pieces.netloc]) valid_chars = set(string.letters + string.digits + ":-_.") assert set(pieces.netloc) <= valid_chars assert pieces.scheme in ['http', 'https'] except AssertionError as e: raise ArgumentError(self.item_name, "The input you've provided is not a valid URL.") return original_string def validate(self, item, item_name): self.item_name = item_name item = super(URLArgument, self).validate(item, item_name) if item is not None: item = self.validate_url(item) return item Add path_only support to URLArgumentfrom __future__ import absolute_import import string import urlparse from pale.arguments.string import StringArgument from pale.errors import ArgumentError class URLArgument(StringArgument): path_only = False def validate_url(self, original_string): """Returns the original string if it was valid, raises an argument error if it's not. """ # nipped from stack overflow: http://stackoverflow.com/questions/827557/how-do-you-validate-a-url-with-a-regular-expression-in-python # I preferred this to the thorough regex approach for simplicity and # readability pieces = urlparse.urlparse(original_string) try: if self.path_only: assert not any([pieces.scheme, pieces.netloc]) assert pieces.path else: assert all([pieces.scheme, pieces.netloc]) valid_chars = set(string.letters + string.digits + ":-_.") assert set(pieces.netloc) <= valid_chars assert pieces.scheme in ['http', 'https'] except AssertionError as e: raise ArgumentError(self.item_name, "The input you've provided is not a valid URL.") return original_string def validate(self, item, item_name): self.item_name = item_name item = super(URLArgument, self).validate(item, item_name) if item is not None: item = self.validate_url(item) return item
<commit_before>from __future__ import absolute_import import string import urlparse from pale.arguments.string import StringArgument from pale.errors import ArgumentError class URLArgument(StringArgument): def validate_url(self, original_string): """Returns the original string if it was valid, raises an argument error if it's not. """ # nipped from stack overflow: http://stackoverflow.com/questions/827557/how-do-you-validate-a-url-with-a-regular-expression-in-python # I preferred this to the thorough regex approach for simplicity and # readability pieces = urlparse.urlparse(original_string) try: assert all([pieces.scheme, pieces.netloc]) valid_chars = set(string.letters + string.digits + ":-_.") assert set(pieces.netloc) <= valid_chars assert pieces.scheme in ['http', 'https'] except AssertionError as e: raise ArgumentError(self.item_name, "The input you've provided is not a valid URL.") return original_string def validate(self, item, item_name): self.item_name = item_name item = super(URLArgument, self).validate(item, item_name) if item is not None: item = self.validate_url(item) return item <commit_msg>Add path_only support to URLArgument<commit_after>from __future__ import absolute_import import string import urlparse from pale.arguments.string import StringArgument from pale.errors import ArgumentError class URLArgument(StringArgument): path_only = False def validate_url(self, original_string): """Returns the original string if it was valid, raises an argument error if it's not. """ # nipped from stack overflow: http://stackoverflow.com/questions/827557/how-do-you-validate-a-url-with-a-regular-expression-in-python # I preferred this to the thorough regex approach for simplicity and # readability pieces = urlparse.urlparse(original_string) try: if self.path_only: assert not any([pieces.scheme, pieces.netloc]) assert pieces.path else: assert all([pieces.scheme, pieces.netloc]) valid_chars = set(string.letters + string.digits + ":-_.") assert set(pieces.netloc) <= valid_chars assert pieces.scheme in ['http', 'https'] except AssertionError as e: raise ArgumentError(self.item_name, "The input you've provided is not a valid URL.") return original_string def validate(self, item, item_name): self.item_name = item_name item = super(URLArgument, self).validate(item, item_name) if item is not None: item = self.validate_url(item) return item
213b889a580f58f5dea13fa63c999ca7dac04450
src/extras/__init__.py
src/extras/__init__.py
__author__ = 's7a' # All imports from logger import Logger from sanitizer import Sanitizer from kucera_francis import KuceraFrancis
__author__ = 's7a' # All imports from logger import Logger from sanitizer import Sanitizer from kucera_francis import KuceraFrancis from stemmed_kucera_francis import StemmedKuceraFrancis
Add Stemmed Kucera Francis to extras package
Add Stemmed Kucera Francis to extras package
Python
mit
Somsubhra/Simplify,Somsubhra/Simplify,Somsubhra/Simplify
__author__ = 's7a' # All imports from logger import Logger from sanitizer import Sanitizer from kucera_francis import KuceraFrancisAdd Stemmed Kucera Francis to extras package
__author__ = 's7a' # All imports from logger import Logger from sanitizer import Sanitizer from kucera_francis import KuceraFrancis from stemmed_kucera_francis import StemmedKuceraFrancis
<commit_before>__author__ = 's7a' # All imports from logger import Logger from sanitizer import Sanitizer from kucera_francis import KuceraFrancis<commit_msg>Add Stemmed Kucera Francis to extras package<commit_after>
__author__ = 's7a' # All imports from logger import Logger from sanitizer import Sanitizer from kucera_francis import KuceraFrancis from stemmed_kucera_francis import StemmedKuceraFrancis
__author__ = 's7a' # All imports from logger import Logger from sanitizer import Sanitizer from kucera_francis import KuceraFrancisAdd Stemmed Kucera Francis to extras package__author__ = 's7a' # All imports from logger import Logger from sanitizer import Sanitizer from kucera_francis import KuceraFrancis from stemmed_kucera_francis import StemmedKuceraFrancis
<commit_before>__author__ = 's7a' # All imports from logger import Logger from sanitizer import Sanitizer from kucera_francis import KuceraFrancis<commit_msg>Add Stemmed Kucera Francis to extras package<commit_after>__author__ = 's7a' # All imports from logger import Logger from sanitizer import Sanitizer from kucera_francis import KuceraFrancis from stemmed_kucera_francis import StemmedKuceraFrancis
06349ea257219e8ad1808fa4fd77f34f7371894a
test/test.py
test/test.py
import os, shutil from nose import with_setup from mbutil import mbtiles_to_disk, disk_to_mbtiles def clear_data(): try: shutil.rmtree('test/output') except Exception: pass try: os.path.mkdir('test/output') except Exception: pass @with_setup(clear_data, clear_data) def test_mbtiles_to_disk(): mbtiles_to_disk('test/data/one_tile.mbtiles', 'test/output') assert os.path.exists('test/output/0/0/0.png') assert os.path.exists('test/output/metadata.json') @with_setup(clear_data, clear_data) def test_mbtiles_to_disk_and_back(): mbtiles_to_disk('test/data/one_tile.mbtiles', 'test/output') assert os.path.exists('test/output/0/0/0.png') disk_to_mbtiles('test/output/', 'test/output/one.mbtiles') assert os.path.exists('test/output/one.mbtiles') @with_setup(clear_data, clear_data) def test_utf8grid_mbtiles_to_disk(): mbtiles_to_disk('test/data/utf8grid.mbtiles', 'test/output') assert os.path.exists('test/output/0/0/0.grid.json') assert os.path.exists('test/output/0/0/0.png') assert os.path.exists('test/output/metadata.json')
import os, shutil from nose import with_setup from mbutil import mbtiles_to_disk, disk_to_mbtiles def clear_data(): try: shutil.rmtree('test/output') except Exception: pass @with_setup(clear_data, clear_data) def test_mbtiles_to_disk(): mbtiles_to_disk('test/data/one_tile.mbtiles', 'test/output') assert os.path.exists('test/output/0/0/0.png') assert os.path.exists('test/output/metadata.json') @with_setup(clear_data, clear_data) def test_mbtiles_to_disk_and_back(): mbtiles_to_disk('test/data/one_tile.mbtiles', 'test/output') assert os.path.exists('test/output/0/0/0.png') disk_to_mbtiles('test/output/', 'test/output/one.mbtiles') assert os.path.exists('test/output/one.mbtiles') @with_setup(clear_data, clear_data) def test_utf8grid_mbtiles_to_disk(): mbtiles_to_disk('test/data/utf8grid.mbtiles', 'test/output') assert os.path.exists('test/output/0/0/0.grid.json') assert os.path.exists('test/output/0/0/0.png') assert os.path.exists('test/output/metadata.json')
Remove dead code, os.path.mkdir does not even exist
Remove dead code, os.path.mkdir does not even exist
Python
bsd-3-clause
davvo/mbutil-eniro,mapbox/mbutil,mapbox/mbutil
import os, shutil from nose import with_setup from mbutil import mbtiles_to_disk, disk_to_mbtiles def clear_data(): try: shutil.rmtree('test/output') except Exception: pass try: os.path.mkdir('test/output') except Exception: pass @with_setup(clear_data, clear_data) def test_mbtiles_to_disk(): mbtiles_to_disk('test/data/one_tile.mbtiles', 'test/output') assert os.path.exists('test/output/0/0/0.png') assert os.path.exists('test/output/metadata.json') @with_setup(clear_data, clear_data) def test_mbtiles_to_disk_and_back(): mbtiles_to_disk('test/data/one_tile.mbtiles', 'test/output') assert os.path.exists('test/output/0/0/0.png') disk_to_mbtiles('test/output/', 'test/output/one.mbtiles') assert os.path.exists('test/output/one.mbtiles') @with_setup(clear_data, clear_data) def test_utf8grid_mbtiles_to_disk(): mbtiles_to_disk('test/data/utf8grid.mbtiles', 'test/output') assert os.path.exists('test/output/0/0/0.grid.json') assert os.path.exists('test/output/0/0/0.png') assert os.path.exists('test/output/metadata.json') Remove dead code, os.path.mkdir does not even exist
import os, shutil from nose import with_setup from mbutil import mbtiles_to_disk, disk_to_mbtiles def clear_data(): try: shutil.rmtree('test/output') except Exception: pass @with_setup(clear_data, clear_data) def test_mbtiles_to_disk(): mbtiles_to_disk('test/data/one_tile.mbtiles', 'test/output') assert os.path.exists('test/output/0/0/0.png') assert os.path.exists('test/output/metadata.json') @with_setup(clear_data, clear_data) def test_mbtiles_to_disk_and_back(): mbtiles_to_disk('test/data/one_tile.mbtiles', 'test/output') assert os.path.exists('test/output/0/0/0.png') disk_to_mbtiles('test/output/', 'test/output/one.mbtiles') assert os.path.exists('test/output/one.mbtiles') @with_setup(clear_data, clear_data) def test_utf8grid_mbtiles_to_disk(): mbtiles_to_disk('test/data/utf8grid.mbtiles', 'test/output') assert os.path.exists('test/output/0/0/0.grid.json') assert os.path.exists('test/output/0/0/0.png') assert os.path.exists('test/output/metadata.json')
<commit_before>import os, shutil from nose import with_setup from mbutil import mbtiles_to_disk, disk_to_mbtiles def clear_data(): try: shutil.rmtree('test/output') except Exception: pass try: os.path.mkdir('test/output') except Exception: pass @with_setup(clear_data, clear_data) def test_mbtiles_to_disk(): mbtiles_to_disk('test/data/one_tile.mbtiles', 'test/output') assert os.path.exists('test/output/0/0/0.png') assert os.path.exists('test/output/metadata.json') @with_setup(clear_data, clear_data) def test_mbtiles_to_disk_and_back(): mbtiles_to_disk('test/data/one_tile.mbtiles', 'test/output') assert os.path.exists('test/output/0/0/0.png') disk_to_mbtiles('test/output/', 'test/output/one.mbtiles') assert os.path.exists('test/output/one.mbtiles') @with_setup(clear_data, clear_data) def test_utf8grid_mbtiles_to_disk(): mbtiles_to_disk('test/data/utf8grid.mbtiles', 'test/output') assert os.path.exists('test/output/0/0/0.grid.json') assert os.path.exists('test/output/0/0/0.png') assert os.path.exists('test/output/metadata.json') <commit_msg>Remove dead code, os.path.mkdir does not even exist<commit_after>
import os, shutil from nose import with_setup from mbutil import mbtiles_to_disk, disk_to_mbtiles def clear_data(): try: shutil.rmtree('test/output') except Exception: pass @with_setup(clear_data, clear_data) def test_mbtiles_to_disk(): mbtiles_to_disk('test/data/one_tile.mbtiles', 'test/output') assert os.path.exists('test/output/0/0/0.png') assert os.path.exists('test/output/metadata.json') @with_setup(clear_data, clear_data) def test_mbtiles_to_disk_and_back(): mbtiles_to_disk('test/data/one_tile.mbtiles', 'test/output') assert os.path.exists('test/output/0/0/0.png') disk_to_mbtiles('test/output/', 'test/output/one.mbtiles') assert os.path.exists('test/output/one.mbtiles') @with_setup(clear_data, clear_data) def test_utf8grid_mbtiles_to_disk(): mbtiles_to_disk('test/data/utf8grid.mbtiles', 'test/output') assert os.path.exists('test/output/0/0/0.grid.json') assert os.path.exists('test/output/0/0/0.png') assert os.path.exists('test/output/metadata.json')
import os, shutil from nose import with_setup from mbutil import mbtiles_to_disk, disk_to_mbtiles def clear_data(): try: shutil.rmtree('test/output') except Exception: pass try: os.path.mkdir('test/output') except Exception: pass @with_setup(clear_data, clear_data) def test_mbtiles_to_disk(): mbtiles_to_disk('test/data/one_tile.mbtiles', 'test/output') assert os.path.exists('test/output/0/0/0.png') assert os.path.exists('test/output/metadata.json') @with_setup(clear_data, clear_data) def test_mbtiles_to_disk_and_back(): mbtiles_to_disk('test/data/one_tile.mbtiles', 'test/output') assert os.path.exists('test/output/0/0/0.png') disk_to_mbtiles('test/output/', 'test/output/one.mbtiles') assert os.path.exists('test/output/one.mbtiles') @with_setup(clear_data, clear_data) def test_utf8grid_mbtiles_to_disk(): mbtiles_to_disk('test/data/utf8grid.mbtiles', 'test/output') assert os.path.exists('test/output/0/0/0.grid.json') assert os.path.exists('test/output/0/0/0.png') assert os.path.exists('test/output/metadata.json') Remove dead code, os.path.mkdir does not even existimport os, shutil from nose import with_setup from mbutil import mbtiles_to_disk, disk_to_mbtiles def clear_data(): try: shutil.rmtree('test/output') except Exception: pass @with_setup(clear_data, clear_data) def test_mbtiles_to_disk(): mbtiles_to_disk('test/data/one_tile.mbtiles', 'test/output') assert os.path.exists('test/output/0/0/0.png') assert os.path.exists('test/output/metadata.json') @with_setup(clear_data, clear_data) def test_mbtiles_to_disk_and_back(): mbtiles_to_disk('test/data/one_tile.mbtiles', 'test/output') assert os.path.exists('test/output/0/0/0.png') disk_to_mbtiles('test/output/', 'test/output/one.mbtiles') assert os.path.exists('test/output/one.mbtiles') @with_setup(clear_data, clear_data) def test_utf8grid_mbtiles_to_disk(): mbtiles_to_disk('test/data/utf8grid.mbtiles', 'test/output') assert os.path.exists('test/output/0/0/0.grid.json') assert os.path.exists('test/output/0/0/0.png') assert os.path.exists('test/output/metadata.json')
<commit_before>import os, shutil from nose import with_setup from mbutil import mbtiles_to_disk, disk_to_mbtiles def clear_data(): try: shutil.rmtree('test/output') except Exception: pass try: os.path.mkdir('test/output') except Exception: pass @with_setup(clear_data, clear_data) def test_mbtiles_to_disk(): mbtiles_to_disk('test/data/one_tile.mbtiles', 'test/output') assert os.path.exists('test/output/0/0/0.png') assert os.path.exists('test/output/metadata.json') @with_setup(clear_data, clear_data) def test_mbtiles_to_disk_and_back(): mbtiles_to_disk('test/data/one_tile.mbtiles', 'test/output') assert os.path.exists('test/output/0/0/0.png') disk_to_mbtiles('test/output/', 'test/output/one.mbtiles') assert os.path.exists('test/output/one.mbtiles') @with_setup(clear_data, clear_data) def test_utf8grid_mbtiles_to_disk(): mbtiles_to_disk('test/data/utf8grid.mbtiles', 'test/output') assert os.path.exists('test/output/0/0/0.grid.json') assert os.path.exists('test/output/0/0/0.png') assert os.path.exists('test/output/metadata.json') <commit_msg>Remove dead code, os.path.mkdir does not even exist<commit_after>import os, shutil from nose import with_setup from mbutil import mbtiles_to_disk, disk_to_mbtiles def clear_data(): try: shutil.rmtree('test/output') except Exception: pass @with_setup(clear_data, clear_data) def test_mbtiles_to_disk(): mbtiles_to_disk('test/data/one_tile.mbtiles', 'test/output') assert os.path.exists('test/output/0/0/0.png') assert os.path.exists('test/output/metadata.json') @with_setup(clear_data, clear_data) def test_mbtiles_to_disk_and_back(): mbtiles_to_disk('test/data/one_tile.mbtiles', 'test/output') assert os.path.exists('test/output/0/0/0.png') disk_to_mbtiles('test/output/', 'test/output/one.mbtiles') assert os.path.exists('test/output/one.mbtiles') @with_setup(clear_data, clear_data) def test_utf8grid_mbtiles_to_disk(): mbtiles_to_disk('test/data/utf8grid.mbtiles', 'test/output') assert os.path.exists('test/output/0/0/0.grid.json') assert os.path.exists('test/output/0/0/0.png') assert os.path.exists('test/output/metadata.json')
d91b8f96290498f1e36d64bd797fcea5e43d3df1
apps/events/api.py
apps/events/api.py
from tastypie.resources import ModelResource from models import Event class EventResource(ModelResource): class Meta: queryset = Event.objects.all() resource_name = 'events'
from copy import copy from tastypie.resources import ModelResource from models import Event class EventResource(ModelResource): def alter_list_data_to_serialize(self, request, data): # Rename list data object to 'events'. if isinstance(data, dict): data['events'] = copy(data['objects']) del(data['objects']) return data class Meta: queryset = Event.objects.all() resource_name = 'events'
Rename data objects to 'events'
Rename data objects to 'events'
Python
mit
dotKom/onlineweb4,dotKom/onlineweb4,dotKom/onlineweb4,dotKom/onlineweb4
from tastypie.resources import ModelResource from models import Event class EventResource(ModelResource): class Meta: queryset = Event.objects.all() resource_name = 'events' Rename data objects to 'events'
from copy import copy from tastypie.resources import ModelResource from models import Event class EventResource(ModelResource): def alter_list_data_to_serialize(self, request, data): # Rename list data object to 'events'. if isinstance(data, dict): data['events'] = copy(data['objects']) del(data['objects']) return data class Meta: queryset = Event.objects.all() resource_name = 'events'
<commit_before>from tastypie.resources import ModelResource from models import Event class EventResource(ModelResource): class Meta: queryset = Event.objects.all() resource_name = 'events' <commit_msg>Rename data objects to 'events'<commit_after>
from copy import copy from tastypie.resources import ModelResource from models import Event class EventResource(ModelResource): def alter_list_data_to_serialize(self, request, data): # Rename list data object to 'events'. if isinstance(data, dict): data['events'] = copy(data['objects']) del(data['objects']) return data class Meta: queryset = Event.objects.all() resource_name = 'events'
from tastypie.resources import ModelResource from models import Event class EventResource(ModelResource): class Meta: queryset = Event.objects.all() resource_name = 'events' Rename data objects to 'events'from copy import copy from tastypie.resources import ModelResource from models import Event class EventResource(ModelResource): def alter_list_data_to_serialize(self, request, data): # Rename list data object to 'events'. if isinstance(data, dict): data['events'] = copy(data['objects']) del(data['objects']) return data class Meta: queryset = Event.objects.all() resource_name = 'events'
<commit_before>from tastypie.resources import ModelResource from models import Event class EventResource(ModelResource): class Meta: queryset = Event.objects.all() resource_name = 'events' <commit_msg>Rename data objects to 'events'<commit_after>from copy import copy from tastypie.resources import ModelResource from models import Event class EventResource(ModelResource): def alter_list_data_to_serialize(self, request, data): # Rename list data object to 'events'. if isinstance(data, dict): data['events'] = copy(data['objects']) del(data['objects']) return data class Meta: queryset = Event.objects.all() resource_name = 'events'
0ce7a7b396dd62c7e52e355108f8f037335bc5ca
src/sentry/api/endpoints/project_environments.py
src/sentry/api/endpoints/project_environments.py
from __future__ import absolute_import from rest_framework.response import Response from sentry.api.bases.project import ProjectEndpoint from sentry.api.serializers import serialize from sentry.models import EnvironmentProject environment_visibility_filter_options = { 'all': lambda queryset: queryset, 'hidden': lambda queryset: queryset.filter(is_hidden=True), 'visible': lambda queryset: queryset.exclude(is_hidden=True), } class ProjectEnvironmentsEndpoint(ProjectEndpoint): def get(self, request, project): queryset = EnvironmentProject.objects.filter( project=project, ).select_related('environment').order_by('environment__name') visibility = request.GET.get('visibility', 'visible') if visibility not in environment_visibility_filter_options: return Response({ 'detail': 'Invalid value for \'visibility\', valid values are: {!r}'.format( environment_visibility_filter_options.keys(), ), }, status=400) add_visibility_filters = environment_visibility_filter_options[visibility] queryset = add_visibility_filters(queryset) return Response(serialize(list(queryset), request.user))
from __future__ import absolute_import from rest_framework.response import Response from sentry.api.bases.project import ProjectEndpoint from sentry.api.serializers import serialize from sentry.models import EnvironmentProject environment_visibility_filter_options = { 'all': lambda queryset: queryset, 'hidden': lambda queryset: queryset.filter(is_hidden=True), 'visible': lambda queryset: queryset.exclude(is_hidden=True), } class ProjectEnvironmentsEndpoint(ProjectEndpoint): def get(self, request, project): queryset = EnvironmentProject.objects.filter( project=project, ).exclude( # HACK(mattrobenolt): We don't want to surface the # "No Environment" environment to the UI since it # doesn't really exist. This might very likely change # with new tagstore backend in the future, but until # then, we're hiding it since it causes more problems # than it's worth. environment__name='', ).select_related('environment').order_by('environment__name') visibility = request.GET.get('visibility', 'visible') if visibility not in environment_visibility_filter_options: return Response({ 'detail': 'Invalid value for \'visibility\', valid values are: {!r}'.format( environment_visibility_filter_options.keys(), ), }, status=400) add_visibility_filters = environment_visibility_filter_options[visibility] queryset = add_visibility_filters(queryset) return Response(serialize(list(queryset), request.user))
Hide "No Environment" environment from project environments
api: Hide "No Environment" environment from project environments
Python
bsd-3-clause
beeftornado/sentry,beeftornado/sentry,mvaled/sentry,ifduyue/sentry,ifduyue/sentry,mvaled/sentry,mvaled/sentry,beeftornado/sentry,mvaled/sentry,looker/sentry,looker/sentry,looker/sentry,ifduyue/sentry,ifduyue/sentry,mvaled/sentry,looker/sentry,mvaled/sentry,ifduyue/sentry,looker/sentry
from __future__ import absolute_import from rest_framework.response import Response from sentry.api.bases.project import ProjectEndpoint from sentry.api.serializers import serialize from sentry.models import EnvironmentProject environment_visibility_filter_options = { 'all': lambda queryset: queryset, 'hidden': lambda queryset: queryset.filter(is_hidden=True), 'visible': lambda queryset: queryset.exclude(is_hidden=True), } class ProjectEnvironmentsEndpoint(ProjectEndpoint): def get(self, request, project): queryset = EnvironmentProject.objects.filter( project=project, ).select_related('environment').order_by('environment__name') visibility = request.GET.get('visibility', 'visible') if visibility not in environment_visibility_filter_options: return Response({ 'detail': 'Invalid value for \'visibility\', valid values are: {!r}'.format( environment_visibility_filter_options.keys(), ), }, status=400) add_visibility_filters = environment_visibility_filter_options[visibility] queryset = add_visibility_filters(queryset) return Response(serialize(list(queryset), request.user)) api: Hide "No Environment" environment from project environments
from __future__ import absolute_import from rest_framework.response import Response from sentry.api.bases.project import ProjectEndpoint from sentry.api.serializers import serialize from sentry.models import EnvironmentProject environment_visibility_filter_options = { 'all': lambda queryset: queryset, 'hidden': lambda queryset: queryset.filter(is_hidden=True), 'visible': lambda queryset: queryset.exclude(is_hidden=True), } class ProjectEnvironmentsEndpoint(ProjectEndpoint): def get(self, request, project): queryset = EnvironmentProject.objects.filter( project=project, ).exclude( # HACK(mattrobenolt): We don't want to surface the # "No Environment" environment to the UI since it # doesn't really exist. This might very likely change # with new tagstore backend in the future, but until # then, we're hiding it since it causes more problems # than it's worth. environment__name='', ).select_related('environment').order_by('environment__name') visibility = request.GET.get('visibility', 'visible') if visibility not in environment_visibility_filter_options: return Response({ 'detail': 'Invalid value for \'visibility\', valid values are: {!r}'.format( environment_visibility_filter_options.keys(), ), }, status=400) add_visibility_filters = environment_visibility_filter_options[visibility] queryset = add_visibility_filters(queryset) return Response(serialize(list(queryset), request.user))
<commit_before>from __future__ import absolute_import from rest_framework.response import Response from sentry.api.bases.project import ProjectEndpoint from sentry.api.serializers import serialize from sentry.models import EnvironmentProject environment_visibility_filter_options = { 'all': lambda queryset: queryset, 'hidden': lambda queryset: queryset.filter(is_hidden=True), 'visible': lambda queryset: queryset.exclude(is_hidden=True), } class ProjectEnvironmentsEndpoint(ProjectEndpoint): def get(self, request, project): queryset = EnvironmentProject.objects.filter( project=project, ).select_related('environment').order_by('environment__name') visibility = request.GET.get('visibility', 'visible') if visibility not in environment_visibility_filter_options: return Response({ 'detail': 'Invalid value for \'visibility\', valid values are: {!r}'.format( environment_visibility_filter_options.keys(), ), }, status=400) add_visibility_filters = environment_visibility_filter_options[visibility] queryset = add_visibility_filters(queryset) return Response(serialize(list(queryset), request.user)) <commit_msg>api: Hide "No Environment" environment from project environments<commit_after>
from __future__ import absolute_import from rest_framework.response import Response from sentry.api.bases.project import ProjectEndpoint from sentry.api.serializers import serialize from sentry.models import EnvironmentProject environment_visibility_filter_options = { 'all': lambda queryset: queryset, 'hidden': lambda queryset: queryset.filter(is_hidden=True), 'visible': lambda queryset: queryset.exclude(is_hidden=True), } class ProjectEnvironmentsEndpoint(ProjectEndpoint): def get(self, request, project): queryset = EnvironmentProject.objects.filter( project=project, ).exclude( # HACK(mattrobenolt): We don't want to surface the # "No Environment" environment to the UI since it # doesn't really exist. This might very likely change # with new tagstore backend in the future, but until # then, we're hiding it since it causes more problems # than it's worth. environment__name='', ).select_related('environment').order_by('environment__name') visibility = request.GET.get('visibility', 'visible') if visibility not in environment_visibility_filter_options: return Response({ 'detail': 'Invalid value for \'visibility\', valid values are: {!r}'.format( environment_visibility_filter_options.keys(), ), }, status=400) add_visibility_filters = environment_visibility_filter_options[visibility] queryset = add_visibility_filters(queryset) return Response(serialize(list(queryset), request.user))
from __future__ import absolute_import from rest_framework.response import Response from sentry.api.bases.project import ProjectEndpoint from sentry.api.serializers import serialize from sentry.models import EnvironmentProject environment_visibility_filter_options = { 'all': lambda queryset: queryset, 'hidden': lambda queryset: queryset.filter(is_hidden=True), 'visible': lambda queryset: queryset.exclude(is_hidden=True), } class ProjectEnvironmentsEndpoint(ProjectEndpoint): def get(self, request, project): queryset = EnvironmentProject.objects.filter( project=project, ).select_related('environment').order_by('environment__name') visibility = request.GET.get('visibility', 'visible') if visibility not in environment_visibility_filter_options: return Response({ 'detail': 'Invalid value for \'visibility\', valid values are: {!r}'.format( environment_visibility_filter_options.keys(), ), }, status=400) add_visibility_filters = environment_visibility_filter_options[visibility] queryset = add_visibility_filters(queryset) return Response(serialize(list(queryset), request.user)) api: Hide "No Environment" environment from project environmentsfrom __future__ import absolute_import from rest_framework.response import Response from sentry.api.bases.project import ProjectEndpoint from sentry.api.serializers import serialize from sentry.models import EnvironmentProject environment_visibility_filter_options = { 'all': lambda queryset: queryset, 'hidden': lambda queryset: queryset.filter(is_hidden=True), 'visible': lambda queryset: queryset.exclude(is_hidden=True), } class ProjectEnvironmentsEndpoint(ProjectEndpoint): def get(self, request, project): queryset = EnvironmentProject.objects.filter( project=project, ).exclude( # HACK(mattrobenolt): We don't want to surface the # "No Environment" environment to the UI since it # doesn't really exist. This might very likely change # with new tagstore backend in the future, but until # then, we're hiding it since it causes more problems # than it's worth. environment__name='', ).select_related('environment').order_by('environment__name') visibility = request.GET.get('visibility', 'visible') if visibility not in environment_visibility_filter_options: return Response({ 'detail': 'Invalid value for \'visibility\', valid values are: {!r}'.format( environment_visibility_filter_options.keys(), ), }, status=400) add_visibility_filters = environment_visibility_filter_options[visibility] queryset = add_visibility_filters(queryset) return Response(serialize(list(queryset), request.user))
<commit_before>from __future__ import absolute_import from rest_framework.response import Response from sentry.api.bases.project import ProjectEndpoint from sentry.api.serializers import serialize from sentry.models import EnvironmentProject environment_visibility_filter_options = { 'all': lambda queryset: queryset, 'hidden': lambda queryset: queryset.filter(is_hidden=True), 'visible': lambda queryset: queryset.exclude(is_hidden=True), } class ProjectEnvironmentsEndpoint(ProjectEndpoint): def get(self, request, project): queryset = EnvironmentProject.objects.filter( project=project, ).select_related('environment').order_by('environment__name') visibility = request.GET.get('visibility', 'visible') if visibility not in environment_visibility_filter_options: return Response({ 'detail': 'Invalid value for \'visibility\', valid values are: {!r}'.format( environment_visibility_filter_options.keys(), ), }, status=400) add_visibility_filters = environment_visibility_filter_options[visibility] queryset = add_visibility_filters(queryset) return Response(serialize(list(queryset), request.user)) <commit_msg>api: Hide "No Environment" environment from project environments<commit_after>from __future__ import absolute_import from rest_framework.response import Response from sentry.api.bases.project import ProjectEndpoint from sentry.api.serializers import serialize from sentry.models import EnvironmentProject environment_visibility_filter_options = { 'all': lambda queryset: queryset, 'hidden': lambda queryset: queryset.filter(is_hidden=True), 'visible': lambda queryset: queryset.exclude(is_hidden=True), } class ProjectEnvironmentsEndpoint(ProjectEndpoint): def get(self, request, project): queryset = EnvironmentProject.objects.filter( project=project, ).exclude( # HACK(mattrobenolt): We don't want to surface the # "No Environment" environment to the UI since it # doesn't really exist. This might very likely change # with new tagstore backend in the future, but until # then, we're hiding it since it causes more problems # than it's worth. environment__name='', ).select_related('environment').order_by('environment__name') visibility = request.GET.get('visibility', 'visible') if visibility not in environment_visibility_filter_options: return Response({ 'detail': 'Invalid value for \'visibility\', valid values are: {!r}'.format( environment_visibility_filter_options.keys(), ), }, status=400) add_visibility_filters = environment_visibility_filter_options[visibility] queryset = add_visibility_filters(queryset) return Response(serialize(list(queryset), request.user))
e652e57be097949d06acd06cef813fd28a45afc2
base_report_auto_create_qweb/__manifest__.py
base_report_auto_create_qweb/__manifest__.py
# -*- coding: utf-8 -*- # Authors: See README.RST for Contributors # Copyright 2015-2016 See __openerp__.py for Authors # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Report qweb auto generation", "version": "9.0.1.0.0", "depends": [ "report", ], "external_dependencies": { "python": [ "unidecode", ], }, "author": "OdooMRP team, " "AvanzOSC, " "Serv. Tecnol. Avanzados - Pedro M. Baeza, " "Odoo Community Association (OCA), ", "website": "http://www.odoomrp.com", "license": "AGPL-3", "contributors": [ "Oihane Crucelaegui <oihanecrucelaegi@avanzosc.es>", "Pedro M. Baeza <pedro.baeza@serviciosbaeza.com>", "Ana Juaristi <anajuaristi@avanzosc.es>", ], "category": "Tools", "data": [ "wizard/report_duplicate_view.xml", "views/report_xml_view.xml", ], 'installable': False, }
# -*- coding: utf-8 -*- # Authors: See README.RST for Contributors # Copyright 2015-2016 See __openerp__.py for Authors # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Report qweb auto generation", "version": "9.0.1.0.0", "depends": [ "report", ], "external_dependencies": { "python": [ "unidecode", ], }, "author": "AvanzOSC, " "Tecnativa, " "Odoo Community Association (OCA), ", "website": "https://github.com/OCA/server-tools", "license": "AGPL-3", "contributors": [ "Oihane Crucelaegui <oihanecrucelaegi@avanzosc.es>", "Pedro M. Baeza <pedro.baeza@serviciosbaeza.com>", "Ana Juaristi <anajuaristi@avanzosc.es>", ], "category": "Tools", "data": [ "wizard/report_duplicate_view.xml", "views/report_xml_view.xml", ], 'installable': False, }
Change authors to new ones
base_report_auto_create_qweb: Change authors to new ones
Python
agpl-3.0
ovnicraft/server-tools,ovnicraft/server-tools,ovnicraft/server-tools
# -*- coding: utf-8 -*- # Authors: See README.RST for Contributors # Copyright 2015-2016 See __openerp__.py for Authors # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Report qweb auto generation", "version": "9.0.1.0.0", "depends": [ "report", ], "external_dependencies": { "python": [ "unidecode", ], }, "author": "OdooMRP team, " "AvanzOSC, " "Serv. Tecnol. Avanzados - Pedro M. Baeza, " "Odoo Community Association (OCA), ", "website": "http://www.odoomrp.com", "license": "AGPL-3", "contributors": [ "Oihane Crucelaegui <oihanecrucelaegi@avanzosc.es>", "Pedro M. Baeza <pedro.baeza@serviciosbaeza.com>", "Ana Juaristi <anajuaristi@avanzosc.es>", ], "category": "Tools", "data": [ "wizard/report_duplicate_view.xml", "views/report_xml_view.xml", ], 'installable': False, } base_report_auto_create_qweb: Change authors to new ones
# -*- coding: utf-8 -*- # Authors: See README.RST for Contributors # Copyright 2015-2016 See __openerp__.py for Authors # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Report qweb auto generation", "version": "9.0.1.0.0", "depends": [ "report", ], "external_dependencies": { "python": [ "unidecode", ], }, "author": "AvanzOSC, " "Tecnativa, " "Odoo Community Association (OCA), ", "website": "https://github.com/OCA/server-tools", "license": "AGPL-3", "contributors": [ "Oihane Crucelaegui <oihanecrucelaegi@avanzosc.es>", "Pedro M. Baeza <pedro.baeza@serviciosbaeza.com>", "Ana Juaristi <anajuaristi@avanzosc.es>", ], "category": "Tools", "data": [ "wizard/report_duplicate_view.xml", "views/report_xml_view.xml", ], 'installable': False, }
<commit_before># -*- coding: utf-8 -*- # Authors: See README.RST for Contributors # Copyright 2015-2016 See __openerp__.py for Authors # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Report qweb auto generation", "version": "9.0.1.0.0", "depends": [ "report", ], "external_dependencies": { "python": [ "unidecode", ], }, "author": "OdooMRP team, " "AvanzOSC, " "Serv. Tecnol. Avanzados - Pedro M. Baeza, " "Odoo Community Association (OCA), ", "website": "http://www.odoomrp.com", "license": "AGPL-3", "contributors": [ "Oihane Crucelaegui <oihanecrucelaegi@avanzosc.es>", "Pedro M. Baeza <pedro.baeza@serviciosbaeza.com>", "Ana Juaristi <anajuaristi@avanzosc.es>", ], "category": "Tools", "data": [ "wizard/report_duplicate_view.xml", "views/report_xml_view.xml", ], 'installable': False, } <commit_msg>base_report_auto_create_qweb: Change authors to new ones<commit_after>
# -*- coding: utf-8 -*- # Authors: See README.RST for Contributors # Copyright 2015-2016 See __openerp__.py for Authors # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Report qweb auto generation", "version": "9.0.1.0.0", "depends": [ "report", ], "external_dependencies": { "python": [ "unidecode", ], }, "author": "AvanzOSC, " "Tecnativa, " "Odoo Community Association (OCA), ", "website": "https://github.com/OCA/server-tools", "license": "AGPL-3", "contributors": [ "Oihane Crucelaegui <oihanecrucelaegi@avanzosc.es>", "Pedro M. Baeza <pedro.baeza@serviciosbaeza.com>", "Ana Juaristi <anajuaristi@avanzosc.es>", ], "category": "Tools", "data": [ "wizard/report_duplicate_view.xml", "views/report_xml_view.xml", ], 'installable': False, }
# -*- coding: utf-8 -*- # Authors: See README.RST for Contributors # Copyright 2015-2016 See __openerp__.py for Authors # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Report qweb auto generation", "version": "9.0.1.0.0", "depends": [ "report", ], "external_dependencies": { "python": [ "unidecode", ], }, "author": "OdooMRP team, " "AvanzOSC, " "Serv. Tecnol. Avanzados - Pedro M. Baeza, " "Odoo Community Association (OCA), ", "website": "http://www.odoomrp.com", "license": "AGPL-3", "contributors": [ "Oihane Crucelaegui <oihanecrucelaegi@avanzosc.es>", "Pedro M. Baeza <pedro.baeza@serviciosbaeza.com>", "Ana Juaristi <anajuaristi@avanzosc.es>", ], "category": "Tools", "data": [ "wizard/report_duplicate_view.xml", "views/report_xml_view.xml", ], 'installable': False, } base_report_auto_create_qweb: Change authors to new ones# -*- coding: utf-8 -*- # Authors: See README.RST for Contributors # Copyright 2015-2016 See __openerp__.py for Authors # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Report qweb auto generation", "version": "9.0.1.0.0", "depends": [ "report", ], "external_dependencies": { "python": [ "unidecode", ], }, "author": "AvanzOSC, " "Tecnativa, " "Odoo Community Association (OCA), ", "website": "https://github.com/OCA/server-tools", "license": "AGPL-3", "contributors": [ "Oihane Crucelaegui <oihanecrucelaegi@avanzosc.es>", "Pedro M. Baeza <pedro.baeza@serviciosbaeza.com>", "Ana Juaristi <anajuaristi@avanzosc.es>", ], "category": "Tools", "data": [ "wizard/report_duplicate_view.xml", "views/report_xml_view.xml", ], 'installable': False, }
<commit_before># -*- coding: utf-8 -*- # Authors: See README.RST for Contributors # Copyright 2015-2016 See __openerp__.py for Authors # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Report qweb auto generation", "version": "9.0.1.0.0", "depends": [ "report", ], "external_dependencies": { "python": [ "unidecode", ], }, "author": "OdooMRP team, " "AvanzOSC, " "Serv. Tecnol. Avanzados - Pedro M. Baeza, " "Odoo Community Association (OCA), ", "website": "http://www.odoomrp.com", "license": "AGPL-3", "contributors": [ "Oihane Crucelaegui <oihanecrucelaegi@avanzosc.es>", "Pedro M. Baeza <pedro.baeza@serviciosbaeza.com>", "Ana Juaristi <anajuaristi@avanzosc.es>", ], "category": "Tools", "data": [ "wizard/report_duplicate_view.xml", "views/report_xml_view.xml", ], 'installable': False, } <commit_msg>base_report_auto_create_qweb: Change authors to new ones<commit_after># -*- coding: utf-8 -*- # Authors: See README.RST for Contributors # Copyright 2015-2016 See __openerp__.py for Authors # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Report qweb auto generation", "version": "9.0.1.0.0", "depends": [ "report", ], "external_dependencies": { "python": [ "unidecode", ], }, "author": "AvanzOSC, " "Tecnativa, " "Odoo Community Association (OCA), ", "website": "https://github.com/OCA/server-tools", "license": "AGPL-3", "contributors": [ "Oihane Crucelaegui <oihanecrucelaegi@avanzosc.es>", "Pedro M. Baeza <pedro.baeza@serviciosbaeza.com>", "Ana Juaristi <anajuaristi@avanzosc.es>", ], "category": "Tools", "data": [ "wizard/report_duplicate_view.xml", "views/report_xml_view.xml", ], 'installable': False, }
c94be38207dc9ec0cdf9c3d406954a249ff6e6ac
awsume/awsumepy/lib/saml.py
awsume/awsumepy/lib/saml.py
import base64 import xmltodict import json import colorama from . safe_print import safe_print from . exceptions import SAMLAssertionParseError def parse_assertion(assertion: str) -> list: roles = [] response = xmltodict.parse(base64.b64decode(assertion)) if response.get('saml2p:Response') is not None: attributes = response.get('saml2p:Response', {}).get('saml2:Assertion', {}).get('saml2:AttributeStatement', {}).get('saml2:Attribute', {}) attribute_value_key = 'saml2:AttributeValue' else: attributes = response.get('samlp:Response', {}).get('saml:Assertion', {}).get('saml:AttributeStatement', {}).get('saml:Attribute', {}) attribute_value_key = 'saml:AttributeValue' if not attributes: raise SAMLAssertionParseError() for attribute in [_ for _ in attributes if _.get('@Name', '') == 'https://aws.amazon.com/SAML/Attributes/Role']: for value in attribute[attribute_value_key]: roles.append(value['#text']) return roles
import base64 import xmltodict import json import colorama from . safe_print import safe_print from . exceptions import SAMLAssertionParseError def parse_assertion(assertion: str) -> list: roles = [] response = xmltodict.parse(base64.b64decode(assertion)) if response.get('saml2p:Response') is not None: attributes = response.get('saml2p:Response', {}).get('saml2:Assertion', {}).get('saml2:AttributeStatement', {}).get('saml2:Attribute', {}) attribute_value_key = 'saml2:AttributeValue' else: attributes = response.get('samlp:Response', {}).get('saml:Assertion', {}).get('saml:AttributeStatement', {}).get('saml:Attribute', {}) attribute_value_key = 'saml:AttributeValue' if not attributes: raise SAMLAssertionParseError() for attribute in [_ for _ in attributes if _.get('@Name', '') == 'https://aws.amazon.com/SAML/Attributes/Role']: if isinstance(attribute[attribute_value_key], list): for value in attribute[attribute_value_key]: roles.append(value['#text']) else: value = attribute[attribute_value_key] roles.append(value['#text']) return roles
Handle having a single role in the SAML assertion
Handle having a single role in the SAML assertion
Python
mit
trek10inc/awsume,trek10inc/awsume
import base64 import xmltodict import json import colorama from . safe_print import safe_print from . exceptions import SAMLAssertionParseError def parse_assertion(assertion: str) -> list: roles = [] response = xmltodict.parse(base64.b64decode(assertion)) if response.get('saml2p:Response') is not None: attributes = response.get('saml2p:Response', {}).get('saml2:Assertion', {}).get('saml2:AttributeStatement', {}).get('saml2:Attribute', {}) attribute_value_key = 'saml2:AttributeValue' else: attributes = response.get('samlp:Response', {}).get('saml:Assertion', {}).get('saml:AttributeStatement', {}).get('saml:Attribute', {}) attribute_value_key = 'saml:AttributeValue' if not attributes: raise SAMLAssertionParseError() for attribute in [_ for _ in attributes if _.get('@Name', '') == 'https://aws.amazon.com/SAML/Attributes/Role']: for value in attribute[attribute_value_key]: roles.append(value['#text']) return roles Handle having a single role in the SAML assertion
import base64 import xmltodict import json import colorama from . safe_print import safe_print from . exceptions import SAMLAssertionParseError def parse_assertion(assertion: str) -> list: roles = [] response = xmltodict.parse(base64.b64decode(assertion)) if response.get('saml2p:Response') is not None: attributes = response.get('saml2p:Response', {}).get('saml2:Assertion', {}).get('saml2:AttributeStatement', {}).get('saml2:Attribute', {}) attribute_value_key = 'saml2:AttributeValue' else: attributes = response.get('samlp:Response', {}).get('saml:Assertion', {}).get('saml:AttributeStatement', {}).get('saml:Attribute', {}) attribute_value_key = 'saml:AttributeValue' if not attributes: raise SAMLAssertionParseError() for attribute in [_ for _ in attributes if _.get('@Name', '') == 'https://aws.amazon.com/SAML/Attributes/Role']: if isinstance(attribute[attribute_value_key], list): for value in attribute[attribute_value_key]: roles.append(value['#text']) else: value = attribute[attribute_value_key] roles.append(value['#text']) return roles
<commit_before>import base64 import xmltodict import json import colorama from . safe_print import safe_print from . exceptions import SAMLAssertionParseError def parse_assertion(assertion: str) -> list: roles = [] response = xmltodict.parse(base64.b64decode(assertion)) if response.get('saml2p:Response') is not None: attributes = response.get('saml2p:Response', {}).get('saml2:Assertion', {}).get('saml2:AttributeStatement', {}).get('saml2:Attribute', {}) attribute_value_key = 'saml2:AttributeValue' else: attributes = response.get('samlp:Response', {}).get('saml:Assertion', {}).get('saml:AttributeStatement', {}).get('saml:Attribute', {}) attribute_value_key = 'saml:AttributeValue' if not attributes: raise SAMLAssertionParseError() for attribute in [_ for _ in attributes if _.get('@Name', '') == 'https://aws.amazon.com/SAML/Attributes/Role']: for value in attribute[attribute_value_key]: roles.append(value['#text']) return roles <commit_msg>Handle having a single role in the SAML assertion<commit_after>
import base64 import xmltodict import json import colorama from . safe_print import safe_print from . exceptions import SAMLAssertionParseError def parse_assertion(assertion: str) -> list: roles = [] response = xmltodict.parse(base64.b64decode(assertion)) if response.get('saml2p:Response') is not None: attributes = response.get('saml2p:Response', {}).get('saml2:Assertion', {}).get('saml2:AttributeStatement', {}).get('saml2:Attribute', {}) attribute_value_key = 'saml2:AttributeValue' else: attributes = response.get('samlp:Response', {}).get('saml:Assertion', {}).get('saml:AttributeStatement', {}).get('saml:Attribute', {}) attribute_value_key = 'saml:AttributeValue' if not attributes: raise SAMLAssertionParseError() for attribute in [_ for _ in attributes if _.get('@Name', '') == 'https://aws.amazon.com/SAML/Attributes/Role']: if isinstance(attribute[attribute_value_key], list): for value in attribute[attribute_value_key]: roles.append(value['#text']) else: value = attribute[attribute_value_key] roles.append(value['#text']) return roles
import base64 import xmltodict import json import colorama from . safe_print import safe_print from . exceptions import SAMLAssertionParseError def parse_assertion(assertion: str) -> list: roles = [] response = xmltodict.parse(base64.b64decode(assertion)) if response.get('saml2p:Response') is not None: attributes = response.get('saml2p:Response', {}).get('saml2:Assertion', {}).get('saml2:AttributeStatement', {}).get('saml2:Attribute', {}) attribute_value_key = 'saml2:AttributeValue' else: attributes = response.get('samlp:Response', {}).get('saml:Assertion', {}).get('saml:AttributeStatement', {}).get('saml:Attribute', {}) attribute_value_key = 'saml:AttributeValue' if not attributes: raise SAMLAssertionParseError() for attribute in [_ for _ in attributes if _.get('@Name', '') == 'https://aws.amazon.com/SAML/Attributes/Role']: for value in attribute[attribute_value_key]: roles.append(value['#text']) return roles Handle having a single role in the SAML assertionimport base64 import xmltodict import json import colorama from . safe_print import safe_print from . exceptions import SAMLAssertionParseError def parse_assertion(assertion: str) -> list: roles = [] response = xmltodict.parse(base64.b64decode(assertion)) if response.get('saml2p:Response') is not None: attributes = response.get('saml2p:Response', {}).get('saml2:Assertion', {}).get('saml2:AttributeStatement', {}).get('saml2:Attribute', {}) attribute_value_key = 'saml2:AttributeValue' else: attributes = response.get('samlp:Response', {}).get('saml:Assertion', {}).get('saml:AttributeStatement', {}).get('saml:Attribute', {}) attribute_value_key = 'saml:AttributeValue' if not attributes: raise SAMLAssertionParseError() for attribute in [_ for _ in attributes if _.get('@Name', '') == 'https://aws.amazon.com/SAML/Attributes/Role']: if isinstance(attribute[attribute_value_key], list): for value in attribute[attribute_value_key]: roles.append(value['#text']) else: value = attribute[attribute_value_key] roles.append(value['#text']) return roles
<commit_before>import base64 import xmltodict import json import colorama from . safe_print import safe_print from . exceptions import SAMLAssertionParseError def parse_assertion(assertion: str) -> list: roles = [] response = xmltodict.parse(base64.b64decode(assertion)) if response.get('saml2p:Response') is not None: attributes = response.get('saml2p:Response', {}).get('saml2:Assertion', {}).get('saml2:AttributeStatement', {}).get('saml2:Attribute', {}) attribute_value_key = 'saml2:AttributeValue' else: attributes = response.get('samlp:Response', {}).get('saml:Assertion', {}).get('saml:AttributeStatement', {}).get('saml:Attribute', {}) attribute_value_key = 'saml:AttributeValue' if not attributes: raise SAMLAssertionParseError() for attribute in [_ for _ in attributes if _.get('@Name', '') == 'https://aws.amazon.com/SAML/Attributes/Role']: for value in attribute[attribute_value_key]: roles.append(value['#text']) return roles <commit_msg>Handle having a single role in the SAML assertion<commit_after>import base64 import xmltodict import json import colorama from . safe_print import safe_print from . exceptions import SAMLAssertionParseError def parse_assertion(assertion: str) -> list: roles = [] response = xmltodict.parse(base64.b64decode(assertion)) if response.get('saml2p:Response') is not None: attributes = response.get('saml2p:Response', {}).get('saml2:Assertion', {}).get('saml2:AttributeStatement', {}).get('saml2:Attribute', {}) attribute_value_key = 'saml2:AttributeValue' else: attributes = response.get('samlp:Response', {}).get('saml:Assertion', {}).get('saml:AttributeStatement', {}).get('saml:Attribute', {}) attribute_value_key = 'saml:AttributeValue' if not attributes: raise SAMLAssertionParseError() for attribute in [_ for _ in attributes if _.get('@Name', '') == 'https://aws.amazon.com/SAML/Attributes/Role']: if isinstance(attribute[attribute_value_key], list): for value in attribute[attribute_value_key]: roles.append(value['#text']) else: value = attribute[attribute_value_key] roles.append(value['#text']) return roles
02bacade9f9680662196e09b9d95086113e03da9
website/settings/local-travis.py
website/settings/local-travis.py
# -*- coding: utf-8 -*- '''Example settings/local.py file. These settings override what's in website/settings/defaults.py NOTE: local.py will not be added to source control. ''' from . import defaults DB_PORT = 27017 DEV_MODE = True DEBUG_MODE = True # Sets app to debug mode, turns off template caching, etc. SEARCH_ENGINE = 'elastic' USE_EMAIL = False USE_CELERY = False USE_GNUPG = False # Email MAIL_SERVER = 'localhost:1025' # For local testing MAIL_USERNAME = 'osf-smtp' MAIL_PASSWORD = 'CHANGEME' # Session COOKIE_NAME = 'osf' SECRET_KEY = "CHANGEME" ##### Celery ##### ## Default RabbitMQ broker BROKER_URL = 'amqp://' # Default RabbitMQ backend CELERY_RESULT_BACKEND = 'amqp://' USE_CDN_FOR_CLIENT_LIBS = False SENTRY_DSN = None
# -*- coding: utf-8 -*- '''Example settings/local.py file. These settings override what's in website/settings/defaults.py NOTE: local.py will not be added to source control. ''' from . import defaults DB_PORT = 27017 DEV_MODE = True DEBUG_MODE = True # Sets app to debug mode, turns off template caching, etc. SEARCH_ENGINE = 'elastic' USE_EMAIL = False USE_CELERY = False USE_GNUPG = False # Email MAIL_SERVER = 'localhost:1025' # For local testing MAIL_USERNAME = 'osf-smtp' MAIL_PASSWORD = 'CHANGEME' # Session COOKIE_NAME = 'osf' SECRET_KEY = "CHANGEME" ##### Celery ##### ## Default RabbitMQ broker BROKER_URL = 'amqp://' # Default RabbitMQ backend CELERY_RESULT_BACKEND = 'amqp://' USE_CDN_FOR_CLIENT_LIBS = False SENTRY_DSN = None TEST_DB_NAME = DB_NAME = 'osf_test'
Add default test db name to travis local.py
Add default test db name to travis local.py
Python
apache-2.0
erinspace/osf.io,zachjanicki/osf.io,kch8qx/osf.io,brianjgeiger/osf.io,icereval/osf.io,brandonPurvis/osf.io,alexschiller/osf.io,felliott/osf.io,mfraezz/osf.io,billyhunt/osf.io,Johnetordoff/osf.io,caneruguz/osf.io,GageGaskins/osf.io,chennan47/osf.io,pattisdr/osf.io,Johnetordoff/osf.io,leb2dg/osf.io,crcresearch/osf.io,alexschiller/osf.io,pattisdr/osf.io,CenterForOpenScience/osf.io,chrisseto/osf.io,laurenrevere/osf.io,leb2dg/osf.io,cslzchen/osf.io,caneruguz/osf.io,brianjgeiger/osf.io,DanielSBrown/osf.io,GageGaskins/osf.io,hmoco/osf.io,jnayak1/osf.io,baylee-d/osf.io,cwisecarver/osf.io,monikagrabowska/osf.io,zamattiac/osf.io,brandonPurvis/osf.io,zamattiac/osf.io,leb2dg/osf.io,rdhyee/osf.io,GageGaskins/osf.io,mattclark/osf.io,chrisseto/osf.io,mluo613/osf.io,KAsante95/osf.io,caseyrollins/osf.io,SSJohns/osf.io,sloria/osf.io,laurenrevere/osf.io,monikagrabowska/osf.io,KAsante95/osf.io,HalcyonChimera/osf.io,TomBaxter/osf.io,icereval/osf.io,adlius/osf.io,samchrisinger/osf.io,samchrisinger/osf.io,rdhyee/osf.io,crcresearch/osf.io,mluke93/osf.io,binoculars/osf.io,Nesiehr/osf.io,billyhunt/osf.io,asanfilippo7/osf.io,abought/osf.io,erinspace/osf.io,hmoco/osf.io,RomanZWang/osf.io,TomBaxter/osf.io,adlius/osf.io,aaxelb/osf.io,cwisecarver/osf.io,asanfilippo7/osf.io,billyhunt/osf.io,kch8qx/osf.io,mfraezz/osf.io,adlius/osf.io,mluo613/osf.io,TomHeatwole/osf.io,mfraezz/osf.io,monikagrabowska/osf.io,rdhyee/osf.io,acshi/osf.io,TomHeatwole/osf.io,caneruguz/osf.io,CenterForOpenScience/osf.io,felliott/osf.io,asanfilippo7/osf.io,cwisecarver/osf.io,SSJohns/osf.io,zamattiac/osf.io,SSJohns/osf.io,kwierman/osf.io,CenterForOpenScience/osf.io,caseyrollins/osf.io,SSJohns/osf.io,acshi/osf.io,mattclark/osf.io,wearpants/osf.io,KAsante95/osf.io,cslzchen/osf.io,rdhyee/osf.io,RomanZWang/osf.io,hmoco/osf.io,alexschiller/osf.io,doublebits/osf.io,emetsger/osf.io,felliott/osf.io,TomHeatwole/osf.io,samchrisinger/osf.io,Johnetordoff/osf.io,sloria/osf.io,mluo613/osf.io,jnayak1/osf.io,pattisdr/osf.io,abought/osf.io,laurenrevere/osf.io,HalcyonChimera/osf.io,TomBaxter/osf.io,zachjanicki/osf.io,DanielSBrown/osf.io,aaxelb/osf.io,icereval/osf.io,kwierman/osf.io,leb2dg/osf.io,jnayak1/osf.io,cwisecarver/osf.io,wearpants/osf.io,Johnetordoff/osf.io,aaxelb/osf.io,kwierman/osf.io,saradbowman/osf.io,KAsante95/osf.io,zachjanicki/osf.io,chrisseto/osf.io,chennan47/osf.io,felliott/osf.io,Nesiehr/osf.io,Nesiehr/osf.io,mattclark/osf.io,monikagrabowska/osf.io,baylee-d/osf.io,baylee-d/osf.io,Nesiehr/osf.io,RomanZWang/osf.io,asanfilippo7/osf.io,mluke93/osf.io,brianjgeiger/osf.io,crcresearch/osf.io,cslzchen/osf.io,kwierman/osf.io,brandonPurvis/osf.io,jnayak1/osf.io,mluke93/osf.io,DanielSBrown/osf.io,mluo613/osf.io,chrisseto/osf.io,amyshi188/osf.io,acshi/osf.io,amyshi188/osf.io,RomanZWang/osf.io,emetsger/osf.io,billyhunt/osf.io,kch8qx/osf.io,doublebits/osf.io,amyshi188/osf.io,kch8qx/osf.io,emetsger/osf.io,hmoco/osf.io,abought/osf.io,DanielSBrown/osf.io,emetsger/osf.io,brandonPurvis/osf.io,mluke93/osf.io,samchrisinger/osf.io,HalcyonChimera/osf.io,amyshi188/osf.io,HalcyonChimera/osf.io,billyhunt/osf.io,binoculars/osf.io,KAsante95/osf.io,monikagrabowska/osf.io,GageGaskins/osf.io,zamattiac/osf.io,cslzchen/osf.io,alexschiller/osf.io,kch8qx/osf.io,brandonPurvis/osf.io,adlius/osf.io,zachjanicki/osf.io,doublebits/osf.io,CenterForOpenScience/osf.io,mluo613/osf.io,erinspace/osf.io,acshi/osf.io,chennan47/osf.io,wearpants/osf.io,aaxelb/osf.io,brianjgeiger/osf.io,doublebits/osf.io,caneruguz/osf.io,doublebits/osf.io,GageGaskins/osf.io,saradbowman/osf.io,caseyrollins/osf.io,wearpants/osf.io,acshi/osf.io,TomHeatwole/osf.io,RomanZWang/osf.io,binoculars/osf.io,abought/osf.io,mfraezz/osf.io,sloria/osf.io,alexschiller/osf.io
# -*- coding: utf-8 -*- '''Example settings/local.py file. These settings override what's in website/settings/defaults.py NOTE: local.py will not be added to source control. ''' from . import defaults DB_PORT = 27017 DEV_MODE = True DEBUG_MODE = True # Sets app to debug mode, turns off template caching, etc. SEARCH_ENGINE = 'elastic' USE_EMAIL = False USE_CELERY = False USE_GNUPG = False # Email MAIL_SERVER = 'localhost:1025' # For local testing MAIL_USERNAME = 'osf-smtp' MAIL_PASSWORD = 'CHANGEME' # Session COOKIE_NAME = 'osf' SECRET_KEY = "CHANGEME" ##### Celery ##### ## Default RabbitMQ broker BROKER_URL = 'amqp://' # Default RabbitMQ backend CELERY_RESULT_BACKEND = 'amqp://' USE_CDN_FOR_CLIENT_LIBS = False SENTRY_DSN = None Add default test db name to travis local.py
# -*- coding: utf-8 -*- '''Example settings/local.py file. These settings override what's in website/settings/defaults.py NOTE: local.py will not be added to source control. ''' from . import defaults DB_PORT = 27017 DEV_MODE = True DEBUG_MODE = True # Sets app to debug mode, turns off template caching, etc. SEARCH_ENGINE = 'elastic' USE_EMAIL = False USE_CELERY = False USE_GNUPG = False # Email MAIL_SERVER = 'localhost:1025' # For local testing MAIL_USERNAME = 'osf-smtp' MAIL_PASSWORD = 'CHANGEME' # Session COOKIE_NAME = 'osf' SECRET_KEY = "CHANGEME" ##### Celery ##### ## Default RabbitMQ broker BROKER_URL = 'amqp://' # Default RabbitMQ backend CELERY_RESULT_BACKEND = 'amqp://' USE_CDN_FOR_CLIENT_LIBS = False SENTRY_DSN = None TEST_DB_NAME = DB_NAME = 'osf_test'
<commit_before># -*- coding: utf-8 -*- '''Example settings/local.py file. These settings override what's in website/settings/defaults.py NOTE: local.py will not be added to source control. ''' from . import defaults DB_PORT = 27017 DEV_MODE = True DEBUG_MODE = True # Sets app to debug mode, turns off template caching, etc. SEARCH_ENGINE = 'elastic' USE_EMAIL = False USE_CELERY = False USE_GNUPG = False # Email MAIL_SERVER = 'localhost:1025' # For local testing MAIL_USERNAME = 'osf-smtp' MAIL_PASSWORD = 'CHANGEME' # Session COOKIE_NAME = 'osf' SECRET_KEY = "CHANGEME" ##### Celery ##### ## Default RabbitMQ broker BROKER_URL = 'amqp://' # Default RabbitMQ backend CELERY_RESULT_BACKEND = 'amqp://' USE_CDN_FOR_CLIENT_LIBS = False SENTRY_DSN = None <commit_msg>Add default test db name to travis local.py<commit_after>
# -*- coding: utf-8 -*- '''Example settings/local.py file. These settings override what's in website/settings/defaults.py NOTE: local.py will not be added to source control. ''' from . import defaults DB_PORT = 27017 DEV_MODE = True DEBUG_MODE = True # Sets app to debug mode, turns off template caching, etc. SEARCH_ENGINE = 'elastic' USE_EMAIL = False USE_CELERY = False USE_GNUPG = False # Email MAIL_SERVER = 'localhost:1025' # For local testing MAIL_USERNAME = 'osf-smtp' MAIL_PASSWORD = 'CHANGEME' # Session COOKIE_NAME = 'osf' SECRET_KEY = "CHANGEME" ##### Celery ##### ## Default RabbitMQ broker BROKER_URL = 'amqp://' # Default RabbitMQ backend CELERY_RESULT_BACKEND = 'amqp://' USE_CDN_FOR_CLIENT_LIBS = False SENTRY_DSN = None TEST_DB_NAME = DB_NAME = 'osf_test'
# -*- coding: utf-8 -*- '''Example settings/local.py file. These settings override what's in website/settings/defaults.py NOTE: local.py will not be added to source control. ''' from . import defaults DB_PORT = 27017 DEV_MODE = True DEBUG_MODE = True # Sets app to debug mode, turns off template caching, etc. SEARCH_ENGINE = 'elastic' USE_EMAIL = False USE_CELERY = False USE_GNUPG = False # Email MAIL_SERVER = 'localhost:1025' # For local testing MAIL_USERNAME = 'osf-smtp' MAIL_PASSWORD = 'CHANGEME' # Session COOKIE_NAME = 'osf' SECRET_KEY = "CHANGEME" ##### Celery ##### ## Default RabbitMQ broker BROKER_URL = 'amqp://' # Default RabbitMQ backend CELERY_RESULT_BACKEND = 'amqp://' USE_CDN_FOR_CLIENT_LIBS = False SENTRY_DSN = None Add default test db name to travis local.py# -*- coding: utf-8 -*- '''Example settings/local.py file. These settings override what's in website/settings/defaults.py NOTE: local.py will not be added to source control. ''' from . import defaults DB_PORT = 27017 DEV_MODE = True DEBUG_MODE = True # Sets app to debug mode, turns off template caching, etc. SEARCH_ENGINE = 'elastic' USE_EMAIL = False USE_CELERY = False USE_GNUPG = False # Email MAIL_SERVER = 'localhost:1025' # For local testing MAIL_USERNAME = 'osf-smtp' MAIL_PASSWORD = 'CHANGEME' # Session COOKIE_NAME = 'osf' SECRET_KEY = "CHANGEME" ##### Celery ##### ## Default RabbitMQ broker BROKER_URL = 'amqp://' # Default RabbitMQ backend CELERY_RESULT_BACKEND = 'amqp://' USE_CDN_FOR_CLIENT_LIBS = False SENTRY_DSN = None TEST_DB_NAME = DB_NAME = 'osf_test'
<commit_before># -*- coding: utf-8 -*- '''Example settings/local.py file. These settings override what's in website/settings/defaults.py NOTE: local.py will not be added to source control. ''' from . import defaults DB_PORT = 27017 DEV_MODE = True DEBUG_MODE = True # Sets app to debug mode, turns off template caching, etc. SEARCH_ENGINE = 'elastic' USE_EMAIL = False USE_CELERY = False USE_GNUPG = False # Email MAIL_SERVER = 'localhost:1025' # For local testing MAIL_USERNAME = 'osf-smtp' MAIL_PASSWORD = 'CHANGEME' # Session COOKIE_NAME = 'osf' SECRET_KEY = "CHANGEME" ##### Celery ##### ## Default RabbitMQ broker BROKER_URL = 'amqp://' # Default RabbitMQ backend CELERY_RESULT_BACKEND = 'amqp://' USE_CDN_FOR_CLIENT_LIBS = False SENTRY_DSN = None <commit_msg>Add default test db name to travis local.py<commit_after># -*- coding: utf-8 -*- '''Example settings/local.py file. These settings override what's in website/settings/defaults.py NOTE: local.py will not be added to source control. ''' from . import defaults DB_PORT = 27017 DEV_MODE = True DEBUG_MODE = True # Sets app to debug mode, turns off template caching, etc. SEARCH_ENGINE = 'elastic' USE_EMAIL = False USE_CELERY = False USE_GNUPG = False # Email MAIL_SERVER = 'localhost:1025' # For local testing MAIL_USERNAME = 'osf-smtp' MAIL_PASSWORD = 'CHANGEME' # Session COOKIE_NAME = 'osf' SECRET_KEY = "CHANGEME" ##### Celery ##### ## Default RabbitMQ broker BROKER_URL = 'amqp://' # Default RabbitMQ backend CELERY_RESULT_BACKEND = 'amqp://' USE_CDN_FOR_CLIENT_LIBS = False SENTRY_DSN = None TEST_DB_NAME = DB_NAME = 'osf_test'
bf4c26907522a04ec77274d8f862e853a64f7d6a
avalon/__main__.py
avalon/__main__.py
import argparse from . import pipeline if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("--creator", action="store_true", help="Launch Instance Creator in standalone mode") parser.add_argument("--loader", action="store_true", help="Launch Asset Loader in standalone mode") parser.add_argument("--manager", action="store_true", help="Launch Manager in standalone mode") parser.add_argument("--projectmanager", action="store_true", help="Launch Manager in standalone mode") parser.add_argument("--root", help="Absolute path to root directory of assets") args, unknown = parser.parse_known_args() host = pipeline.debug_host() pipeline.register_host(host) if args.creator: from .tools import creator creator.show(debug=True) elif args.loader: from .tools import loader loader.show(debug=True) elif args.manager: from .tools import sceneinventory sceneinventory.show(debug=True) elif args.projectmanager: from .tools import projectmanager projectmanager.cli(unknown)
import argparse from . import pipeline if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("--creator", action="store_true", help="Launch Instance Creator in standalone mode") parser.add_argument("--loader", action="store_true", help="Launch Asset Loader in standalone mode") parser.add_argument("--sceneinventory", action="store_true", help="Launch Scene Inventory in standalone mode") parser.add_argument("--projectmanager", action="store_true", help="Launch Manager in standalone mode") parser.add_argument("--root", help="Absolute path to root directory of assets") args, unknown = parser.parse_known_args() host = pipeline.debug_host() pipeline.register_host(host) if args.creator: from .tools import creator creator.show(debug=True) elif args.loader: from .tools import loader loader.show(debug=True) elif args.sceneinventory: from .tools import sceneinventory sceneinventory.show(debug=True) elif args.projectmanager: from .tools import projectmanager projectmanager.cli(unknown)
Refactor manager argument to sceneinventory
Refactor manager argument to sceneinventory
Python
mit
mindbender-studio/core,getavalon/core,mindbender-studio/core,getavalon/core
import argparse from . import pipeline if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("--creator", action="store_true", help="Launch Instance Creator in standalone mode") parser.add_argument("--loader", action="store_true", help="Launch Asset Loader in standalone mode") parser.add_argument("--manager", action="store_true", help="Launch Manager in standalone mode") parser.add_argument("--projectmanager", action="store_true", help="Launch Manager in standalone mode") parser.add_argument("--root", help="Absolute path to root directory of assets") args, unknown = parser.parse_known_args() host = pipeline.debug_host() pipeline.register_host(host) if args.creator: from .tools import creator creator.show(debug=True) elif args.loader: from .tools import loader loader.show(debug=True) elif args.manager: from .tools import sceneinventory sceneinventory.show(debug=True) elif args.projectmanager: from .tools import projectmanager projectmanager.cli(unknown) Refactor manager argument to sceneinventory
import argparse from . import pipeline if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("--creator", action="store_true", help="Launch Instance Creator in standalone mode") parser.add_argument("--loader", action="store_true", help="Launch Asset Loader in standalone mode") parser.add_argument("--sceneinventory", action="store_true", help="Launch Scene Inventory in standalone mode") parser.add_argument("--projectmanager", action="store_true", help="Launch Manager in standalone mode") parser.add_argument("--root", help="Absolute path to root directory of assets") args, unknown = parser.parse_known_args() host = pipeline.debug_host() pipeline.register_host(host) if args.creator: from .tools import creator creator.show(debug=True) elif args.loader: from .tools import loader loader.show(debug=True) elif args.sceneinventory: from .tools import sceneinventory sceneinventory.show(debug=True) elif args.projectmanager: from .tools import projectmanager projectmanager.cli(unknown)
<commit_before>import argparse from . import pipeline if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("--creator", action="store_true", help="Launch Instance Creator in standalone mode") parser.add_argument("--loader", action="store_true", help="Launch Asset Loader in standalone mode") parser.add_argument("--manager", action="store_true", help="Launch Manager in standalone mode") parser.add_argument("--projectmanager", action="store_true", help="Launch Manager in standalone mode") parser.add_argument("--root", help="Absolute path to root directory of assets") args, unknown = parser.parse_known_args() host = pipeline.debug_host() pipeline.register_host(host) if args.creator: from .tools import creator creator.show(debug=True) elif args.loader: from .tools import loader loader.show(debug=True) elif args.manager: from .tools import sceneinventory sceneinventory.show(debug=True) elif args.projectmanager: from .tools import projectmanager projectmanager.cli(unknown) <commit_msg>Refactor manager argument to sceneinventory<commit_after>
import argparse from . import pipeline if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("--creator", action="store_true", help="Launch Instance Creator in standalone mode") parser.add_argument("--loader", action="store_true", help="Launch Asset Loader in standalone mode") parser.add_argument("--sceneinventory", action="store_true", help="Launch Scene Inventory in standalone mode") parser.add_argument("--projectmanager", action="store_true", help="Launch Manager in standalone mode") parser.add_argument("--root", help="Absolute path to root directory of assets") args, unknown = parser.parse_known_args() host = pipeline.debug_host() pipeline.register_host(host) if args.creator: from .tools import creator creator.show(debug=True) elif args.loader: from .tools import loader loader.show(debug=True) elif args.sceneinventory: from .tools import sceneinventory sceneinventory.show(debug=True) elif args.projectmanager: from .tools import projectmanager projectmanager.cli(unknown)
import argparse from . import pipeline if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("--creator", action="store_true", help="Launch Instance Creator in standalone mode") parser.add_argument("--loader", action="store_true", help="Launch Asset Loader in standalone mode") parser.add_argument("--manager", action="store_true", help="Launch Manager in standalone mode") parser.add_argument("--projectmanager", action="store_true", help="Launch Manager in standalone mode") parser.add_argument("--root", help="Absolute path to root directory of assets") args, unknown = parser.parse_known_args() host = pipeline.debug_host() pipeline.register_host(host) if args.creator: from .tools import creator creator.show(debug=True) elif args.loader: from .tools import loader loader.show(debug=True) elif args.manager: from .tools import sceneinventory sceneinventory.show(debug=True) elif args.projectmanager: from .tools import projectmanager projectmanager.cli(unknown) Refactor manager argument to sceneinventoryimport argparse from . import pipeline if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("--creator", action="store_true", help="Launch Instance Creator in standalone mode") parser.add_argument("--loader", action="store_true", help="Launch Asset Loader in standalone mode") parser.add_argument("--sceneinventory", action="store_true", help="Launch Scene Inventory in standalone mode") parser.add_argument("--projectmanager", action="store_true", help="Launch Manager in standalone mode") parser.add_argument("--root", help="Absolute path to root directory of assets") args, unknown = parser.parse_known_args() host = pipeline.debug_host() pipeline.register_host(host) if args.creator: from .tools import creator creator.show(debug=True) elif args.loader: from .tools import loader loader.show(debug=True) elif args.sceneinventory: from .tools import sceneinventory sceneinventory.show(debug=True) elif args.projectmanager: from .tools import projectmanager projectmanager.cli(unknown)
<commit_before>import argparse from . import pipeline if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("--creator", action="store_true", help="Launch Instance Creator in standalone mode") parser.add_argument("--loader", action="store_true", help="Launch Asset Loader in standalone mode") parser.add_argument("--manager", action="store_true", help="Launch Manager in standalone mode") parser.add_argument("--projectmanager", action="store_true", help="Launch Manager in standalone mode") parser.add_argument("--root", help="Absolute path to root directory of assets") args, unknown = parser.parse_known_args() host = pipeline.debug_host() pipeline.register_host(host) if args.creator: from .tools import creator creator.show(debug=True) elif args.loader: from .tools import loader loader.show(debug=True) elif args.manager: from .tools import sceneinventory sceneinventory.show(debug=True) elif args.projectmanager: from .tools import projectmanager projectmanager.cli(unknown) <commit_msg>Refactor manager argument to sceneinventory<commit_after>import argparse from . import pipeline if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("--creator", action="store_true", help="Launch Instance Creator in standalone mode") parser.add_argument("--loader", action="store_true", help="Launch Asset Loader in standalone mode") parser.add_argument("--sceneinventory", action="store_true", help="Launch Scene Inventory in standalone mode") parser.add_argument("--projectmanager", action="store_true", help="Launch Manager in standalone mode") parser.add_argument("--root", help="Absolute path to root directory of assets") args, unknown = parser.parse_known_args() host = pipeline.debug_host() pipeline.register_host(host) if args.creator: from .tools import creator creator.show(debug=True) elif args.loader: from .tools import loader loader.show(debug=True) elif args.sceneinventory: from .tools import sceneinventory sceneinventory.show(debug=True) elif args.projectmanager: from .tools import projectmanager projectmanager.cli(unknown)
79ee512bb989056c521e3e38d9d8a52c2bd3d3fc
tests/__init__.py
tests/__init__.py
# -*- coding: utf8 -*- import sys import os import libcrowds_statistics as plugin # Use the PyBossa test suite sys.path.append(os.path.abspath("./pybossa/test")) os.environ['STATISTICS_SETTINGS'] = '../settings_test.py' def setUpPackage(): """Setup the plugin.""" from default import flask_app with flask_app.app_context(): flask_app.config['STATISTICS_RECORD_ALL_IPS'] = False plugin_dir = os.path.dirname(plugin.__file__) plugin.LibCrowdsStatistics(plugin_dir).setup()
# -*- coding: utf8 -*- import sys import os import libcrowds_statistics as plugin # Use the PyBossa test suite sys.path.append(os.path.abspath("./pybossa/test")) os.environ['STATISTICS_SETTINGS'] = '../settings_test.py' def setUpPackage(): """Setup the plugin.""" from default import flask_app with flask_app.app_context(): plugin_dir = os.path.dirname(plugin.__file__) plugin.LibCrowdsStatistics(plugin_dir).setup()
Remove duplicate setting of config variable
Remove duplicate setting of config variable
Python
bsd-3-clause
LibCrowds/libcrowds-statistics,LibCrowds/libcrowds-statistics,LibCrowds/libcrowds-statistics
# -*- coding: utf8 -*- import sys import os import libcrowds_statistics as plugin # Use the PyBossa test suite sys.path.append(os.path.abspath("./pybossa/test")) os.environ['STATISTICS_SETTINGS'] = '../settings_test.py' def setUpPackage(): """Setup the plugin.""" from default import flask_app with flask_app.app_context(): flask_app.config['STATISTICS_RECORD_ALL_IPS'] = False plugin_dir = os.path.dirname(plugin.__file__) plugin.LibCrowdsStatistics(plugin_dir).setup() Remove duplicate setting of config variable
# -*- coding: utf8 -*- import sys import os import libcrowds_statistics as plugin # Use the PyBossa test suite sys.path.append(os.path.abspath("./pybossa/test")) os.environ['STATISTICS_SETTINGS'] = '../settings_test.py' def setUpPackage(): """Setup the plugin.""" from default import flask_app with flask_app.app_context(): plugin_dir = os.path.dirname(plugin.__file__) plugin.LibCrowdsStatistics(plugin_dir).setup()
<commit_before># -*- coding: utf8 -*- import sys import os import libcrowds_statistics as plugin # Use the PyBossa test suite sys.path.append(os.path.abspath("./pybossa/test")) os.environ['STATISTICS_SETTINGS'] = '../settings_test.py' def setUpPackage(): """Setup the plugin.""" from default import flask_app with flask_app.app_context(): flask_app.config['STATISTICS_RECORD_ALL_IPS'] = False plugin_dir = os.path.dirname(plugin.__file__) plugin.LibCrowdsStatistics(plugin_dir).setup() <commit_msg>Remove duplicate setting of config variable<commit_after>
# -*- coding: utf8 -*- import sys import os import libcrowds_statistics as plugin # Use the PyBossa test suite sys.path.append(os.path.abspath("./pybossa/test")) os.environ['STATISTICS_SETTINGS'] = '../settings_test.py' def setUpPackage(): """Setup the plugin.""" from default import flask_app with flask_app.app_context(): plugin_dir = os.path.dirname(plugin.__file__) plugin.LibCrowdsStatistics(plugin_dir).setup()
# -*- coding: utf8 -*- import sys import os import libcrowds_statistics as plugin # Use the PyBossa test suite sys.path.append(os.path.abspath("./pybossa/test")) os.environ['STATISTICS_SETTINGS'] = '../settings_test.py' def setUpPackage(): """Setup the plugin.""" from default import flask_app with flask_app.app_context(): flask_app.config['STATISTICS_RECORD_ALL_IPS'] = False plugin_dir = os.path.dirname(plugin.__file__) plugin.LibCrowdsStatistics(plugin_dir).setup() Remove duplicate setting of config variable# -*- coding: utf8 -*- import sys import os import libcrowds_statistics as plugin # Use the PyBossa test suite sys.path.append(os.path.abspath("./pybossa/test")) os.environ['STATISTICS_SETTINGS'] = '../settings_test.py' def setUpPackage(): """Setup the plugin.""" from default import flask_app with flask_app.app_context(): plugin_dir = os.path.dirname(plugin.__file__) plugin.LibCrowdsStatistics(plugin_dir).setup()
<commit_before># -*- coding: utf8 -*- import sys import os import libcrowds_statistics as plugin # Use the PyBossa test suite sys.path.append(os.path.abspath("./pybossa/test")) os.environ['STATISTICS_SETTINGS'] = '../settings_test.py' def setUpPackage(): """Setup the plugin.""" from default import flask_app with flask_app.app_context(): flask_app.config['STATISTICS_RECORD_ALL_IPS'] = False plugin_dir = os.path.dirname(plugin.__file__) plugin.LibCrowdsStatistics(plugin_dir).setup() <commit_msg>Remove duplicate setting of config variable<commit_after># -*- coding: utf8 -*- import sys import os import libcrowds_statistics as plugin # Use the PyBossa test suite sys.path.append(os.path.abspath("./pybossa/test")) os.environ['STATISTICS_SETTINGS'] = '../settings_test.py' def setUpPackage(): """Setup the plugin.""" from default import flask_app with flask_app.app_context(): plugin_dir = os.path.dirname(plugin.__file__) plugin.LibCrowdsStatistics(plugin_dir).setup()
27668d5e5c1c40b342ca4d280ed3aaa49532c845
email-ping.py
email-ping.py
import smtplib import time from email.mime.text import MIMEText to_list = ('',) # add recipient (your remote account) here from_email = '' # email from which the e-mail is sent; must be accepted by SMTP s = smtplib.SMTP('') # SMTP address s.login('', '') # ('smtp login', 'smtp password') for to in to_list: msg = MIMEText('server status: OK') msg['Subject'] = 'Server status '+time.ctime() msg['From'] = from_email msg['To'] = to print msg.as_string() s.sendmail(from_email, [to], msg.as_string())
#!/usr/bin/python import smtplib import time from email.mime.text import MIMEText to_list = ('',) # add recipient (your remote account) here from_email = '' # email from which the e-mail is sent; must be accepted by SMTP s = smtplib.SMTP_SSL('') # SMTP address s.login('', '') # ('smtp login', 'smtp password') for to in to_list: msg = MIMEText('server status: OK') msg['Subject'] = 'Server status '+time.ctime() msg['From'] = from_email msg['To'] = to print msg.as_string() s.sendmail(from_email, [to], msg.as_string())
Update email_ping.py with header and SSL default
Update email_ping.py with header and SSL default
Python
mit
krzysztofr/gmail-force-check
import smtplib import time from email.mime.text import MIMEText to_list = ('',) # add recipient (your remote account) here from_email = '' # email from which the e-mail is sent; must be accepted by SMTP s = smtplib.SMTP('') # SMTP address s.login('', '') # ('smtp login', 'smtp password') for to in to_list: msg = MIMEText('server status: OK') msg['Subject'] = 'Server status '+time.ctime() msg['From'] = from_email msg['To'] = to print msg.as_string() s.sendmail(from_email, [to], msg.as_string()) Update email_ping.py with header and SSL default
#!/usr/bin/python import smtplib import time from email.mime.text import MIMEText to_list = ('',) # add recipient (your remote account) here from_email = '' # email from which the e-mail is sent; must be accepted by SMTP s = smtplib.SMTP_SSL('') # SMTP address s.login('', '') # ('smtp login', 'smtp password') for to in to_list: msg = MIMEText('server status: OK') msg['Subject'] = 'Server status '+time.ctime() msg['From'] = from_email msg['To'] = to print msg.as_string() s.sendmail(from_email, [to], msg.as_string())
<commit_before>import smtplib import time from email.mime.text import MIMEText to_list = ('',) # add recipient (your remote account) here from_email = '' # email from which the e-mail is sent; must be accepted by SMTP s = smtplib.SMTP('') # SMTP address s.login('', '') # ('smtp login', 'smtp password') for to in to_list: msg = MIMEText('server status: OK') msg['Subject'] = 'Server status '+time.ctime() msg['From'] = from_email msg['To'] = to print msg.as_string() s.sendmail(from_email, [to], msg.as_string()) <commit_msg>Update email_ping.py with header and SSL default<commit_after>
#!/usr/bin/python import smtplib import time from email.mime.text import MIMEText to_list = ('',) # add recipient (your remote account) here from_email = '' # email from which the e-mail is sent; must be accepted by SMTP s = smtplib.SMTP_SSL('') # SMTP address s.login('', '') # ('smtp login', 'smtp password') for to in to_list: msg = MIMEText('server status: OK') msg['Subject'] = 'Server status '+time.ctime() msg['From'] = from_email msg['To'] = to print msg.as_string() s.sendmail(from_email, [to], msg.as_string())
import smtplib import time from email.mime.text import MIMEText to_list = ('',) # add recipient (your remote account) here from_email = '' # email from which the e-mail is sent; must be accepted by SMTP s = smtplib.SMTP('') # SMTP address s.login('', '') # ('smtp login', 'smtp password') for to in to_list: msg = MIMEText('server status: OK') msg['Subject'] = 'Server status '+time.ctime() msg['From'] = from_email msg['To'] = to print msg.as_string() s.sendmail(from_email, [to], msg.as_string()) Update email_ping.py with header and SSL default#!/usr/bin/python import smtplib import time from email.mime.text import MIMEText to_list = ('',) # add recipient (your remote account) here from_email = '' # email from which the e-mail is sent; must be accepted by SMTP s = smtplib.SMTP_SSL('') # SMTP address s.login('', '') # ('smtp login', 'smtp password') for to in to_list: msg = MIMEText('server status: OK') msg['Subject'] = 'Server status '+time.ctime() msg['From'] = from_email msg['To'] = to print msg.as_string() s.sendmail(from_email, [to], msg.as_string())
<commit_before>import smtplib import time from email.mime.text import MIMEText to_list = ('',) # add recipient (your remote account) here from_email = '' # email from which the e-mail is sent; must be accepted by SMTP s = smtplib.SMTP('') # SMTP address s.login('', '') # ('smtp login', 'smtp password') for to in to_list: msg = MIMEText('server status: OK') msg['Subject'] = 'Server status '+time.ctime() msg['From'] = from_email msg['To'] = to print msg.as_string() s.sendmail(from_email, [to], msg.as_string()) <commit_msg>Update email_ping.py with header and SSL default<commit_after>#!/usr/bin/python import smtplib import time from email.mime.text import MIMEText to_list = ('',) # add recipient (your remote account) here from_email = '' # email from which the e-mail is sent; must be accepted by SMTP s = smtplib.SMTP_SSL('') # SMTP address s.login('', '') # ('smtp login', 'smtp password') for to in to_list: msg = MIMEText('server status: OK') msg['Subject'] = 'Server status '+time.ctime() msg['From'] = from_email msg['To'] = to print msg.as_string() s.sendmail(from_email, [to], msg.as_string())
72b0ed654749bdd01989567a5eee2234cb8328ce
registration/admin.py
registration/admin.py
from django.contrib import admin from registration.models import RegistrationProfile class RegistrationAdmin(admin.ModelAdmin): list_display = ('__unicode__', 'activation_key_expired') search_fields = ('user__username', 'user__first_name') admin.site.register(RegistrationProfile, RegistrationAdmin)
from django.contrib import admin from registration.models import RegistrationProfile class RegistrationAdmin(admin.ModelAdmin): list_display = ('__unicode__', 'activation_key_expired') raw_id_fields = ['user'] search_fields = ('user__username', 'user__first_name') admin.site.register(RegistrationProfile, RegistrationAdmin)
Use raw_id_fields for the relation from RegistrationProfile to User, for sites which have huge numbers of users.
Use raw_id_fields for the relation from RegistrationProfile to User, for sites which have huge numbers of users.
Python
bsd-3-clause
lubosz/django-registration,lubosz/django-registration
from django.contrib import admin from registration.models import RegistrationProfile class RegistrationAdmin(admin.ModelAdmin): list_display = ('__unicode__', 'activation_key_expired') search_fields = ('user__username', 'user__first_name') admin.site.register(RegistrationProfile, RegistrationAdmin) Use raw_id_fields for the relation from RegistrationProfile to User, for sites which have huge numbers of users.
from django.contrib import admin from registration.models import RegistrationProfile class RegistrationAdmin(admin.ModelAdmin): list_display = ('__unicode__', 'activation_key_expired') raw_id_fields = ['user'] search_fields = ('user__username', 'user__first_name') admin.site.register(RegistrationProfile, RegistrationAdmin)
<commit_before>from django.contrib import admin from registration.models import RegistrationProfile class RegistrationAdmin(admin.ModelAdmin): list_display = ('__unicode__', 'activation_key_expired') search_fields = ('user__username', 'user__first_name') admin.site.register(RegistrationProfile, RegistrationAdmin) <commit_msg>Use raw_id_fields for the relation from RegistrationProfile to User, for sites which have huge numbers of users.<commit_after>
from django.contrib import admin from registration.models import RegistrationProfile class RegistrationAdmin(admin.ModelAdmin): list_display = ('__unicode__', 'activation_key_expired') raw_id_fields = ['user'] search_fields = ('user__username', 'user__first_name') admin.site.register(RegistrationProfile, RegistrationAdmin)
from django.contrib import admin from registration.models import RegistrationProfile class RegistrationAdmin(admin.ModelAdmin): list_display = ('__unicode__', 'activation_key_expired') search_fields = ('user__username', 'user__first_name') admin.site.register(RegistrationProfile, RegistrationAdmin) Use raw_id_fields for the relation from RegistrationProfile to User, for sites which have huge numbers of users.from django.contrib import admin from registration.models import RegistrationProfile class RegistrationAdmin(admin.ModelAdmin): list_display = ('__unicode__', 'activation_key_expired') raw_id_fields = ['user'] search_fields = ('user__username', 'user__first_name') admin.site.register(RegistrationProfile, RegistrationAdmin)
<commit_before>from django.contrib import admin from registration.models import RegistrationProfile class RegistrationAdmin(admin.ModelAdmin): list_display = ('__unicode__', 'activation_key_expired') search_fields = ('user__username', 'user__first_name') admin.site.register(RegistrationProfile, RegistrationAdmin) <commit_msg>Use raw_id_fields for the relation from RegistrationProfile to User, for sites which have huge numbers of users.<commit_after>from django.contrib import admin from registration.models import RegistrationProfile class RegistrationAdmin(admin.ModelAdmin): list_display = ('__unicode__', 'activation_key_expired') raw_id_fields = ['user'] search_fields = ('user__username', 'user__first_name') admin.site.register(RegistrationProfile, RegistrationAdmin)
5b48bab8c884dd66dc40bc591fc0c66621fa01a1
game_state.py
game_state.py
""" An enum describing the various possible game states. Author: Isaac Arvestad """ class GameState(Enum): playing = 1 over = 2
""" An enum describing the various possible game states. Author: Isaac Arvestad """ class GameState(Enum): playing = 1 ended = 2
Change name from 'over' to 'ended'.
Change name from 'over' to 'ended'.
Python
mit
isaacarvestad/four-in-a-row
""" An enum describing the various possible game states. Author: Isaac Arvestad """ class GameState(Enum): playing = 1 over = 2 Change name from 'over' to 'ended'.
""" An enum describing the various possible game states. Author: Isaac Arvestad """ class GameState(Enum): playing = 1 ended = 2
<commit_before>""" An enum describing the various possible game states. Author: Isaac Arvestad """ class GameState(Enum): playing = 1 over = 2 <commit_msg>Change name from 'over' to 'ended'.<commit_after>
""" An enum describing the various possible game states. Author: Isaac Arvestad """ class GameState(Enum): playing = 1 ended = 2
""" An enum describing the various possible game states. Author: Isaac Arvestad """ class GameState(Enum): playing = 1 over = 2 Change name from 'over' to 'ended'.""" An enum describing the various possible game states. Author: Isaac Arvestad """ class GameState(Enum): playing = 1 ended = 2
<commit_before>""" An enum describing the various possible game states. Author: Isaac Arvestad """ class GameState(Enum): playing = 1 over = 2 <commit_msg>Change name from 'over' to 'ended'.<commit_after>""" An enum describing the various possible game states. Author: Isaac Arvestad """ class GameState(Enum): playing = 1 ended = 2
bc9656c1ced31f0592b6d73a0678386843afa5b5
db/migrations/migration5.py
db/migrations/migration5.py
import sqlite3 def migrate(database_path): print "migrating to db version 5" conn = sqlite3.connect(database_path) conn.text_factory = str cursor = conn.cursor() # update settings table to include smtp server settings cursor.execute('''ALTER TABLE sales ADD COLUMN "unread" INTEGER''') cursor.execute('''ALTER TABLE purchases ADD COLUMN "unread" INTEGER''') cursor.execute('''ALTER TABLE cases ADD COLUMN "unread" INTEGER''') # update version cursor.execute('''PRAGMA user_version = 5''') conn.commit() conn.close()
import sqlite3 def migrate(database_path): print "migrating to db version 5" conn = sqlite3.connect(database_path) conn.text_factory = str cursor = conn.cursor() # update settings table to include smtp server settings cursor.execute('''ALTER TABLE sales ADD COLUMN "unread" INTEGER''') cursor.execute('''ALTER TABLE purchases ADD COLUMN "unread" INTEGER''') cursor.execute('''ALTER TABLE cases ADD COLUMN "unread" INTEGER''') cursor.execute('''UPDATE purchases SET unread = 0;''') cursor.execute('''UPDATE purchases SET unread = 0;''') cursor.execute('''UPDATE purchases SET unread = 0;''') # update version cursor.execute('''PRAGMA user_version = 5''') conn.commit() conn.close()
Initialize unread column to 0
Initialize unread column to 0
Python
mit
tyler-smith/OpenBazaar-Server,tyler-smith/OpenBazaar-Server,OpenBazaar/OpenBazaar-Server,cpacia/OpenBazaar-Server,cpacia/OpenBazaar-Server,tyler-smith/OpenBazaar-Server,OpenBazaar/Network,OpenBazaar/OpenBazaar-Server,OpenBazaar/Network,saltduck/OpenBazaar-Server,OpenBazaar/Network,tomgalloway/OpenBazaar-Server,cpacia/OpenBazaar-Server,tomgalloway/OpenBazaar-Server,OpenBazaar/OpenBazaar-Server,saltduck/OpenBazaar-Server,tomgalloway/OpenBazaar-Server,saltduck/OpenBazaar-Server
import sqlite3 def migrate(database_path): print "migrating to db version 5" conn = sqlite3.connect(database_path) conn.text_factory = str cursor = conn.cursor() # update settings table to include smtp server settings cursor.execute('''ALTER TABLE sales ADD COLUMN "unread" INTEGER''') cursor.execute('''ALTER TABLE purchases ADD COLUMN "unread" INTEGER''') cursor.execute('''ALTER TABLE cases ADD COLUMN "unread" INTEGER''') # update version cursor.execute('''PRAGMA user_version = 5''') conn.commit() conn.close() Initialize unread column to 0
import sqlite3 def migrate(database_path): print "migrating to db version 5" conn = sqlite3.connect(database_path) conn.text_factory = str cursor = conn.cursor() # update settings table to include smtp server settings cursor.execute('''ALTER TABLE sales ADD COLUMN "unread" INTEGER''') cursor.execute('''ALTER TABLE purchases ADD COLUMN "unread" INTEGER''') cursor.execute('''ALTER TABLE cases ADD COLUMN "unread" INTEGER''') cursor.execute('''UPDATE purchases SET unread = 0;''') cursor.execute('''UPDATE purchases SET unread = 0;''') cursor.execute('''UPDATE purchases SET unread = 0;''') # update version cursor.execute('''PRAGMA user_version = 5''') conn.commit() conn.close()
<commit_before>import sqlite3 def migrate(database_path): print "migrating to db version 5" conn = sqlite3.connect(database_path) conn.text_factory = str cursor = conn.cursor() # update settings table to include smtp server settings cursor.execute('''ALTER TABLE sales ADD COLUMN "unread" INTEGER''') cursor.execute('''ALTER TABLE purchases ADD COLUMN "unread" INTEGER''') cursor.execute('''ALTER TABLE cases ADD COLUMN "unread" INTEGER''') # update version cursor.execute('''PRAGMA user_version = 5''') conn.commit() conn.close() <commit_msg>Initialize unread column to 0<commit_after>
import sqlite3 def migrate(database_path): print "migrating to db version 5" conn = sqlite3.connect(database_path) conn.text_factory = str cursor = conn.cursor() # update settings table to include smtp server settings cursor.execute('''ALTER TABLE sales ADD COLUMN "unread" INTEGER''') cursor.execute('''ALTER TABLE purchases ADD COLUMN "unread" INTEGER''') cursor.execute('''ALTER TABLE cases ADD COLUMN "unread" INTEGER''') cursor.execute('''UPDATE purchases SET unread = 0;''') cursor.execute('''UPDATE purchases SET unread = 0;''') cursor.execute('''UPDATE purchases SET unread = 0;''') # update version cursor.execute('''PRAGMA user_version = 5''') conn.commit() conn.close()
import sqlite3 def migrate(database_path): print "migrating to db version 5" conn = sqlite3.connect(database_path) conn.text_factory = str cursor = conn.cursor() # update settings table to include smtp server settings cursor.execute('''ALTER TABLE sales ADD COLUMN "unread" INTEGER''') cursor.execute('''ALTER TABLE purchases ADD COLUMN "unread" INTEGER''') cursor.execute('''ALTER TABLE cases ADD COLUMN "unread" INTEGER''') # update version cursor.execute('''PRAGMA user_version = 5''') conn.commit() conn.close() Initialize unread column to 0import sqlite3 def migrate(database_path): print "migrating to db version 5" conn = sqlite3.connect(database_path) conn.text_factory = str cursor = conn.cursor() # update settings table to include smtp server settings cursor.execute('''ALTER TABLE sales ADD COLUMN "unread" INTEGER''') cursor.execute('''ALTER TABLE purchases ADD COLUMN "unread" INTEGER''') cursor.execute('''ALTER TABLE cases ADD COLUMN "unread" INTEGER''') cursor.execute('''UPDATE purchases SET unread = 0;''') cursor.execute('''UPDATE purchases SET unread = 0;''') cursor.execute('''UPDATE purchases SET unread = 0;''') # update version cursor.execute('''PRAGMA user_version = 5''') conn.commit() conn.close()
<commit_before>import sqlite3 def migrate(database_path): print "migrating to db version 5" conn = sqlite3.connect(database_path) conn.text_factory = str cursor = conn.cursor() # update settings table to include smtp server settings cursor.execute('''ALTER TABLE sales ADD COLUMN "unread" INTEGER''') cursor.execute('''ALTER TABLE purchases ADD COLUMN "unread" INTEGER''') cursor.execute('''ALTER TABLE cases ADD COLUMN "unread" INTEGER''') # update version cursor.execute('''PRAGMA user_version = 5''') conn.commit() conn.close() <commit_msg>Initialize unread column to 0<commit_after>import sqlite3 def migrate(database_path): print "migrating to db version 5" conn = sqlite3.connect(database_path) conn.text_factory = str cursor = conn.cursor() # update settings table to include smtp server settings cursor.execute('''ALTER TABLE sales ADD COLUMN "unread" INTEGER''') cursor.execute('''ALTER TABLE purchases ADD COLUMN "unread" INTEGER''') cursor.execute('''ALTER TABLE cases ADD COLUMN "unread" INTEGER''') cursor.execute('''UPDATE purchases SET unread = 0;''') cursor.execute('''UPDATE purchases SET unread = 0;''') cursor.execute('''UPDATE purchases SET unread = 0;''') # update version cursor.execute('''PRAGMA user_version = 5''') conn.commit() conn.close()
1abf1add68f9a1224fe5f754b0f01a86dbb1008c
maras/nestdb.py
maras/nestdb.py
''' Create a stock database with a built in nesting key index ''' # Import maras libs import maras.database import maras.tree_index # We can likely build these out as mixins, making it easy to apply high level # constructs to multiple unerlying database implimentations class NestDB(maras.database.Database): ''' Create a high level database which translates entry keys into a higherarcical dict like structure ''' def __init__(self, path): maras.database.Database.__init__(self, path) self.__init_db() def __init_db(self): ''' Init the db, open it if it already exists, otherwise create it ''' try: self.open() except maras.database.DatabasePathException: self.create() def new_index(self, name): ''' Add a new named index ''' new = NestIndex(self.path, name) self.add_index(new) class NestIndex(maras.tree_index.TreeBasedIndex): ''' The index to manage higherarcical keys ''' def __init__(self, *args, **kwargs): kwargs['node_capacity'] = kwargs.get('node_capacity', 1000) maras.tree_index.TreeBasedIndex.__init__(self, *args, **kwargs) def make_key_value(self, data): return data.get('_key', 'None') def make_key(self, key): return key
''' Create a stock database with a built in nesting key index ''' # Import maras libs import maras.database import maras.tree_index # We can likely build these out as mixins, making it easy to apply high level # constructs to multiple unerlying database implimentations class NestDB(maras.database.Database): ''' Create a high level database which translates entry keys into a higherarcical dict like structure ''' def __init__(self, path): maras.database.Database.__init__(self, path) self.__init_db() def __init_db(self): ''' Init the db, open it if it already exists, otherwise create it ''' try: self.open() except maras.database.DatabasePathException: self.create() def new_index(self, name): ''' Add a new named index ''' new = NestIndex(self.path, name) self.add_index(new) class NestIndex(maras.tree_index.TreeBasedIndex): ''' The index to manage higherarcical keys ''' def __init__(self, *args, **kwargs): kwargs['node_capacity'] = kwargs.get('node_capacity', 1000) maras.tree_index.TreeBasedIndex.__init__(self, *args, **kwargs) def make_key_value(self, data): if '_key' in data: return data.pop('_key') return 'None' def make_key(self, key): return key
Clean out the _key from the data, no need to double entry
Clean out the _key from the data, no need to double entry
Python
apache-2.0
thatch45/maras_old
''' Create a stock database with a built in nesting key index ''' # Import maras libs import maras.database import maras.tree_index # We can likely build these out as mixins, making it easy to apply high level # constructs to multiple unerlying database implimentations class NestDB(maras.database.Database): ''' Create a high level database which translates entry keys into a higherarcical dict like structure ''' def __init__(self, path): maras.database.Database.__init__(self, path) self.__init_db() def __init_db(self): ''' Init the db, open it if it already exists, otherwise create it ''' try: self.open() except maras.database.DatabasePathException: self.create() def new_index(self, name): ''' Add a new named index ''' new = NestIndex(self.path, name) self.add_index(new) class NestIndex(maras.tree_index.TreeBasedIndex): ''' The index to manage higherarcical keys ''' def __init__(self, *args, **kwargs): kwargs['node_capacity'] = kwargs.get('node_capacity', 1000) maras.tree_index.TreeBasedIndex.__init__(self, *args, **kwargs) def make_key_value(self, data): return data.get('_key', 'None') def make_key(self, key): return key Clean out the _key from the data, no need to double entry
''' Create a stock database with a built in nesting key index ''' # Import maras libs import maras.database import maras.tree_index # We can likely build these out as mixins, making it easy to apply high level # constructs to multiple unerlying database implimentations class NestDB(maras.database.Database): ''' Create a high level database which translates entry keys into a higherarcical dict like structure ''' def __init__(self, path): maras.database.Database.__init__(self, path) self.__init_db() def __init_db(self): ''' Init the db, open it if it already exists, otherwise create it ''' try: self.open() except maras.database.DatabasePathException: self.create() def new_index(self, name): ''' Add a new named index ''' new = NestIndex(self.path, name) self.add_index(new) class NestIndex(maras.tree_index.TreeBasedIndex): ''' The index to manage higherarcical keys ''' def __init__(self, *args, **kwargs): kwargs['node_capacity'] = kwargs.get('node_capacity', 1000) maras.tree_index.TreeBasedIndex.__init__(self, *args, **kwargs) def make_key_value(self, data): if '_key' in data: return data.pop('_key') return 'None' def make_key(self, key): return key
<commit_before>''' Create a stock database with a built in nesting key index ''' # Import maras libs import maras.database import maras.tree_index # We can likely build these out as mixins, making it easy to apply high level # constructs to multiple unerlying database implimentations class NestDB(maras.database.Database): ''' Create a high level database which translates entry keys into a higherarcical dict like structure ''' def __init__(self, path): maras.database.Database.__init__(self, path) self.__init_db() def __init_db(self): ''' Init the db, open it if it already exists, otherwise create it ''' try: self.open() except maras.database.DatabasePathException: self.create() def new_index(self, name): ''' Add a new named index ''' new = NestIndex(self.path, name) self.add_index(new) class NestIndex(maras.tree_index.TreeBasedIndex): ''' The index to manage higherarcical keys ''' def __init__(self, *args, **kwargs): kwargs['node_capacity'] = kwargs.get('node_capacity', 1000) maras.tree_index.TreeBasedIndex.__init__(self, *args, **kwargs) def make_key_value(self, data): return data.get('_key', 'None') def make_key(self, key): return key <commit_msg>Clean out the _key from the data, no need to double entry<commit_after>
''' Create a stock database with a built in nesting key index ''' # Import maras libs import maras.database import maras.tree_index # We can likely build these out as mixins, making it easy to apply high level # constructs to multiple unerlying database implimentations class NestDB(maras.database.Database): ''' Create a high level database which translates entry keys into a higherarcical dict like structure ''' def __init__(self, path): maras.database.Database.__init__(self, path) self.__init_db() def __init_db(self): ''' Init the db, open it if it already exists, otherwise create it ''' try: self.open() except maras.database.DatabasePathException: self.create() def new_index(self, name): ''' Add a new named index ''' new = NestIndex(self.path, name) self.add_index(new) class NestIndex(maras.tree_index.TreeBasedIndex): ''' The index to manage higherarcical keys ''' def __init__(self, *args, **kwargs): kwargs['node_capacity'] = kwargs.get('node_capacity', 1000) maras.tree_index.TreeBasedIndex.__init__(self, *args, **kwargs) def make_key_value(self, data): if '_key' in data: return data.pop('_key') return 'None' def make_key(self, key): return key
''' Create a stock database with a built in nesting key index ''' # Import maras libs import maras.database import maras.tree_index # We can likely build these out as mixins, making it easy to apply high level # constructs to multiple unerlying database implimentations class NestDB(maras.database.Database): ''' Create a high level database which translates entry keys into a higherarcical dict like structure ''' def __init__(self, path): maras.database.Database.__init__(self, path) self.__init_db() def __init_db(self): ''' Init the db, open it if it already exists, otherwise create it ''' try: self.open() except maras.database.DatabasePathException: self.create() def new_index(self, name): ''' Add a new named index ''' new = NestIndex(self.path, name) self.add_index(new) class NestIndex(maras.tree_index.TreeBasedIndex): ''' The index to manage higherarcical keys ''' def __init__(self, *args, **kwargs): kwargs['node_capacity'] = kwargs.get('node_capacity', 1000) maras.tree_index.TreeBasedIndex.__init__(self, *args, **kwargs) def make_key_value(self, data): return data.get('_key', 'None') def make_key(self, key): return key Clean out the _key from the data, no need to double entry''' Create a stock database with a built in nesting key index ''' # Import maras libs import maras.database import maras.tree_index # We can likely build these out as mixins, making it easy to apply high level # constructs to multiple unerlying database implimentations class NestDB(maras.database.Database): ''' Create a high level database which translates entry keys into a higherarcical dict like structure ''' def __init__(self, path): maras.database.Database.__init__(self, path) self.__init_db() def __init_db(self): ''' Init the db, open it if it already exists, otherwise create it ''' try: self.open() except maras.database.DatabasePathException: self.create() def new_index(self, name): ''' Add a new named index ''' new = NestIndex(self.path, name) self.add_index(new) class NestIndex(maras.tree_index.TreeBasedIndex): ''' The index to manage higherarcical keys ''' def __init__(self, *args, **kwargs): kwargs['node_capacity'] = kwargs.get('node_capacity', 1000) maras.tree_index.TreeBasedIndex.__init__(self, *args, **kwargs) def make_key_value(self, data): if '_key' in data: return data.pop('_key') return 'None' def make_key(self, key): return key
<commit_before>''' Create a stock database with a built in nesting key index ''' # Import maras libs import maras.database import maras.tree_index # We can likely build these out as mixins, making it easy to apply high level # constructs to multiple unerlying database implimentations class NestDB(maras.database.Database): ''' Create a high level database which translates entry keys into a higherarcical dict like structure ''' def __init__(self, path): maras.database.Database.__init__(self, path) self.__init_db() def __init_db(self): ''' Init the db, open it if it already exists, otherwise create it ''' try: self.open() except maras.database.DatabasePathException: self.create() def new_index(self, name): ''' Add a new named index ''' new = NestIndex(self.path, name) self.add_index(new) class NestIndex(maras.tree_index.TreeBasedIndex): ''' The index to manage higherarcical keys ''' def __init__(self, *args, **kwargs): kwargs['node_capacity'] = kwargs.get('node_capacity', 1000) maras.tree_index.TreeBasedIndex.__init__(self, *args, **kwargs) def make_key_value(self, data): return data.get('_key', 'None') def make_key(self, key): return key <commit_msg>Clean out the _key from the data, no need to double entry<commit_after>''' Create a stock database with a built in nesting key index ''' # Import maras libs import maras.database import maras.tree_index # We can likely build these out as mixins, making it easy to apply high level # constructs to multiple unerlying database implimentations class NestDB(maras.database.Database): ''' Create a high level database which translates entry keys into a higherarcical dict like structure ''' def __init__(self, path): maras.database.Database.__init__(self, path) self.__init_db() def __init_db(self): ''' Init the db, open it if it already exists, otherwise create it ''' try: self.open() except maras.database.DatabasePathException: self.create() def new_index(self, name): ''' Add a new named index ''' new = NestIndex(self.path, name) self.add_index(new) class NestIndex(maras.tree_index.TreeBasedIndex): ''' The index to manage higherarcical keys ''' def __init__(self, *args, **kwargs): kwargs['node_capacity'] = kwargs.get('node_capacity', 1000) maras.tree_index.TreeBasedIndex.__init__(self, *args, **kwargs) def make_key_value(self, data): if '_key' in data: return data.pop('_key') return 'None' def make_key(self, key): return key
a2713927beb4b80ba62cc0273df24d33cca4a689
namuhub/__init__.py
namuhub/__init__.py
"""namuhub --- namu.wiki contribution graph""" from flask import Flask, jsonify, render_template, request, url_for app = Flask('namuhub') @app.route('/', methods=['GET']) def index(): return render_template('index.html') @app.route('/<user>', methods=['GET']) def index_user(user=''): return render_template('index.html', **{'user': user}) @app.route('/', methods=['POST']) def namu(): user = request.POST.get('user', None) if not user: return '', 501
"""namuhub --- namu.wiki contribution graph""" import time from collections import defaultdict from datetime import timedelta from flask import Flask, jsonify, render_template, request, url_for from namuhub import namu as namuwiki app = Flask('namuhub') @app.route('/', methods=['GET']) def index(): return render_template('index.html') @app.route('/<user>', methods=['GET']) def index_user(user=''): return render_template('index.html', **{'user': user}) @app.route('/', methods=['POST']) def namu(): user = request.form.get('user', None) if not user: return jsonify({}), 501 contribs = namuwiki.contrib(user) data = defaultdict(lambda: []) # First, separate contributions into list by their activity date for contrib in contribs: date = (contrib.when - timedelta(hours=9)).date().strftime('%Y-%m-%d') data[date].append(contrib) # Convert defaultdict to dict # However, this may be inefficient but I don't care about performance at this point because it doesn't matter while it's a small project data = dict(data) # Next, we should serialize it as dict object to make sure that all the values are JSON serialiable for key, value in data.items(): value = [c.as_dict() for c in value] # Almost done, fix timezone and convert its date property to unix timestamp number that can be parsed by javascript's date object for i, c in enumerate(value): value[i]['when'] = int(time.mktime((c['when'] + timedelta(hours=9)).timetuple())) * 1000 # Overwrite existing value data[key] = value return jsonify(data)
Return namu.wiki contribution data as JSON
Return namu.wiki contribution data as JSON
Python
apache-2.0
ssut/namuhub,ssut/namuhub,ssut/namuhub
"""namuhub --- namu.wiki contribution graph""" from flask import Flask, jsonify, render_template, request, url_for app = Flask('namuhub') @app.route('/', methods=['GET']) def index(): return render_template('index.html') @app.route('/<user>', methods=['GET']) def index_user(user=''): return render_template('index.html', **{'user': user}) @app.route('/', methods=['POST']) def namu(): user = request.POST.get('user', None) if not user: return '', 501 Return namu.wiki contribution data as JSON
"""namuhub --- namu.wiki contribution graph""" import time from collections import defaultdict from datetime import timedelta from flask import Flask, jsonify, render_template, request, url_for from namuhub import namu as namuwiki app = Flask('namuhub') @app.route('/', methods=['GET']) def index(): return render_template('index.html') @app.route('/<user>', methods=['GET']) def index_user(user=''): return render_template('index.html', **{'user': user}) @app.route('/', methods=['POST']) def namu(): user = request.form.get('user', None) if not user: return jsonify({}), 501 contribs = namuwiki.contrib(user) data = defaultdict(lambda: []) # First, separate contributions into list by their activity date for contrib in contribs: date = (contrib.when - timedelta(hours=9)).date().strftime('%Y-%m-%d') data[date].append(contrib) # Convert defaultdict to dict # However, this may be inefficient but I don't care about performance at this point because it doesn't matter while it's a small project data = dict(data) # Next, we should serialize it as dict object to make sure that all the values are JSON serialiable for key, value in data.items(): value = [c.as_dict() for c in value] # Almost done, fix timezone and convert its date property to unix timestamp number that can be parsed by javascript's date object for i, c in enumerate(value): value[i]['when'] = int(time.mktime((c['when'] + timedelta(hours=9)).timetuple())) * 1000 # Overwrite existing value data[key] = value return jsonify(data)
<commit_before>"""namuhub --- namu.wiki contribution graph""" from flask import Flask, jsonify, render_template, request, url_for app = Flask('namuhub') @app.route('/', methods=['GET']) def index(): return render_template('index.html') @app.route('/<user>', methods=['GET']) def index_user(user=''): return render_template('index.html', **{'user': user}) @app.route('/', methods=['POST']) def namu(): user = request.POST.get('user', None) if not user: return '', 501 <commit_msg>Return namu.wiki contribution data as JSON<commit_after>
"""namuhub --- namu.wiki contribution graph""" import time from collections import defaultdict from datetime import timedelta from flask import Flask, jsonify, render_template, request, url_for from namuhub import namu as namuwiki app = Flask('namuhub') @app.route('/', methods=['GET']) def index(): return render_template('index.html') @app.route('/<user>', methods=['GET']) def index_user(user=''): return render_template('index.html', **{'user': user}) @app.route('/', methods=['POST']) def namu(): user = request.form.get('user', None) if not user: return jsonify({}), 501 contribs = namuwiki.contrib(user) data = defaultdict(lambda: []) # First, separate contributions into list by their activity date for contrib in contribs: date = (contrib.when - timedelta(hours=9)).date().strftime('%Y-%m-%d') data[date].append(contrib) # Convert defaultdict to dict # However, this may be inefficient but I don't care about performance at this point because it doesn't matter while it's a small project data = dict(data) # Next, we should serialize it as dict object to make sure that all the values are JSON serialiable for key, value in data.items(): value = [c.as_dict() for c in value] # Almost done, fix timezone and convert its date property to unix timestamp number that can be parsed by javascript's date object for i, c in enumerate(value): value[i]['when'] = int(time.mktime((c['when'] + timedelta(hours=9)).timetuple())) * 1000 # Overwrite existing value data[key] = value return jsonify(data)
"""namuhub --- namu.wiki contribution graph""" from flask import Flask, jsonify, render_template, request, url_for app = Flask('namuhub') @app.route('/', methods=['GET']) def index(): return render_template('index.html') @app.route('/<user>', methods=['GET']) def index_user(user=''): return render_template('index.html', **{'user': user}) @app.route('/', methods=['POST']) def namu(): user = request.POST.get('user', None) if not user: return '', 501 Return namu.wiki contribution data as JSON"""namuhub --- namu.wiki contribution graph""" import time from collections import defaultdict from datetime import timedelta from flask import Flask, jsonify, render_template, request, url_for from namuhub import namu as namuwiki app = Flask('namuhub') @app.route('/', methods=['GET']) def index(): return render_template('index.html') @app.route('/<user>', methods=['GET']) def index_user(user=''): return render_template('index.html', **{'user': user}) @app.route('/', methods=['POST']) def namu(): user = request.form.get('user', None) if not user: return jsonify({}), 501 contribs = namuwiki.contrib(user) data = defaultdict(lambda: []) # First, separate contributions into list by their activity date for contrib in contribs: date = (contrib.when - timedelta(hours=9)).date().strftime('%Y-%m-%d') data[date].append(contrib) # Convert defaultdict to dict # However, this may be inefficient but I don't care about performance at this point because it doesn't matter while it's a small project data = dict(data) # Next, we should serialize it as dict object to make sure that all the values are JSON serialiable for key, value in data.items(): value = [c.as_dict() for c in value] # Almost done, fix timezone and convert its date property to unix timestamp number that can be parsed by javascript's date object for i, c in enumerate(value): value[i]['when'] = int(time.mktime((c['when'] + timedelta(hours=9)).timetuple())) * 1000 # Overwrite existing value data[key] = value return jsonify(data)
<commit_before>"""namuhub --- namu.wiki contribution graph""" from flask import Flask, jsonify, render_template, request, url_for app = Flask('namuhub') @app.route('/', methods=['GET']) def index(): return render_template('index.html') @app.route('/<user>', methods=['GET']) def index_user(user=''): return render_template('index.html', **{'user': user}) @app.route('/', methods=['POST']) def namu(): user = request.POST.get('user', None) if not user: return '', 501 <commit_msg>Return namu.wiki contribution data as JSON<commit_after>"""namuhub --- namu.wiki contribution graph""" import time from collections import defaultdict from datetime import timedelta from flask import Flask, jsonify, render_template, request, url_for from namuhub import namu as namuwiki app = Flask('namuhub') @app.route('/', methods=['GET']) def index(): return render_template('index.html') @app.route('/<user>', methods=['GET']) def index_user(user=''): return render_template('index.html', **{'user': user}) @app.route('/', methods=['POST']) def namu(): user = request.form.get('user', None) if not user: return jsonify({}), 501 contribs = namuwiki.contrib(user) data = defaultdict(lambda: []) # First, separate contributions into list by their activity date for contrib in contribs: date = (contrib.when - timedelta(hours=9)).date().strftime('%Y-%m-%d') data[date].append(contrib) # Convert defaultdict to dict # However, this may be inefficient but I don't care about performance at this point because it doesn't matter while it's a small project data = dict(data) # Next, we should serialize it as dict object to make sure that all the values are JSON serialiable for key, value in data.items(): value = [c.as_dict() for c in value] # Almost done, fix timezone and convert its date property to unix timestamp number that can be parsed by javascript's date object for i, c in enumerate(value): value[i]['when'] = int(time.mktime((c['when'] + timedelta(hours=9)).timetuple())) * 1000 # Overwrite existing value data[key] = value return jsonify(data)
f3978f2bee9fdbef4e2d415e4a6e584e451f4da4
nbtutor/__init__.py
nbtutor/__init__.py
# -*- coding: utf-8 -*- """ nbtutor - a small utility to indicate which cells should be cleared (exercises). """ import os try: from nbconvert.preprocessors.base import Preprocessor except ImportError: from IPython.nbconvert.preprocessors.base import Preprocessor from traitlets import Unicode class ClearExercisePreprocessor(Preprocessor): solutions_dir = Unicode("_solutions").tag(config=True) def __init__(self, **kw): if not os.path.exists(self.solutions_dir): os.makedirs(self.solutions_dir) self.solution_count = 1 super(Preprocessor, self).__init__(**kw) def preprocess_cell(self, cell, resources, index): if 'clear_cell' in cell.metadata and cell.metadata.clear_cell: fname = os.path.join( self.solutions_dir, resources['metadata']['name'] + str(self.solution_count) + '.py') with open(fname, 'w') as f: f.write(cell['source']) cell['source'] = ["# %load {0}".format(fname)] cell['outputs'] = [] # cell['source'] = [] self.solution_count += 1 return cell, resources
# -*- coding: utf-8 -*- """ nbtutor - a small utility to indicate which cells should be cleared (exercises). """ import os try: from nbconvert.preprocessors.base import Preprocessor except ImportError: from IPython.nbconvert.preprocessors.base import Preprocessor from traitlets import Unicode class ClearExercisePreprocessor(Preprocessor): solutions_dir = Unicode("_solutions").tag(config=True) def __init__(self, **kw): if not os.path.exists(self.solutions_dir): os.makedirs(self.solutions_dir) self.solution_count = 1 super(Preprocessor, self).__init__(**kw) def preprocess_cell(self, cell, resources, index): if 'tags' in cell.metadata and 'nbtutor-solution' in cell.metadata.tags: fname = os.path.join( self.solutions_dir, resources['metadata']['name'] + str(self.solution_count) + '.py') with open(fname, 'w') as f: f.write(cell['source']) cell['source'] = ["# %load {0}".format(fname)] cell['outputs'] = [] # cell['source'] = [] self.solution_count += 1 return cell, resources
Update to use tags instead of custom metadata
Update to use tags instead of custom metadata
Python
bsd-2-clause
jorisvandenbossche/nbtutor,jorisvandenbossche/nbtutor
# -*- coding: utf-8 -*- """ nbtutor - a small utility to indicate which cells should be cleared (exercises). """ import os try: from nbconvert.preprocessors.base import Preprocessor except ImportError: from IPython.nbconvert.preprocessors.base import Preprocessor from traitlets import Unicode class ClearExercisePreprocessor(Preprocessor): solutions_dir = Unicode("_solutions").tag(config=True) def __init__(self, **kw): if not os.path.exists(self.solutions_dir): os.makedirs(self.solutions_dir) self.solution_count = 1 super(Preprocessor, self).__init__(**kw) def preprocess_cell(self, cell, resources, index): if 'clear_cell' in cell.metadata and cell.metadata.clear_cell: fname = os.path.join( self.solutions_dir, resources['metadata']['name'] + str(self.solution_count) + '.py') with open(fname, 'w') as f: f.write(cell['source']) cell['source'] = ["# %load {0}".format(fname)] cell['outputs'] = [] # cell['source'] = [] self.solution_count += 1 return cell, resources Update to use tags instead of custom metadata
# -*- coding: utf-8 -*- """ nbtutor - a small utility to indicate which cells should be cleared (exercises). """ import os try: from nbconvert.preprocessors.base import Preprocessor except ImportError: from IPython.nbconvert.preprocessors.base import Preprocessor from traitlets import Unicode class ClearExercisePreprocessor(Preprocessor): solutions_dir = Unicode("_solutions").tag(config=True) def __init__(self, **kw): if not os.path.exists(self.solutions_dir): os.makedirs(self.solutions_dir) self.solution_count = 1 super(Preprocessor, self).__init__(**kw) def preprocess_cell(self, cell, resources, index): if 'tags' in cell.metadata and 'nbtutor-solution' in cell.metadata.tags: fname = os.path.join( self.solutions_dir, resources['metadata']['name'] + str(self.solution_count) + '.py') with open(fname, 'w') as f: f.write(cell['source']) cell['source'] = ["# %load {0}".format(fname)] cell['outputs'] = [] # cell['source'] = [] self.solution_count += 1 return cell, resources
<commit_before># -*- coding: utf-8 -*- """ nbtutor - a small utility to indicate which cells should be cleared (exercises). """ import os try: from nbconvert.preprocessors.base import Preprocessor except ImportError: from IPython.nbconvert.preprocessors.base import Preprocessor from traitlets import Unicode class ClearExercisePreprocessor(Preprocessor): solutions_dir = Unicode("_solutions").tag(config=True) def __init__(self, **kw): if not os.path.exists(self.solutions_dir): os.makedirs(self.solutions_dir) self.solution_count = 1 super(Preprocessor, self).__init__(**kw) def preprocess_cell(self, cell, resources, index): if 'clear_cell' in cell.metadata and cell.metadata.clear_cell: fname = os.path.join( self.solutions_dir, resources['metadata']['name'] + str(self.solution_count) + '.py') with open(fname, 'w') as f: f.write(cell['source']) cell['source'] = ["# %load {0}".format(fname)] cell['outputs'] = [] # cell['source'] = [] self.solution_count += 1 return cell, resources <commit_msg>Update to use tags instead of custom metadata<commit_after>
# -*- coding: utf-8 -*- """ nbtutor - a small utility to indicate which cells should be cleared (exercises). """ import os try: from nbconvert.preprocessors.base import Preprocessor except ImportError: from IPython.nbconvert.preprocessors.base import Preprocessor from traitlets import Unicode class ClearExercisePreprocessor(Preprocessor): solutions_dir = Unicode("_solutions").tag(config=True) def __init__(self, **kw): if not os.path.exists(self.solutions_dir): os.makedirs(self.solutions_dir) self.solution_count = 1 super(Preprocessor, self).__init__(**kw) def preprocess_cell(self, cell, resources, index): if 'tags' in cell.metadata and 'nbtutor-solution' in cell.metadata.tags: fname = os.path.join( self.solutions_dir, resources['metadata']['name'] + str(self.solution_count) + '.py') with open(fname, 'w') as f: f.write(cell['source']) cell['source'] = ["# %load {0}".format(fname)] cell['outputs'] = [] # cell['source'] = [] self.solution_count += 1 return cell, resources
# -*- coding: utf-8 -*- """ nbtutor - a small utility to indicate which cells should be cleared (exercises). """ import os try: from nbconvert.preprocessors.base import Preprocessor except ImportError: from IPython.nbconvert.preprocessors.base import Preprocessor from traitlets import Unicode class ClearExercisePreprocessor(Preprocessor): solutions_dir = Unicode("_solutions").tag(config=True) def __init__(self, **kw): if not os.path.exists(self.solutions_dir): os.makedirs(self.solutions_dir) self.solution_count = 1 super(Preprocessor, self).__init__(**kw) def preprocess_cell(self, cell, resources, index): if 'clear_cell' in cell.metadata and cell.metadata.clear_cell: fname = os.path.join( self.solutions_dir, resources['metadata']['name'] + str(self.solution_count) + '.py') with open(fname, 'w') as f: f.write(cell['source']) cell['source'] = ["# %load {0}".format(fname)] cell['outputs'] = [] # cell['source'] = [] self.solution_count += 1 return cell, resources Update to use tags instead of custom metadata# -*- coding: utf-8 -*- """ nbtutor - a small utility to indicate which cells should be cleared (exercises). """ import os try: from nbconvert.preprocessors.base import Preprocessor except ImportError: from IPython.nbconvert.preprocessors.base import Preprocessor from traitlets import Unicode class ClearExercisePreprocessor(Preprocessor): solutions_dir = Unicode("_solutions").tag(config=True) def __init__(self, **kw): if not os.path.exists(self.solutions_dir): os.makedirs(self.solutions_dir) self.solution_count = 1 super(Preprocessor, self).__init__(**kw) def preprocess_cell(self, cell, resources, index): if 'tags' in cell.metadata and 'nbtutor-solution' in cell.metadata.tags: fname = os.path.join( self.solutions_dir, resources['metadata']['name'] + str(self.solution_count) + '.py') with open(fname, 'w') as f: f.write(cell['source']) cell['source'] = ["# %load {0}".format(fname)] cell['outputs'] = [] # cell['source'] = [] self.solution_count += 1 return cell, resources
<commit_before># -*- coding: utf-8 -*- """ nbtutor - a small utility to indicate which cells should be cleared (exercises). """ import os try: from nbconvert.preprocessors.base import Preprocessor except ImportError: from IPython.nbconvert.preprocessors.base import Preprocessor from traitlets import Unicode class ClearExercisePreprocessor(Preprocessor): solutions_dir = Unicode("_solutions").tag(config=True) def __init__(self, **kw): if not os.path.exists(self.solutions_dir): os.makedirs(self.solutions_dir) self.solution_count = 1 super(Preprocessor, self).__init__(**kw) def preprocess_cell(self, cell, resources, index): if 'clear_cell' in cell.metadata and cell.metadata.clear_cell: fname = os.path.join( self.solutions_dir, resources['metadata']['name'] + str(self.solution_count) + '.py') with open(fname, 'w') as f: f.write(cell['source']) cell['source'] = ["# %load {0}".format(fname)] cell['outputs'] = [] # cell['source'] = [] self.solution_count += 1 return cell, resources <commit_msg>Update to use tags instead of custom metadata<commit_after># -*- coding: utf-8 -*- """ nbtutor - a small utility to indicate which cells should be cleared (exercises). """ import os try: from nbconvert.preprocessors.base import Preprocessor except ImportError: from IPython.nbconvert.preprocessors.base import Preprocessor from traitlets import Unicode class ClearExercisePreprocessor(Preprocessor): solutions_dir = Unicode("_solutions").tag(config=True) def __init__(self, **kw): if not os.path.exists(self.solutions_dir): os.makedirs(self.solutions_dir) self.solution_count = 1 super(Preprocessor, self).__init__(**kw) def preprocess_cell(self, cell, resources, index): if 'tags' in cell.metadata and 'nbtutor-solution' in cell.metadata.tags: fname = os.path.join( self.solutions_dir, resources['metadata']['name'] + str(self.solution_count) + '.py') with open(fname, 'w') as f: f.write(cell['source']) cell['source'] = ["# %load {0}".format(fname)] cell['outputs'] = [] # cell['source'] = [] self.solution_count += 1 return cell, resources
b7c0f274b227acad4d4b76e619a75ef7ac252732
tests/test_base.py
tests/test_base.py
from unittest import TestCase, main from antfarm import App, Response from antfarm.response import STATUS BASE_ENV = { 'REQUEST_METHOD': 'GET', } class AppTest(TestCase): def test_001_basic(self): app = App(root_view=lambda r: Response('true')) def start_response(s, h): self.assertEqual(s, '200 OK') self.assertTrue(any(h[0] == 'Content-Type' for h in h)) resp = app(BASE_ENV, start_response) self.assertEqual(resp, [b'true']) if __name__ == '__main__': main()
from unittest import TestCase, main from antfarm import App, Response from antfarm.response import STATUS BASE_ENV = { 'REQUEST_METHOD': 'GET', } class AppTest(TestCase): def test_001_basic(self): app = App(root_view=lambda r: Response('true')) def start_response(s, h): self.assertEqual(s, '200 OK') self.assertTrue(any(h[0] == 'Content-Type' for h in h)) resp = app(BASE_ENV, start_response) self.assertEqual(list(resp), [b'true']) if __name__ == '__main__': main()
Update test now that response is iterable
Update test now that response is iterable
Python
mit
funkybob/antfarm
from unittest import TestCase, main from antfarm import App, Response from antfarm.response import STATUS BASE_ENV = { 'REQUEST_METHOD': 'GET', } class AppTest(TestCase): def test_001_basic(self): app = App(root_view=lambda r: Response('true')) def start_response(s, h): self.assertEqual(s, '200 OK') self.assertTrue(any(h[0] == 'Content-Type' for h in h)) resp = app(BASE_ENV, start_response) self.assertEqual(resp, [b'true']) if __name__ == '__main__': main() Update test now that response is iterable
from unittest import TestCase, main from antfarm import App, Response from antfarm.response import STATUS BASE_ENV = { 'REQUEST_METHOD': 'GET', } class AppTest(TestCase): def test_001_basic(self): app = App(root_view=lambda r: Response('true')) def start_response(s, h): self.assertEqual(s, '200 OK') self.assertTrue(any(h[0] == 'Content-Type' for h in h)) resp = app(BASE_ENV, start_response) self.assertEqual(list(resp), [b'true']) if __name__ == '__main__': main()
<commit_before> from unittest import TestCase, main from antfarm import App, Response from antfarm.response import STATUS BASE_ENV = { 'REQUEST_METHOD': 'GET', } class AppTest(TestCase): def test_001_basic(self): app = App(root_view=lambda r: Response('true')) def start_response(s, h): self.assertEqual(s, '200 OK') self.assertTrue(any(h[0] == 'Content-Type' for h in h)) resp = app(BASE_ENV, start_response) self.assertEqual(resp, [b'true']) if __name__ == '__main__': main() <commit_msg>Update test now that response is iterable<commit_after>
from unittest import TestCase, main from antfarm import App, Response from antfarm.response import STATUS BASE_ENV = { 'REQUEST_METHOD': 'GET', } class AppTest(TestCase): def test_001_basic(self): app = App(root_view=lambda r: Response('true')) def start_response(s, h): self.assertEqual(s, '200 OK') self.assertTrue(any(h[0] == 'Content-Type' for h in h)) resp = app(BASE_ENV, start_response) self.assertEqual(list(resp), [b'true']) if __name__ == '__main__': main()
from unittest import TestCase, main from antfarm import App, Response from antfarm.response import STATUS BASE_ENV = { 'REQUEST_METHOD': 'GET', } class AppTest(TestCase): def test_001_basic(self): app = App(root_view=lambda r: Response('true')) def start_response(s, h): self.assertEqual(s, '200 OK') self.assertTrue(any(h[0] == 'Content-Type' for h in h)) resp = app(BASE_ENV, start_response) self.assertEqual(resp, [b'true']) if __name__ == '__main__': main() Update test now that response is iterable from unittest import TestCase, main from antfarm import App, Response from antfarm.response import STATUS BASE_ENV = { 'REQUEST_METHOD': 'GET', } class AppTest(TestCase): def test_001_basic(self): app = App(root_view=lambda r: Response('true')) def start_response(s, h): self.assertEqual(s, '200 OK') self.assertTrue(any(h[0] == 'Content-Type' for h in h)) resp = app(BASE_ENV, start_response) self.assertEqual(list(resp), [b'true']) if __name__ == '__main__': main()
<commit_before> from unittest import TestCase, main from antfarm import App, Response from antfarm.response import STATUS BASE_ENV = { 'REQUEST_METHOD': 'GET', } class AppTest(TestCase): def test_001_basic(self): app = App(root_view=lambda r: Response('true')) def start_response(s, h): self.assertEqual(s, '200 OK') self.assertTrue(any(h[0] == 'Content-Type' for h in h)) resp = app(BASE_ENV, start_response) self.assertEqual(resp, [b'true']) if __name__ == '__main__': main() <commit_msg>Update test now that response is iterable<commit_after> from unittest import TestCase, main from antfarm import App, Response from antfarm.response import STATUS BASE_ENV = { 'REQUEST_METHOD': 'GET', } class AppTest(TestCase): def test_001_basic(self): app = App(root_view=lambda r: Response('true')) def start_response(s, h): self.assertEqual(s, '200 OK') self.assertTrue(any(h[0] == 'Content-Type' for h in h)) resp = app(BASE_ENV, start_response) self.assertEqual(list(resp), [b'true']) if __name__ == '__main__': main()
89422fb5aaa10a99b3d9d0e576551fdd4d111a27
tests/registryd/test_registry_startup.py
tests/registryd/test_registry_startup.py
PROPERTIES_IFACE = 'org.freedesktop.DBus.Properties' ACCESSIBLE_IFACE = 'org.a11y.atspi.Accessible' def get_property(proxy, iface_name, prop_name): return proxy.Get(iface_name, prop_name, dbus_interface=PROPERTIES_IFACE) def test_accessible_iface_properties(registry, session_manager): values = [ ('Name', 'main'), ('Description', ''), ] for prop_name, expected in values: assert get_property(registry, ACCESSIBLE_IFACE, prop_name) == expected
PROPERTIES_IFACE = 'org.freedesktop.DBus.Properties' ACCESSIBLE_IFACE = 'org.a11y.atspi.Accessible' def get_property(proxy, iface_name, prop_name): return proxy.Get(iface_name, prop_name, dbus_interface=PROPERTIES_IFACE) def test_accessible_iface_properties(registry, session_manager): values = [ ('Name', 'main'), ('Description', ''), ] for prop_name, expected in values: assert get_property(registry, ACCESSIBLE_IFACE, prop_name) == expected def test_empty_registry_has_zero_children(registry, session_manager): assert get_property(registry, ACCESSIBLE_IFACE, 'ChildCount') == 0
Test ChildCount on an empty registry
Test ChildCount on an empty registry
Python
lgpl-2.1
GNOME/at-spi2-core,GNOME/at-spi2-core,GNOME/at-spi2-core
PROPERTIES_IFACE = 'org.freedesktop.DBus.Properties' ACCESSIBLE_IFACE = 'org.a11y.atspi.Accessible' def get_property(proxy, iface_name, prop_name): return proxy.Get(iface_name, prop_name, dbus_interface=PROPERTIES_IFACE) def test_accessible_iface_properties(registry, session_manager): values = [ ('Name', 'main'), ('Description', ''), ] for prop_name, expected in values: assert get_property(registry, ACCESSIBLE_IFACE, prop_name) == expected Test ChildCount on an empty registry
PROPERTIES_IFACE = 'org.freedesktop.DBus.Properties' ACCESSIBLE_IFACE = 'org.a11y.atspi.Accessible' def get_property(proxy, iface_name, prop_name): return proxy.Get(iface_name, prop_name, dbus_interface=PROPERTIES_IFACE) def test_accessible_iface_properties(registry, session_manager): values = [ ('Name', 'main'), ('Description', ''), ] for prop_name, expected in values: assert get_property(registry, ACCESSIBLE_IFACE, prop_name) == expected def test_empty_registry_has_zero_children(registry, session_manager): assert get_property(registry, ACCESSIBLE_IFACE, 'ChildCount') == 0
<commit_before>PROPERTIES_IFACE = 'org.freedesktop.DBus.Properties' ACCESSIBLE_IFACE = 'org.a11y.atspi.Accessible' def get_property(proxy, iface_name, prop_name): return proxy.Get(iface_name, prop_name, dbus_interface=PROPERTIES_IFACE) def test_accessible_iface_properties(registry, session_manager): values = [ ('Name', 'main'), ('Description', ''), ] for prop_name, expected in values: assert get_property(registry, ACCESSIBLE_IFACE, prop_name) == expected <commit_msg>Test ChildCount on an empty registry<commit_after>
PROPERTIES_IFACE = 'org.freedesktop.DBus.Properties' ACCESSIBLE_IFACE = 'org.a11y.atspi.Accessible' def get_property(proxy, iface_name, prop_name): return proxy.Get(iface_name, prop_name, dbus_interface=PROPERTIES_IFACE) def test_accessible_iface_properties(registry, session_manager): values = [ ('Name', 'main'), ('Description', ''), ] for prop_name, expected in values: assert get_property(registry, ACCESSIBLE_IFACE, prop_name) == expected def test_empty_registry_has_zero_children(registry, session_manager): assert get_property(registry, ACCESSIBLE_IFACE, 'ChildCount') == 0
PROPERTIES_IFACE = 'org.freedesktop.DBus.Properties' ACCESSIBLE_IFACE = 'org.a11y.atspi.Accessible' def get_property(proxy, iface_name, prop_name): return proxy.Get(iface_name, prop_name, dbus_interface=PROPERTIES_IFACE) def test_accessible_iface_properties(registry, session_manager): values = [ ('Name', 'main'), ('Description', ''), ] for prop_name, expected in values: assert get_property(registry, ACCESSIBLE_IFACE, prop_name) == expected Test ChildCount on an empty registryPROPERTIES_IFACE = 'org.freedesktop.DBus.Properties' ACCESSIBLE_IFACE = 'org.a11y.atspi.Accessible' def get_property(proxy, iface_name, prop_name): return proxy.Get(iface_name, prop_name, dbus_interface=PROPERTIES_IFACE) def test_accessible_iface_properties(registry, session_manager): values = [ ('Name', 'main'), ('Description', ''), ] for prop_name, expected in values: assert get_property(registry, ACCESSIBLE_IFACE, prop_name) == expected def test_empty_registry_has_zero_children(registry, session_manager): assert get_property(registry, ACCESSIBLE_IFACE, 'ChildCount') == 0
<commit_before>PROPERTIES_IFACE = 'org.freedesktop.DBus.Properties' ACCESSIBLE_IFACE = 'org.a11y.atspi.Accessible' def get_property(proxy, iface_name, prop_name): return proxy.Get(iface_name, prop_name, dbus_interface=PROPERTIES_IFACE) def test_accessible_iface_properties(registry, session_manager): values = [ ('Name', 'main'), ('Description', ''), ] for prop_name, expected in values: assert get_property(registry, ACCESSIBLE_IFACE, prop_name) == expected <commit_msg>Test ChildCount on an empty registry<commit_after>PROPERTIES_IFACE = 'org.freedesktop.DBus.Properties' ACCESSIBLE_IFACE = 'org.a11y.atspi.Accessible' def get_property(proxy, iface_name, prop_name): return proxy.Get(iface_name, prop_name, dbus_interface=PROPERTIES_IFACE) def test_accessible_iface_properties(registry, session_manager): values = [ ('Name', 'main'), ('Description', ''), ] for prop_name, expected in values: assert get_property(registry, ACCESSIBLE_IFACE, prop_name) == expected def test_empty_registry_has_zero_children(registry, session_manager): assert get_property(registry, ACCESSIBLE_IFACE, 'ChildCount') == 0
a0bb9cbcb2999d06747dec78b4959baad8d374d8
organizer/models.py
organizer/models.py
from django.db import models # Model Field Reference # https://docs.djangoproject.com/en/1.8/ref/models/fields/ class Tag(models.Model): name = models.CharField(max_length=31) slug = models.SlugField() class Startup(models.Model): name = models.CharField(max_length=31) slug = models.SlugField() description = models.TextField() founded_date = models.DateField() contact = models.EmailField() website = models.URLField() class NewsLink(models.Model): title = models.CharField(max_length=63) pub_date = models.DateField() link = models.URLField()
from django.db import models # Model Field Reference # https://docs.djangoproject.com/en/1.8/ref/models/fields/ class Tag(models.Model): name = models.CharField(max_length=31) slug = models.SlugField() class Startup(models.Model): name = models.CharField(max_length=31) slug = models.SlugField() description = models.TextField() founded_date = models.DateField() contact = models.EmailField() website = models.URLField() class NewsLink(models.Model): title = models.CharField(max_length=63) pub_date = models.DateField() link = models.URLField() startup = models.ForeignKey(Startup)
Define NewsLink model related fields.
Ch03: Define NewsLink model related fields. [skip ci] https://docs.djangoproject.com/en/1.8/ref/models/fields/#foreignkey The NewsLink model now has a ForeignKey pointing to the Startup model. External news articles may thus only point to a single startup business, but any of our startup businesses may have multiple articles written about it.
Python
bsd-2-clause
jambonrose/DjangoUnleashed-1.8,jambonrose/DjangoUnleashed-1.8
from django.db import models # Model Field Reference # https://docs.djangoproject.com/en/1.8/ref/models/fields/ class Tag(models.Model): name = models.CharField(max_length=31) slug = models.SlugField() class Startup(models.Model): name = models.CharField(max_length=31) slug = models.SlugField() description = models.TextField() founded_date = models.DateField() contact = models.EmailField() website = models.URLField() class NewsLink(models.Model): title = models.CharField(max_length=63) pub_date = models.DateField() link = models.URLField() Ch03: Define NewsLink model related fields. [skip ci] https://docs.djangoproject.com/en/1.8/ref/models/fields/#foreignkey The NewsLink model now has a ForeignKey pointing to the Startup model. External news articles may thus only point to a single startup business, but any of our startup businesses may have multiple articles written about it.
from django.db import models # Model Field Reference # https://docs.djangoproject.com/en/1.8/ref/models/fields/ class Tag(models.Model): name = models.CharField(max_length=31) slug = models.SlugField() class Startup(models.Model): name = models.CharField(max_length=31) slug = models.SlugField() description = models.TextField() founded_date = models.DateField() contact = models.EmailField() website = models.URLField() class NewsLink(models.Model): title = models.CharField(max_length=63) pub_date = models.DateField() link = models.URLField() startup = models.ForeignKey(Startup)
<commit_before>from django.db import models # Model Field Reference # https://docs.djangoproject.com/en/1.8/ref/models/fields/ class Tag(models.Model): name = models.CharField(max_length=31) slug = models.SlugField() class Startup(models.Model): name = models.CharField(max_length=31) slug = models.SlugField() description = models.TextField() founded_date = models.DateField() contact = models.EmailField() website = models.URLField() class NewsLink(models.Model): title = models.CharField(max_length=63) pub_date = models.DateField() link = models.URLField() <commit_msg>Ch03: Define NewsLink model related fields. [skip ci] https://docs.djangoproject.com/en/1.8/ref/models/fields/#foreignkey The NewsLink model now has a ForeignKey pointing to the Startup model. External news articles may thus only point to a single startup business, but any of our startup businesses may have multiple articles written about it.<commit_after>
from django.db import models # Model Field Reference # https://docs.djangoproject.com/en/1.8/ref/models/fields/ class Tag(models.Model): name = models.CharField(max_length=31) slug = models.SlugField() class Startup(models.Model): name = models.CharField(max_length=31) slug = models.SlugField() description = models.TextField() founded_date = models.DateField() contact = models.EmailField() website = models.URLField() class NewsLink(models.Model): title = models.CharField(max_length=63) pub_date = models.DateField() link = models.URLField() startup = models.ForeignKey(Startup)
from django.db import models # Model Field Reference # https://docs.djangoproject.com/en/1.8/ref/models/fields/ class Tag(models.Model): name = models.CharField(max_length=31) slug = models.SlugField() class Startup(models.Model): name = models.CharField(max_length=31) slug = models.SlugField() description = models.TextField() founded_date = models.DateField() contact = models.EmailField() website = models.URLField() class NewsLink(models.Model): title = models.CharField(max_length=63) pub_date = models.DateField() link = models.URLField() Ch03: Define NewsLink model related fields. [skip ci] https://docs.djangoproject.com/en/1.8/ref/models/fields/#foreignkey The NewsLink model now has a ForeignKey pointing to the Startup model. External news articles may thus only point to a single startup business, but any of our startup businesses may have multiple articles written about it.from django.db import models # Model Field Reference # https://docs.djangoproject.com/en/1.8/ref/models/fields/ class Tag(models.Model): name = models.CharField(max_length=31) slug = models.SlugField() class Startup(models.Model): name = models.CharField(max_length=31) slug = models.SlugField() description = models.TextField() founded_date = models.DateField() contact = models.EmailField() website = models.URLField() class NewsLink(models.Model): title = models.CharField(max_length=63) pub_date = models.DateField() link = models.URLField() startup = models.ForeignKey(Startup)
<commit_before>from django.db import models # Model Field Reference # https://docs.djangoproject.com/en/1.8/ref/models/fields/ class Tag(models.Model): name = models.CharField(max_length=31) slug = models.SlugField() class Startup(models.Model): name = models.CharField(max_length=31) slug = models.SlugField() description = models.TextField() founded_date = models.DateField() contact = models.EmailField() website = models.URLField() class NewsLink(models.Model): title = models.CharField(max_length=63) pub_date = models.DateField() link = models.URLField() <commit_msg>Ch03: Define NewsLink model related fields. [skip ci] https://docs.djangoproject.com/en/1.8/ref/models/fields/#foreignkey The NewsLink model now has a ForeignKey pointing to the Startup model. External news articles may thus only point to a single startup business, but any of our startup businesses may have multiple articles written about it.<commit_after>from django.db import models # Model Field Reference # https://docs.djangoproject.com/en/1.8/ref/models/fields/ class Tag(models.Model): name = models.CharField(max_length=31) slug = models.SlugField() class Startup(models.Model): name = models.CharField(max_length=31) slug = models.SlugField() description = models.TextField() founded_date = models.DateField() contact = models.EmailField() website = models.URLField() class NewsLink(models.Model): title = models.CharField(max_length=63) pub_date = models.DateField() link = models.URLField() startup = models.ForeignKey(Startup)
1090ecf891dd7c0928cdaae385464d3be660fdbf
penn/base.py
penn/base.py
from requests import get class WrapperBase(object): def __init__(self, bearer, token): self.bearer = bearer self.token = token @property def headers(self): """The HTTP headers needed for signed requests""" return { "Authorization-Bearer": self.bearer, "Authorization-Token": self.token, } def _request(self, url, params=None): """Make a signed request to the API, raise any API errors, and returning a tuple of (data, metadata)""" response = get(url, params=params, headers=self.headers).json() if response['service_meta']['error_text']: raise ValueError(response['service_meta']['error_text']) return response
from requests import get class WrapperBase(object): def __init__(self, bearer, token): self.bearer = bearer self.token = token @property def headers(self): """The HTTP headers needed for signed requests""" return { "Authorization-Bearer": self.bearer, "Authorization-Token": self.token, } def _request(self, url, params=None): """Make a signed request to the API, raise any API errors, and returning a tuple of (data, metadata)""" response = get(url, params=params, headers=self.headers) if response.status_code != 200: raise ValueError('Request to {} returned {}'.format(response.url, response.status_code)) response = response.json() if response['service_meta']['error_text']: raise ValueError(response['service_meta']['error_text']) return response
Add better error handling for non-200 responses
Add better error handling for non-200 responses
Python
mit
pennlabs/penn-sdk-python,pennlabs/penn-sdk-python
from requests import get class WrapperBase(object): def __init__(self, bearer, token): self.bearer = bearer self.token = token @property def headers(self): """The HTTP headers needed for signed requests""" return { "Authorization-Bearer": self.bearer, "Authorization-Token": self.token, } def _request(self, url, params=None): """Make a signed request to the API, raise any API errors, and returning a tuple of (data, metadata)""" response = get(url, params=params, headers=self.headers).json() if response['service_meta']['error_text']: raise ValueError(response['service_meta']['error_text']) return response Add better error handling for non-200 responses
from requests import get class WrapperBase(object): def __init__(self, bearer, token): self.bearer = bearer self.token = token @property def headers(self): """The HTTP headers needed for signed requests""" return { "Authorization-Bearer": self.bearer, "Authorization-Token": self.token, } def _request(self, url, params=None): """Make a signed request to the API, raise any API errors, and returning a tuple of (data, metadata)""" response = get(url, params=params, headers=self.headers) if response.status_code != 200: raise ValueError('Request to {} returned {}'.format(response.url, response.status_code)) response = response.json() if response['service_meta']['error_text']: raise ValueError(response['service_meta']['error_text']) return response
<commit_before>from requests import get class WrapperBase(object): def __init__(self, bearer, token): self.bearer = bearer self.token = token @property def headers(self): """The HTTP headers needed for signed requests""" return { "Authorization-Bearer": self.bearer, "Authorization-Token": self.token, } def _request(self, url, params=None): """Make a signed request to the API, raise any API errors, and returning a tuple of (data, metadata)""" response = get(url, params=params, headers=self.headers).json() if response['service_meta']['error_text']: raise ValueError(response['service_meta']['error_text']) return response <commit_msg>Add better error handling for non-200 responses<commit_after>
from requests import get class WrapperBase(object): def __init__(self, bearer, token): self.bearer = bearer self.token = token @property def headers(self): """The HTTP headers needed for signed requests""" return { "Authorization-Bearer": self.bearer, "Authorization-Token": self.token, } def _request(self, url, params=None): """Make a signed request to the API, raise any API errors, and returning a tuple of (data, metadata)""" response = get(url, params=params, headers=self.headers) if response.status_code != 200: raise ValueError('Request to {} returned {}'.format(response.url, response.status_code)) response = response.json() if response['service_meta']['error_text']: raise ValueError(response['service_meta']['error_text']) return response
from requests import get class WrapperBase(object): def __init__(self, bearer, token): self.bearer = bearer self.token = token @property def headers(self): """The HTTP headers needed for signed requests""" return { "Authorization-Bearer": self.bearer, "Authorization-Token": self.token, } def _request(self, url, params=None): """Make a signed request to the API, raise any API errors, and returning a tuple of (data, metadata)""" response = get(url, params=params, headers=self.headers).json() if response['service_meta']['error_text']: raise ValueError(response['service_meta']['error_text']) return response Add better error handling for non-200 responsesfrom requests import get class WrapperBase(object): def __init__(self, bearer, token): self.bearer = bearer self.token = token @property def headers(self): """The HTTP headers needed for signed requests""" return { "Authorization-Bearer": self.bearer, "Authorization-Token": self.token, } def _request(self, url, params=None): """Make a signed request to the API, raise any API errors, and returning a tuple of (data, metadata)""" response = get(url, params=params, headers=self.headers) if response.status_code != 200: raise ValueError('Request to {} returned {}'.format(response.url, response.status_code)) response = response.json() if response['service_meta']['error_text']: raise ValueError(response['service_meta']['error_text']) return response
<commit_before>from requests import get class WrapperBase(object): def __init__(self, bearer, token): self.bearer = bearer self.token = token @property def headers(self): """The HTTP headers needed for signed requests""" return { "Authorization-Bearer": self.bearer, "Authorization-Token": self.token, } def _request(self, url, params=None): """Make a signed request to the API, raise any API errors, and returning a tuple of (data, metadata)""" response = get(url, params=params, headers=self.headers).json() if response['service_meta']['error_text']: raise ValueError(response['service_meta']['error_text']) return response <commit_msg>Add better error handling for non-200 responses<commit_after>from requests import get class WrapperBase(object): def __init__(self, bearer, token): self.bearer = bearer self.token = token @property def headers(self): """The HTTP headers needed for signed requests""" return { "Authorization-Bearer": self.bearer, "Authorization-Token": self.token, } def _request(self, url, params=None): """Make a signed request to the API, raise any API errors, and returning a tuple of (data, metadata)""" response = get(url, params=params, headers=self.headers) if response.status_code != 200: raise ValueError('Request to {} returned {}'.format(response.url, response.status_code)) response = response.json() if response['service_meta']['error_text']: raise ValueError(response['service_meta']['error_text']) return response
4ee3900c8ac78c8ed1d0145f9d99a0485b542141
senic_hub/backend/views/setup_config.py
senic_hub/backend/views/setup_config.py
from cornice.service import Service from ..commands import create_configuration_files_and_restart_apps_ from ..config import path configuration_service = Service( name='configuration_create', path=path('setup/config'), renderer='json', accept='application/json', ) @configuration_service.post() def configuration_create_view(request): create_configuration_files_and_restart_apps_(request.registry.settings)
from cornice.service import Service from ..commands import create_configuration_files_and_restart_apps_ from ..config import path from ..supervisor import get_supervisor_rpc_client, stop_program configuration_service = Service( name='configuration_create', path=path('setup/config'), renderer='json', accept='application/json', ) @configuration_service.post() def configuration_create_view(request): create_configuration_files_and_restart_apps_(request.registry.settings) # stop device discovery daemon supervisorctl = get_supervisor_rpc_client() stop_program('device_discovery', supervisorctl)
Stop device discovery after onboarding
Stop device discovery after onboarding
Python
mit
grunskis/nuimo-hub-backend,grunskis/senic-hub,grunskis/nuimo-hub-backend,grunskis/nuimo-hub-backend,getsenic/senic-hub,grunskis/senic-hub,grunskis/senic-hub,grunskis/senic-hub,grunskis/nuimo-hub-backend,getsenic/senic-hub,grunskis/nuimo-hub-backend,grunskis/senic-hub,grunskis/senic-hub
from cornice.service import Service from ..commands import create_configuration_files_and_restart_apps_ from ..config import path configuration_service = Service( name='configuration_create', path=path('setup/config'), renderer='json', accept='application/json', ) @configuration_service.post() def configuration_create_view(request): create_configuration_files_and_restart_apps_(request.registry.settings) Stop device discovery after onboarding
from cornice.service import Service from ..commands import create_configuration_files_and_restart_apps_ from ..config import path from ..supervisor import get_supervisor_rpc_client, stop_program configuration_service = Service( name='configuration_create', path=path('setup/config'), renderer='json', accept='application/json', ) @configuration_service.post() def configuration_create_view(request): create_configuration_files_and_restart_apps_(request.registry.settings) # stop device discovery daemon supervisorctl = get_supervisor_rpc_client() stop_program('device_discovery', supervisorctl)
<commit_before>from cornice.service import Service from ..commands import create_configuration_files_and_restart_apps_ from ..config import path configuration_service = Service( name='configuration_create', path=path('setup/config'), renderer='json', accept='application/json', ) @configuration_service.post() def configuration_create_view(request): create_configuration_files_and_restart_apps_(request.registry.settings) <commit_msg>Stop device discovery after onboarding<commit_after>
from cornice.service import Service from ..commands import create_configuration_files_and_restart_apps_ from ..config import path from ..supervisor import get_supervisor_rpc_client, stop_program configuration_service = Service( name='configuration_create', path=path('setup/config'), renderer='json', accept='application/json', ) @configuration_service.post() def configuration_create_view(request): create_configuration_files_and_restart_apps_(request.registry.settings) # stop device discovery daemon supervisorctl = get_supervisor_rpc_client() stop_program('device_discovery', supervisorctl)
from cornice.service import Service from ..commands import create_configuration_files_and_restart_apps_ from ..config import path configuration_service = Service( name='configuration_create', path=path('setup/config'), renderer='json', accept='application/json', ) @configuration_service.post() def configuration_create_view(request): create_configuration_files_and_restart_apps_(request.registry.settings) Stop device discovery after onboardingfrom cornice.service import Service from ..commands import create_configuration_files_and_restart_apps_ from ..config import path from ..supervisor import get_supervisor_rpc_client, stop_program configuration_service = Service( name='configuration_create', path=path('setup/config'), renderer='json', accept='application/json', ) @configuration_service.post() def configuration_create_view(request): create_configuration_files_and_restart_apps_(request.registry.settings) # stop device discovery daemon supervisorctl = get_supervisor_rpc_client() stop_program('device_discovery', supervisorctl)
<commit_before>from cornice.service import Service from ..commands import create_configuration_files_and_restart_apps_ from ..config import path configuration_service = Service( name='configuration_create', path=path('setup/config'), renderer='json', accept='application/json', ) @configuration_service.post() def configuration_create_view(request): create_configuration_files_and_restart_apps_(request.registry.settings) <commit_msg>Stop device discovery after onboarding<commit_after>from cornice.service import Service from ..commands import create_configuration_files_and_restart_apps_ from ..config import path from ..supervisor import get_supervisor_rpc_client, stop_program configuration_service = Service( name='configuration_create', path=path('setup/config'), renderer='json', accept='application/json', ) @configuration_service.post() def configuration_create_view(request): create_configuration_files_and_restart_apps_(request.registry.settings) # stop device discovery daemon supervisorctl = get_supervisor_rpc_client() stop_program('device_discovery', supervisorctl)
608298a3bed65a36312500f15d58ac6c3cd6663d
pybeam/beam_file.py
pybeam/beam_file.py
from beam_construct import beam class BeamFile(object): def __init__(self, filename): self._tree = beam.parse(file(filename,"r").read()) def selectChunkByName(self, name): for c in self._tree.chunk: if c.chunk_name == name: return c raise KeyError(name) @property def atoms(self): return self.selectChunkByName("Atom").payload.atom
from beam_construct import beam class BeamFile(object): def __init__(self, filename): self._tree = beam.parse(file(filename,"r").read()) def selectChunkByName(self, name): for c in self._tree.chunk: if c.chunk_name == name: return c raise KeyError(name) @property def atoms(self): return self.selectChunkByName("Atom").payload.atom @property def exports(self): expt = self.selectChunkByName("ExpT") atoms = self.atoms return [(atoms[e.function], e.arity, e.label) for e in expt.payload.entry] @property def imports(self): impt = self.selectChunkByName("ImpT") atoms = self.atoms return [(atoms[e.module], atoms[e.function], e.arity) for e in impt.payload.entry]
Add @property exports Add @property imports
Add @property exports Add @property imports
Python
mit
matwey/pybeam
from beam_construct import beam class BeamFile(object): def __init__(self, filename): self._tree = beam.parse(file(filename,"r").read()) def selectChunkByName(self, name): for c in self._tree.chunk: if c.chunk_name == name: return c raise KeyError(name) @property def atoms(self): return self.selectChunkByName("Atom").payload.atom Add @property exports Add @property imports
from beam_construct import beam class BeamFile(object): def __init__(self, filename): self._tree = beam.parse(file(filename,"r").read()) def selectChunkByName(self, name): for c in self._tree.chunk: if c.chunk_name == name: return c raise KeyError(name) @property def atoms(self): return self.selectChunkByName("Atom").payload.atom @property def exports(self): expt = self.selectChunkByName("ExpT") atoms = self.atoms return [(atoms[e.function], e.arity, e.label) for e in expt.payload.entry] @property def imports(self): impt = self.selectChunkByName("ImpT") atoms = self.atoms return [(atoms[e.module], atoms[e.function], e.arity) for e in impt.payload.entry]
<commit_before>from beam_construct import beam class BeamFile(object): def __init__(self, filename): self._tree = beam.parse(file(filename,"r").read()) def selectChunkByName(self, name): for c in self._tree.chunk: if c.chunk_name == name: return c raise KeyError(name) @property def atoms(self): return self.selectChunkByName("Atom").payload.atom <commit_msg>Add @property exports Add @property imports<commit_after>
from beam_construct import beam class BeamFile(object): def __init__(self, filename): self._tree = beam.parse(file(filename,"r").read()) def selectChunkByName(self, name): for c in self._tree.chunk: if c.chunk_name == name: return c raise KeyError(name) @property def atoms(self): return self.selectChunkByName("Atom").payload.atom @property def exports(self): expt = self.selectChunkByName("ExpT") atoms = self.atoms return [(atoms[e.function], e.arity, e.label) for e in expt.payload.entry] @property def imports(self): impt = self.selectChunkByName("ImpT") atoms = self.atoms return [(atoms[e.module], atoms[e.function], e.arity) for e in impt.payload.entry]
from beam_construct import beam class BeamFile(object): def __init__(self, filename): self._tree = beam.parse(file(filename,"r").read()) def selectChunkByName(self, name): for c in self._tree.chunk: if c.chunk_name == name: return c raise KeyError(name) @property def atoms(self): return self.selectChunkByName("Atom").payload.atom Add @property exports Add @property importsfrom beam_construct import beam class BeamFile(object): def __init__(self, filename): self._tree = beam.parse(file(filename,"r").read()) def selectChunkByName(self, name): for c in self._tree.chunk: if c.chunk_name == name: return c raise KeyError(name) @property def atoms(self): return self.selectChunkByName("Atom").payload.atom @property def exports(self): expt = self.selectChunkByName("ExpT") atoms = self.atoms return [(atoms[e.function], e.arity, e.label) for e in expt.payload.entry] @property def imports(self): impt = self.selectChunkByName("ImpT") atoms = self.atoms return [(atoms[e.module], atoms[e.function], e.arity) for e in impt.payload.entry]
<commit_before>from beam_construct import beam class BeamFile(object): def __init__(self, filename): self._tree = beam.parse(file(filename,"r").read()) def selectChunkByName(self, name): for c in self._tree.chunk: if c.chunk_name == name: return c raise KeyError(name) @property def atoms(self): return self.selectChunkByName("Atom").payload.atom <commit_msg>Add @property exports Add @property imports<commit_after>from beam_construct import beam class BeamFile(object): def __init__(self, filename): self._tree = beam.parse(file(filename,"r").read()) def selectChunkByName(self, name): for c in self._tree.chunk: if c.chunk_name == name: return c raise KeyError(name) @property def atoms(self): return self.selectChunkByName("Atom").payload.atom @property def exports(self): expt = self.selectChunkByName("ExpT") atoms = self.atoms return [(atoms[e.function], e.arity, e.label) for e in expt.payload.entry] @property def imports(self): impt = self.selectChunkByName("ImpT") atoms = self.atoms return [(atoms[e.module], atoms[e.function], e.arity) for e in impt.payload.entry]
164e4b5f02fbe9558e9fa50b12e7b28921f5be9b
wxGestalt.py
wxGestalt.py
# -*- coding: utf-8 -*- import wx import wxClass class wxGestaltApp(wxClass.MyFrame1): def __init__(self, *args, **kw): super(wxGestaltApp, self).__init__(*args, **kw) self.InitUI() def InitUI(self): self.Show() def On_Quit( self, event ): self.Close(True) def On_ScanSerialPort( self, event ): event.Skip() if __name__ == '__main__': ex = wx.App() ex1 = wxGestaltApp(None) ex1.Show() ex.MainLoop()
# -*- coding: utf-8 -*- # Modules # Modules for the wx Gui import wx import wxClass # Modules for the serial communication import serial import glob # Variables # Current global setting for the Serial port in use SerialPortInUse = "" # Functions def ScanSerialPorts(): # Scan for available ports. return a list of device names. return glob.glob('/dev/ttyACM*') + glob.glob('/dev/ttyS*') + glob.glob('/dev/ttyUSB*') + glob.glob('/dev/tty*') # Classes # The class for the main app class wxGestaltApp(wxClass.MyFrame1): def __init__(self, *args, **kw): super(wxGestaltApp, self).__init__(*args, **kw) self.InitUI() def InitUI(self): self.Show() def On_Quit( self, event ): self.Close(True) def On_ScanSerialPort( self, event ): # looks for available serial ports SerialPortsAvailable = ScanSerialPorts() global SerialPortInUse # Global variable that can be accessed by the whole program dlg = wx.SingleChoiceDialog(self, 'Choose the serial port for your machine: ', 'Serial port settings', SerialPortsAvailable, wx.CHOICEDLG_STYLE) if dlg.ShowModal() == wx.ID_OK: SerialPortInUse = dlg.GetStringSelection() print SerialPortInUse dlg.Destroy() if __name__ == '__main__': ex = wx.App() ex1 = wxGestaltApp(None) ex1.Show() ex.MainLoop()
Add the functionality for choosing the serial port
Add the functionality for choosing the serial port
Python
mit
openp2pdesign/wxGestalt
# -*- coding: utf-8 -*- import wx import wxClass class wxGestaltApp(wxClass.MyFrame1): def __init__(self, *args, **kw): super(wxGestaltApp, self).__init__(*args, **kw) self.InitUI() def InitUI(self): self.Show() def On_Quit( self, event ): self.Close(True) def On_ScanSerialPort( self, event ): event.Skip() if __name__ == '__main__': ex = wx.App() ex1 = wxGestaltApp(None) ex1.Show() ex.MainLoop() Add the functionality for choosing the serial port
# -*- coding: utf-8 -*- # Modules # Modules for the wx Gui import wx import wxClass # Modules for the serial communication import serial import glob # Variables # Current global setting for the Serial port in use SerialPortInUse = "" # Functions def ScanSerialPorts(): # Scan for available ports. return a list of device names. return glob.glob('/dev/ttyACM*') + glob.glob('/dev/ttyS*') + glob.glob('/dev/ttyUSB*') + glob.glob('/dev/tty*') # Classes # The class for the main app class wxGestaltApp(wxClass.MyFrame1): def __init__(self, *args, **kw): super(wxGestaltApp, self).__init__(*args, **kw) self.InitUI() def InitUI(self): self.Show() def On_Quit( self, event ): self.Close(True) def On_ScanSerialPort( self, event ): # looks for available serial ports SerialPortsAvailable = ScanSerialPorts() global SerialPortInUse # Global variable that can be accessed by the whole program dlg = wx.SingleChoiceDialog(self, 'Choose the serial port for your machine: ', 'Serial port settings', SerialPortsAvailable, wx.CHOICEDLG_STYLE) if dlg.ShowModal() == wx.ID_OK: SerialPortInUse = dlg.GetStringSelection() print SerialPortInUse dlg.Destroy() if __name__ == '__main__': ex = wx.App() ex1 = wxGestaltApp(None) ex1.Show() ex.MainLoop()
<commit_before># -*- coding: utf-8 -*- import wx import wxClass class wxGestaltApp(wxClass.MyFrame1): def __init__(self, *args, **kw): super(wxGestaltApp, self).__init__(*args, **kw) self.InitUI() def InitUI(self): self.Show() def On_Quit( self, event ): self.Close(True) def On_ScanSerialPort( self, event ): event.Skip() if __name__ == '__main__': ex = wx.App() ex1 = wxGestaltApp(None) ex1.Show() ex.MainLoop() <commit_msg>Add the functionality for choosing the serial port<commit_after>
# -*- coding: utf-8 -*- # Modules # Modules for the wx Gui import wx import wxClass # Modules for the serial communication import serial import glob # Variables # Current global setting for the Serial port in use SerialPortInUse = "" # Functions def ScanSerialPorts(): # Scan for available ports. return a list of device names. return glob.glob('/dev/ttyACM*') + glob.glob('/dev/ttyS*') + glob.glob('/dev/ttyUSB*') + glob.glob('/dev/tty*') # Classes # The class for the main app class wxGestaltApp(wxClass.MyFrame1): def __init__(self, *args, **kw): super(wxGestaltApp, self).__init__(*args, **kw) self.InitUI() def InitUI(self): self.Show() def On_Quit( self, event ): self.Close(True) def On_ScanSerialPort( self, event ): # looks for available serial ports SerialPortsAvailable = ScanSerialPorts() global SerialPortInUse # Global variable that can be accessed by the whole program dlg = wx.SingleChoiceDialog(self, 'Choose the serial port for your machine: ', 'Serial port settings', SerialPortsAvailable, wx.CHOICEDLG_STYLE) if dlg.ShowModal() == wx.ID_OK: SerialPortInUse = dlg.GetStringSelection() print SerialPortInUse dlg.Destroy() if __name__ == '__main__': ex = wx.App() ex1 = wxGestaltApp(None) ex1.Show() ex.MainLoop()
# -*- coding: utf-8 -*- import wx import wxClass class wxGestaltApp(wxClass.MyFrame1): def __init__(self, *args, **kw): super(wxGestaltApp, self).__init__(*args, **kw) self.InitUI() def InitUI(self): self.Show() def On_Quit( self, event ): self.Close(True) def On_ScanSerialPort( self, event ): event.Skip() if __name__ == '__main__': ex = wx.App() ex1 = wxGestaltApp(None) ex1.Show() ex.MainLoop() Add the functionality for choosing the serial port# -*- coding: utf-8 -*- # Modules # Modules for the wx Gui import wx import wxClass # Modules for the serial communication import serial import glob # Variables # Current global setting for the Serial port in use SerialPortInUse = "" # Functions def ScanSerialPorts(): # Scan for available ports. return a list of device names. return glob.glob('/dev/ttyACM*') + glob.glob('/dev/ttyS*') + glob.glob('/dev/ttyUSB*') + glob.glob('/dev/tty*') # Classes # The class for the main app class wxGestaltApp(wxClass.MyFrame1): def __init__(self, *args, **kw): super(wxGestaltApp, self).__init__(*args, **kw) self.InitUI() def InitUI(self): self.Show() def On_Quit( self, event ): self.Close(True) def On_ScanSerialPort( self, event ): # looks for available serial ports SerialPortsAvailable = ScanSerialPorts() global SerialPortInUse # Global variable that can be accessed by the whole program dlg = wx.SingleChoiceDialog(self, 'Choose the serial port for your machine: ', 'Serial port settings', SerialPortsAvailable, wx.CHOICEDLG_STYLE) if dlg.ShowModal() == wx.ID_OK: SerialPortInUse = dlg.GetStringSelection() print SerialPortInUse dlg.Destroy() if __name__ == '__main__': ex = wx.App() ex1 = wxGestaltApp(None) ex1.Show() ex.MainLoop()
<commit_before># -*- coding: utf-8 -*- import wx import wxClass class wxGestaltApp(wxClass.MyFrame1): def __init__(self, *args, **kw): super(wxGestaltApp, self).__init__(*args, **kw) self.InitUI() def InitUI(self): self.Show() def On_Quit( self, event ): self.Close(True) def On_ScanSerialPort( self, event ): event.Skip() if __name__ == '__main__': ex = wx.App() ex1 = wxGestaltApp(None) ex1.Show() ex.MainLoop() <commit_msg>Add the functionality for choosing the serial port<commit_after># -*- coding: utf-8 -*- # Modules # Modules for the wx Gui import wx import wxClass # Modules for the serial communication import serial import glob # Variables # Current global setting for the Serial port in use SerialPortInUse = "" # Functions def ScanSerialPorts(): # Scan for available ports. return a list of device names. return glob.glob('/dev/ttyACM*') + glob.glob('/dev/ttyS*') + glob.glob('/dev/ttyUSB*') + glob.glob('/dev/tty*') # Classes # The class for the main app class wxGestaltApp(wxClass.MyFrame1): def __init__(self, *args, **kw): super(wxGestaltApp, self).__init__(*args, **kw) self.InitUI() def InitUI(self): self.Show() def On_Quit( self, event ): self.Close(True) def On_ScanSerialPort( self, event ): # looks for available serial ports SerialPortsAvailable = ScanSerialPorts() global SerialPortInUse # Global variable that can be accessed by the whole program dlg = wx.SingleChoiceDialog(self, 'Choose the serial port for your machine: ', 'Serial port settings', SerialPortsAvailable, wx.CHOICEDLG_STYLE) if dlg.ShowModal() == wx.ID_OK: SerialPortInUse = dlg.GetStringSelection() print SerialPortInUse dlg.Destroy() if __name__ == '__main__': ex = wx.App() ex1 = wxGestaltApp(None) ex1.Show() ex.MainLoop()
2e23898ea287b6b9efcf6bcb8758cf61fca25256
rest/serializers.py
rest/serializers.py
# Author: Braedy Kuzma from rest_framework import serializers from dash.models import Post, Author, Comment, Category class AuthorSerializer(serializers.ModelSerializer): class Meta: model = Author fields = ('id', 'host', 'url') def to_representation(self, author): rv = serializers.ModelSerializer.to_representation(self, author) rv['displayName'] = author.user.get_username() return rv class CategorySerializer(serializers.BaseSerializer): def to_representation(self, category): return category.category class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = '__all__' author = AuthorSerializer() def to_representation(self, post): rv = serializers.ModelSerializer.to_representation(self, post) categories = Category.objects.filter(post=post) catSer = CategorySerializer(categories, many=True) rv['categories'] = catSer.data # The source and the origin is the same as the id -- so says the Hindle rv['source'] = rv['id'] rv['origin'] = rv['id'] return rv class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = ('author', 'comment', 'contentType', 'published', 'id') author = AuthorSerializer()
# Author: Braedy Kuzma from rest_framework import serializers from dash.models import Post, Author, Comment, Category class AuthorSerializer(serializers.ModelSerializer): class Meta: model = Author fields = ('id', 'host', 'url', 'github') def to_representation(self, author): rv = serializers.ModelSerializer.to_representation(self, author) rv['displayName'] = author.user.get_username() return rv class CategorySerializer(serializers.BaseSerializer): def to_representation(self, category): return category.category class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = '__all__' author = AuthorSerializer() def to_representation(self, post): rv = serializers.ModelSerializer.to_representation(self, post) categories = Category.objects.filter(post=post) catSer = CategorySerializer(categories, many=True) rv['categories'] = catSer.data # The source and the origin is the same as the id -- so says the Hindle rv['source'] = rv['id'] rv['origin'] = rv['id'] return rv class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = ('author', 'comment', 'contentType', 'published', 'id') author = AuthorSerializer()
Add missing github field to Author serializer.
Add missing github field to Author serializer.
Python
apache-2.0
CMPUT404W17T06/CMPUT404-project,CMPUT404W17T06/CMPUT404-project,CMPUT404W17T06/CMPUT404-project
# Author: Braedy Kuzma from rest_framework import serializers from dash.models import Post, Author, Comment, Category class AuthorSerializer(serializers.ModelSerializer): class Meta: model = Author fields = ('id', 'host', 'url') def to_representation(self, author): rv = serializers.ModelSerializer.to_representation(self, author) rv['displayName'] = author.user.get_username() return rv class CategorySerializer(serializers.BaseSerializer): def to_representation(self, category): return category.category class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = '__all__' author = AuthorSerializer() def to_representation(self, post): rv = serializers.ModelSerializer.to_representation(self, post) categories = Category.objects.filter(post=post) catSer = CategorySerializer(categories, many=True) rv['categories'] = catSer.data # The source and the origin is the same as the id -- so says the Hindle rv['source'] = rv['id'] rv['origin'] = rv['id'] return rv class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = ('author', 'comment', 'contentType', 'published', 'id') author = AuthorSerializer() Add missing github field to Author serializer.
# Author: Braedy Kuzma from rest_framework import serializers from dash.models import Post, Author, Comment, Category class AuthorSerializer(serializers.ModelSerializer): class Meta: model = Author fields = ('id', 'host', 'url', 'github') def to_representation(self, author): rv = serializers.ModelSerializer.to_representation(self, author) rv['displayName'] = author.user.get_username() return rv class CategorySerializer(serializers.BaseSerializer): def to_representation(self, category): return category.category class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = '__all__' author = AuthorSerializer() def to_representation(self, post): rv = serializers.ModelSerializer.to_representation(self, post) categories = Category.objects.filter(post=post) catSer = CategorySerializer(categories, many=True) rv['categories'] = catSer.data # The source and the origin is the same as the id -- so says the Hindle rv['source'] = rv['id'] rv['origin'] = rv['id'] return rv class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = ('author', 'comment', 'contentType', 'published', 'id') author = AuthorSerializer()
<commit_before># Author: Braedy Kuzma from rest_framework import serializers from dash.models import Post, Author, Comment, Category class AuthorSerializer(serializers.ModelSerializer): class Meta: model = Author fields = ('id', 'host', 'url') def to_representation(self, author): rv = serializers.ModelSerializer.to_representation(self, author) rv['displayName'] = author.user.get_username() return rv class CategorySerializer(serializers.BaseSerializer): def to_representation(self, category): return category.category class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = '__all__' author = AuthorSerializer() def to_representation(self, post): rv = serializers.ModelSerializer.to_representation(self, post) categories = Category.objects.filter(post=post) catSer = CategorySerializer(categories, many=True) rv['categories'] = catSer.data # The source and the origin is the same as the id -- so says the Hindle rv['source'] = rv['id'] rv['origin'] = rv['id'] return rv class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = ('author', 'comment', 'contentType', 'published', 'id') author = AuthorSerializer() <commit_msg>Add missing github field to Author serializer.<commit_after>
# Author: Braedy Kuzma from rest_framework import serializers from dash.models import Post, Author, Comment, Category class AuthorSerializer(serializers.ModelSerializer): class Meta: model = Author fields = ('id', 'host', 'url', 'github') def to_representation(self, author): rv = serializers.ModelSerializer.to_representation(self, author) rv['displayName'] = author.user.get_username() return rv class CategorySerializer(serializers.BaseSerializer): def to_representation(self, category): return category.category class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = '__all__' author = AuthorSerializer() def to_representation(self, post): rv = serializers.ModelSerializer.to_representation(self, post) categories = Category.objects.filter(post=post) catSer = CategorySerializer(categories, many=True) rv['categories'] = catSer.data # The source and the origin is the same as the id -- so says the Hindle rv['source'] = rv['id'] rv['origin'] = rv['id'] return rv class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = ('author', 'comment', 'contentType', 'published', 'id') author = AuthorSerializer()
# Author: Braedy Kuzma from rest_framework import serializers from dash.models import Post, Author, Comment, Category class AuthorSerializer(serializers.ModelSerializer): class Meta: model = Author fields = ('id', 'host', 'url') def to_representation(self, author): rv = serializers.ModelSerializer.to_representation(self, author) rv['displayName'] = author.user.get_username() return rv class CategorySerializer(serializers.BaseSerializer): def to_representation(self, category): return category.category class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = '__all__' author = AuthorSerializer() def to_representation(self, post): rv = serializers.ModelSerializer.to_representation(self, post) categories = Category.objects.filter(post=post) catSer = CategorySerializer(categories, many=True) rv['categories'] = catSer.data # The source and the origin is the same as the id -- so says the Hindle rv['source'] = rv['id'] rv['origin'] = rv['id'] return rv class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = ('author', 'comment', 'contentType', 'published', 'id') author = AuthorSerializer() Add missing github field to Author serializer.# Author: Braedy Kuzma from rest_framework import serializers from dash.models import Post, Author, Comment, Category class AuthorSerializer(serializers.ModelSerializer): class Meta: model = Author fields = ('id', 'host', 'url', 'github') def to_representation(self, author): rv = serializers.ModelSerializer.to_representation(self, author) rv['displayName'] = author.user.get_username() return rv class CategorySerializer(serializers.BaseSerializer): def to_representation(self, category): return category.category class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = '__all__' author = AuthorSerializer() def to_representation(self, post): rv = serializers.ModelSerializer.to_representation(self, post) categories = Category.objects.filter(post=post) catSer = CategorySerializer(categories, many=True) rv['categories'] = catSer.data # The source and the origin is the same as the id -- so says the Hindle rv['source'] = rv['id'] rv['origin'] = rv['id'] return rv class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = ('author', 'comment', 'contentType', 'published', 'id') author = AuthorSerializer()
<commit_before># Author: Braedy Kuzma from rest_framework import serializers from dash.models import Post, Author, Comment, Category class AuthorSerializer(serializers.ModelSerializer): class Meta: model = Author fields = ('id', 'host', 'url') def to_representation(self, author): rv = serializers.ModelSerializer.to_representation(self, author) rv['displayName'] = author.user.get_username() return rv class CategorySerializer(serializers.BaseSerializer): def to_representation(self, category): return category.category class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = '__all__' author = AuthorSerializer() def to_representation(self, post): rv = serializers.ModelSerializer.to_representation(self, post) categories = Category.objects.filter(post=post) catSer = CategorySerializer(categories, many=True) rv['categories'] = catSer.data # The source and the origin is the same as the id -- so says the Hindle rv['source'] = rv['id'] rv['origin'] = rv['id'] return rv class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = ('author', 'comment', 'contentType', 'published', 'id') author = AuthorSerializer() <commit_msg>Add missing github field to Author serializer.<commit_after># Author: Braedy Kuzma from rest_framework import serializers from dash.models import Post, Author, Comment, Category class AuthorSerializer(serializers.ModelSerializer): class Meta: model = Author fields = ('id', 'host', 'url', 'github') def to_representation(self, author): rv = serializers.ModelSerializer.to_representation(self, author) rv['displayName'] = author.user.get_username() return rv class CategorySerializer(serializers.BaseSerializer): def to_representation(self, category): return category.category class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = '__all__' author = AuthorSerializer() def to_representation(self, post): rv = serializers.ModelSerializer.to_representation(self, post) categories = Category.objects.filter(post=post) catSer = CategorySerializer(categories, many=True) rv['categories'] = catSer.data # The source and the origin is the same as the id -- so says the Hindle rv['source'] = rv['id'] rv['origin'] = rv['id'] return rv class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = ('author', 'comment', 'contentType', 'published', 'id') author = AuthorSerializer()
427b894fdd5690bc7a52dbcea42c4918b87d0046
run_tests.py
run_tests.py
#!/usr/bin/env python3 # Copyright (c) 2013 Spotify AB # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy of # the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. import coverage import sys import unittest import os def main(): #Cleanup old html report: for root, dirs, files in os.walk('test/output_coverage_html/'): for f in files: if f == '.gitignore' or f == '.empty_dir': continue os.unlink(os.path.join(root, f)) for d in dirs: shutil.rmtree(os.path.join(root, d)) #Perform coverage analisys: cov = coverage.coverage() cov.start() #Discover the tests and execute them: loader = unittest.TestLoader() tests = loader.discover('./test/') testRunner = unittest.runner.TextTestRunner(descriptions=True, verbosity=1) testRunner.run(tests) cov.stop() cov.html_report() if __name__ == '__main__': main()
#!/usr/bin/env python3 # Copyright (c) 2013 Spotify AB # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy of # the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. try: import coverage except ImportError: pass import sys import unittest import os def main(): #Cleanup old html report: for root, dirs, files in os.walk('test/output_coverage_html/'): for f in files: if f == '.gitignore' or f == '.empty_dir': continue os.unlink(os.path.join(root, f)) for d in dirs: shutil.rmtree(os.path.join(root, d)) #Perform coverage analisys: if "coverage" in sys.modules: cov = coverage.coverage() cov.start() #Discover the tests and execute them: loader = unittest.TestLoader() tests = loader.discover('./test/') testRunner = unittest.runner.TextTestRunner(descriptions=True, verbosity=1) testRunner.run(tests) if "coverage" in sys.modules: cov.stop() cov.html_report() if __name__ == '__main__': main()
Make coverage module optional during test run
Make coverage module optional during test run Change-Id: I79f767a90a84c7b482e0cc9acd311619611802e9
Python
apache-2.0
brainly/check-growth
#!/usr/bin/env python3 # Copyright (c) 2013 Spotify AB # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy of # the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. import coverage import sys import unittest import os def main(): #Cleanup old html report: for root, dirs, files in os.walk('test/output_coverage_html/'): for f in files: if f == '.gitignore' or f == '.empty_dir': continue os.unlink(os.path.join(root, f)) for d in dirs: shutil.rmtree(os.path.join(root, d)) #Perform coverage analisys: cov = coverage.coverage() cov.start() #Discover the tests and execute them: loader = unittest.TestLoader() tests = loader.discover('./test/') testRunner = unittest.runner.TextTestRunner(descriptions=True, verbosity=1) testRunner.run(tests) cov.stop() cov.html_report() if __name__ == '__main__': main() Make coverage module optional during test run Change-Id: I79f767a90a84c7b482e0cc9acd311619611802e9
#!/usr/bin/env python3 # Copyright (c) 2013 Spotify AB # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy of # the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. try: import coverage except ImportError: pass import sys import unittest import os def main(): #Cleanup old html report: for root, dirs, files in os.walk('test/output_coverage_html/'): for f in files: if f == '.gitignore' or f == '.empty_dir': continue os.unlink(os.path.join(root, f)) for d in dirs: shutil.rmtree(os.path.join(root, d)) #Perform coverage analisys: if "coverage" in sys.modules: cov = coverage.coverage() cov.start() #Discover the tests and execute them: loader = unittest.TestLoader() tests = loader.discover('./test/') testRunner = unittest.runner.TextTestRunner(descriptions=True, verbosity=1) testRunner.run(tests) if "coverage" in sys.modules: cov.stop() cov.html_report() if __name__ == '__main__': main()
<commit_before>#!/usr/bin/env python3 # Copyright (c) 2013 Spotify AB # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy of # the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. import coverage import sys import unittest import os def main(): #Cleanup old html report: for root, dirs, files in os.walk('test/output_coverage_html/'): for f in files: if f == '.gitignore' or f == '.empty_dir': continue os.unlink(os.path.join(root, f)) for d in dirs: shutil.rmtree(os.path.join(root, d)) #Perform coverage analisys: cov = coverage.coverage() cov.start() #Discover the tests and execute them: loader = unittest.TestLoader() tests = loader.discover('./test/') testRunner = unittest.runner.TextTestRunner(descriptions=True, verbosity=1) testRunner.run(tests) cov.stop() cov.html_report() if __name__ == '__main__': main() <commit_msg>Make coverage module optional during test run Change-Id: I79f767a90a84c7b482e0cc9acd311619611802e9<commit_after>
#!/usr/bin/env python3 # Copyright (c) 2013 Spotify AB # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy of # the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. try: import coverage except ImportError: pass import sys import unittest import os def main(): #Cleanup old html report: for root, dirs, files in os.walk('test/output_coverage_html/'): for f in files: if f == '.gitignore' or f == '.empty_dir': continue os.unlink(os.path.join(root, f)) for d in dirs: shutil.rmtree(os.path.join(root, d)) #Perform coverage analisys: if "coverage" in sys.modules: cov = coverage.coverage() cov.start() #Discover the tests and execute them: loader = unittest.TestLoader() tests = loader.discover('./test/') testRunner = unittest.runner.TextTestRunner(descriptions=True, verbosity=1) testRunner.run(tests) if "coverage" in sys.modules: cov.stop() cov.html_report() if __name__ == '__main__': main()
#!/usr/bin/env python3 # Copyright (c) 2013 Spotify AB # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy of # the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. import coverage import sys import unittest import os def main(): #Cleanup old html report: for root, dirs, files in os.walk('test/output_coverage_html/'): for f in files: if f == '.gitignore' or f == '.empty_dir': continue os.unlink(os.path.join(root, f)) for d in dirs: shutil.rmtree(os.path.join(root, d)) #Perform coverage analisys: cov = coverage.coverage() cov.start() #Discover the tests and execute them: loader = unittest.TestLoader() tests = loader.discover('./test/') testRunner = unittest.runner.TextTestRunner(descriptions=True, verbosity=1) testRunner.run(tests) cov.stop() cov.html_report() if __name__ == '__main__': main() Make coverage module optional during test run Change-Id: I79f767a90a84c7b482e0cc9acd311619611802e9#!/usr/bin/env python3 # Copyright (c) 2013 Spotify AB # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy of # the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. try: import coverage except ImportError: pass import sys import unittest import os def main(): #Cleanup old html report: for root, dirs, files in os.walk('test/output_coverage_html/'): for f in files: if f == '.gitignore' or f == '.empty_dir': continue os.unlink(os.path.join(root, f)) for d in dirs: shutil.rmtree(os.path.join(root, d)) #Perform coverage analisys: if "coverage" in sys.modules: cov = coverage.coverage() cov.start() #Discover the tests and execute them: loader = unittest.TestLoader() tests = loader.discover('./test/') testRunner = unittest.runner.TextTestRunner(descriptions=True, verbosity=1) testRunner.run(tests) if "coverage" in sys.modules: cov.stop() cov.html_report() if __name__ == '__main__': main()
<commit_before>#!/usr/bin/env python3 # Copyright (c) 2013 Spotify AB # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy of # the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. import coverage import sys import unittest import os def main(): #Cleanup old html report: for root, dirs, files in os.walk('test/output_coverage_html/'): for f in files: if f == '.gitignore' or f == '.empty_dir': continue os.unlink(os.path.join(root, f)) for d in dirs: shutil.rmtree(os.path.join(root, d)) #Perform coverage analisys: cov = coverage.coverage() cov.start() #Discover the tests and execute them: loader = unittest.TestLoader() tests = loader.discover('./test/') testRunner = unittest.runner.TextTestRunner(descriptions=True, verbosity=1) testRunner.run(tests) cov.stop() cov.html_report() if __name__ == '__main__': main() <commit_msg>Make coverage module optional during test run Change-Id: I79f767a90a84c7b482e0cc9acd311619611802e9<commit_after>#!/usr/bin/env python3 # Copyright (c) 2013 Spotify AB # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy of # the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. try: import coverage except ImportError: pass import sys import unittest import os def main(): #Cleanup old html report: for root, dirs, files in os.walk('test/output_coverage_html/'): for f in files: if f == '.gitignore' or f == '.empty_dir': continue os.unlink(os.path.join(root, f)) for d in dirs: shutil.rmtree(os.path.join(root, d)) #Perform coverage analisys: if "coverage" in sys.modules: cov = coverage.coverage() cov.start() #Discover the tests and execute them: loader = unittest.TestLoader() tests = loader.discover('./test/') testRunner = unittest.runner.TextTestRunner(descriptions=True, verbosity=1) testRunner.run(tests) if "coverage" in sys.modules: cov.stop() cov.html_report() if __name__ == '__main__': main()
5e1ea27b1334f74dee4f7d3f3823f80037da3690
serrano/cors.py
serrano/cors.py
from warnings import warn from django.conf import settings def patch_response(request, response, methods): if getattr(settings, 'SERRANO_CORS_ENABLED', False): if hasattr(settings, 'SERRANO_CORS_ORIGIN'): warn('SERRANO_CORS_ORIGIN has been deprecated in favor ' 'of SERRANO_CORS_ORIGINS', DeprecationWarning) allowed_origins = [s.strip() for s in settings.SERRANO_CORS_ORIGIN.split(',')] else: allowed_origins = getattr(settings, 'SERRANO_CORS_ORIGINS', ()) origin = request.META.get('HTTP_ORIGIN') if not allowed_origins or origin and origin in allowed_origins: # The origin must be explicitly listed when used with the # Access-Control-Allow-Credentials header # See https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS#Access-Control-Allow-Origin # noqa response['Access-Control-Allow-Origin'] = origin if request.method == 'OPTIONS': response['Access-Control-Allow-Credentials'] = 'true' response['Access-Control-Allow-Methods'] = ', '.join(methods) headers = request.META.get('HTTP_ACCESS_CONTROL_REQUEST_HEADERS') # noqa if headers: response['Access-Control-Allow-Headers'] = headers return response
from warnings import warn from django.conf import settings def patch_response(request, response, methods): if getattr(settings, 'SERRANO_CORS_ENABLED', False): if hasattr(settings, 'SERRANO_CORS_ORIGIN'): warn('SERRANO_CORS_ORIGIN has been deprecated in favor ' 'of SERRANO_CORS_ORIGINS', DeprecationWarning) allowed_origins = [s.strip() for s in settings.SERRANO_CORS_ORIGIN.split(',')] else: allowed_origins = getattr(settings, 'SERRANO_CORS_ORIGINS', ()) origin = request.META.get('HTTP_ORIGIN') if not allowed_origins or origin in allowed_origins: # The origin must be explicitly listed when used with the # Access-Control-Allow-Credentials header # See https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS#Access-Control-Allow-Origin # noqa response['Access-Control-Allow-Origin'] = origin if request.method == 'OPTIONS': response['Access-Control-Allow-Credentials'] = 'true' response['Access-Control-Allow-Methods'] = ', '.join(methods) headers = request.META.get('HTTP_ACCESS_CONTROL_REQUEST_HEADERS') # noqa if headers: response['Access-Control-Allow-Headers'] = headers return response
Remove truth assertion on origin
Remove truth assertion on origin This is a remnant from testing in the SERRANO_CORS_ORIGIN string. Now that the `in` applies to a list, this assertion is no longer needed.
Python
bsd-2-clause
chop-dbhi/serrano,rv816/serrano_night,chop-dbhi/serrano,rv816/serrano_night
from warnings import warn from django.conf import settings def patch_response(request, response, methods): if getattr(settings, 'SERRANO_CORS_ENABLED', False): if hasattr(settings, 'SERRANO_CORS_ORIGIN'): warn('SERRANO_CORS_ORIGIN has been deprecated in favor ' 'of SERRANO_CORS_ORIGINS', DeprecationWarning) allowed_origins = [s.strip() for s in settings.SERRANO_CORS_ORIGIN.split(',')] else: allowed_origins = getattr(settings, 'SERRANO_CORS_ORIGINS', ()) origin = request.META.get('HTTP_ORIGIN') if not allowed_origins or origin and origin in allowed_origins: # The origin must be explicitly listed when used with the # Access-Control-Allow-Credentials header # See https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS#Access-Control-Allow-Origin # noqa response['Access-Control-Allow-Origin'] = origin if request.method == 'OPTIONS': response['Access-Control-Allow-Credentials'] = 'true' response['Access-Control-Allow-Methods'] = ', '.join(methods) headers = request.META.get('HTTP_ACCESS_CONTROL_REQUEST_HEADERS') # noqa if headers: response['Access-Control-Allow-Headers'] = headers return response Remove truth assertion on origin This is a remnant from testing in the SERRANO_CORS_ORIGIN string. Now that the `in` applies to a list, this assertion is no longer needed.
from warnings import warn from django.conf import settings def patch_response(request, response, methods): if getattr(settings, 'SERRANO_CORS_ENABLED', False): if hasattr(settings, 'SERRANO_CORS_ORIGIN'): warn('SERRANO_CORS_ORIGIN has been deprecated in favor ' 'of SERRANO_CORS_ORIGINS', DeprecationWarning) allowed_origins = [s.strip() for s in settings.SERRANO_CORS_ORIGIN.split(',')] else: allowed_origins = getattr(settings, 'SERRANO_CORS_ORIGINS', ()) origin = request.META.get('HTTP_ORIGIN') if not allowed_origins or origin in allowed_origins: # The origin must be explicitly listed when used with the # Access-Control-Allow-Credentials header # See https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS#Access-Control-Allow-Origin # noqa response['Access-Control-Allow-Origin'] = origin if request.method == 'OPTIONS': response['Access-Control-Allow-Credentials'] = 'true' response['Access-Control-Allow-Methods'] = ', '.join(methods) headers = request.META.get('HTTP_ACCESS_CONTROL_REQUEST_HEADERS') # noqa if headers: response['Access-Control-Allow-Headers'] = headers return response
<commit_before>from warnings import warn from django.conf import settings def patch_response(request, response, methods): if getattr(settings, 'SERRANO_CORS_ENABLED', False): if hasattr(settings, 'SERRANO_CORS_ORIGIN'): warn('SERRANO_CORS_ORIGIN has been deprecated in favor ' 'of SERRANO_CORS_ORIGINS', DeprecationWarning) allowed_origins = [s.strip() for s in settings.SERRANO_CORS_ORIGIN.split(',')] else: allowed_origins = getattr(settings, 'SERRANO_CORS_ORIGINS', ()) origin = request.META.get('HTTP_ORIGIN') if not allowed_origins or origin and origin in allowed_origins: # The origin must be explicitly listed when used with the # Access-Control-Allow-Credentials header # See https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS#Access-Control-Allow-Origin # noqa response['Access-Control-Allow-Origin'] = origin if request.method == 'OPTIONS': response['Access-Control-Allow-Credentials'] = 'true' response['Access-Control-Allow-Methods'] = ', '.join(methods) headers = request.META.get('HTTP_ACCESS_CONTROL_REQUEST_HEADERS') # noqa if headers: response['Access-Control-Allow-Headers'] = headers return response <commit_msg>Remove truth assertion on origin This is a remnant from testing in the SERRANO_CORS_ORIGIN string. Now that the `in` applies to a list, this assertion is no longer needed.<commit_after>
from warnings import warn from django.conf import settings def patch_response(request, response, methods): if getattr(settings, 'SERRANO_CORS_ENABLED', False): if hasattr(settings, 'SERRANO_CORS_ORIGIN'): warn('SERRANO_CORS_ORIGIN has been deprecated in favor ' 'of SERRANO_CORS_ORIGINS', DeprecationWarning) allowed_origins = [s.strip() for s in settings.SERRANO_CORS_ORIGIN.split(',')] else: allowed_origins = getattr(settings, 'SERRANO_CORS_ORIGINS', ()) origin = request.META.get('HTTP_ORIGIN') if not allowed_origins or origin in allowed_origins: # The origin must be explicitly listed when used with the # Access-Control-Allow-Credentials header # See https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS#Access-Control-Allow-Origin # noqa response['Access-Control-Allow-Origin'] = origin if request.method == 'OPTIONS': response['Access-Control-Allow-Credentials'] = 'true' response['Access-Control-Allow-Methods'] = ', '.join(methods) headers = request.META.get('HTTP_ACCESS_CONTROL_REQUEST_HEADERS') # noqa if headers: response['Access-Control-Allow-Headers'] = headers return response
from warnings import warn from django.conf import settings def patch_response(request, response, methods): if getattr(settings, 'SERRANO_CORS_ENABLED', False): if hasattr(settings, 'SERRANO_CORS_ORIGIN'): warn('SERRANO_CORS_ORIGIN has been deprecated in favor ' 'of SERRANO_CORS_ORIGINS', DeprecationWarning) allowed_origins = [s.strip() for s in settings.SERRANO_CORS_ORIGIN.split(',')] else: allowed_origins = getattr(settings, 'SERRANO_CORS_ORIGINS', ()) origin = request.META.get('HTTP_ORIGIN') if not allowed_origins or origin and origin in allowed_origins: # The origin must be explicitly listed when used with the # Access-Control-Allow-Credentials header # See https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS#Access-Control-Allow-Origin # noqa response['Access-Control-Allow-Origin'] = origin if request.method == 'OPTIONS': response['Access-Control-Allow-Credentials'] = 'true' response['Access-Control-Allow-Methods'] = ', '.join(methods) headers = request.META.get('HTTP_ACCESS_CONTROL_REQUEST_HEADERS') # noqa if headers: response['Access-Control-Allow-Headers'] = headers return response Remove truth assertion on origin This is a remnant from testing in the SERRANO_CORS_ORIGIN string. Now that the `in` applies to a list, this assertion is no longer needed.from warnings import warn from django.conf import settings def patch_response(request, response, methods): if getattr(settings, 'SERRANO_CORS_ENABLED', False): if hasattr(settings, 'SERRANO_CORS_ORIGIN'): warn('SERRANO_CORS_ORIGIN has been deprecated in favor ' 'of SERRANO_CORS_ORIGINS', DeprecationWarning) allowed_origins = [s.strip() for s in settings.SERRANO_CORS_ORIGIN.split(',')] else: allowed_origins = getattr(settings, 'SERRANO_CORS_ORIGINS', ()) origin = request.META.get('HTTP_ORIGIN') if not allowed_origins or origin in allowed_origins: # The origin must be explicitly listed when used with the # Access-Control-Allow-Credentials header # See https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS#Access-Control-Allow-Origin # noqa response['Access-Control-Allow-Origin'] = origin if request.method == 'OPTIONS': response['Access-Control-Allow-Credentials'] = 'true' response['Access-Control-Allow-Methods'] = ', '.join(methods) headers = request.META.get('HTTP_ACCESS_CONTROL_REQUEST_HEADERS') # noqa if headers: response['Access-Control-Allow-Headers'] = headers return response
<commit_before>from warnings import warn from django.conf import settings def patch_response(request, response, methods): if getattr(settings, 'SERRANO_CORS_ENABLED', False): if hasattr(settings, 'SERRANO_CORS_ORIGIN'): warn('SERRANO_CORS_ORIGIN has been deprecated in favor ' 'of SERRANO_CORS_ORIGINS', DeprecationWarning) allowed_origins = [s.strip() for s in settings.SERRANO_CORS_ORIGIN.split(',')] else: allowed_origins = getattr(settings, 'SERRANO_CORS_ORIGINS', ()) origin = request.META.get('HTTP_ORIGIN') if not allowed_origins or origin and origin in allowed_origins: # The origin must be explicitly listed when used with the # Access-Control-Allow-Credentials header # See https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS#Access-Control-Allow-Origin # noqa response['Access-Control-Allow-Origin'] = origin if request.method == 'OPTIONS': response['Access-Control-Allow-Credentials'] = 'true' response['Access-Control-Allow-Methods'] = ', '.join(methods) headers = request.META.get('HTTP_ACCESS_CONTROL_REQUEST_HEADERS') # noqa if headers: response['Access-Control-Allow-Headers'] = headers return response <commit_msg>Remove truth assertion on origin This is a remnant from testing in the SERRANO_CORS_ORIGIN string. Now that the `in` applies to a list, this assertion is no longer needed.<commit_after>from warnings import warn from django.conf import settings def patch_response(request, response, methods): if getattr(settings, 'SERRANO_CORS_ENABLED', False): if hasattr(settings, 'SERRANO_CORS_ORIGIN'): warn('SERRANO_CORS_ORIGIN has been deprecated in favor ' 'of SERRANO_CORS_ORIGINS', DeprecationWarning) allowed_origins = [s.strip() for s in settings.SERRANO_CORS_ORIGIN.split(',')] else: allowed_origins = getattr(settings, 'SERRANO_CORS_ORIGINS', ()) origin = request.META.get('HTTP_ORIGIN') if not allowed_origins or origin in allowed_origins: # The origin must be explicitly listed when used with the # Access-Control-Allow-Credentials header # See https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS#Access-Control-Allow-Origin # noqa response['Access-Control-Allow-Origin'] = origin if request.method == 'OPTIONS': response['Access-Control-Allow-Credentials'] = 'true' response['Access-Control-Allow-Methods'] = ', '.join(methods) headers = request.META.get('HTTP_ACCESS_CONTROL_REQUEST_HEADERS') # noqa if headers: response['Access-Control-Allow-Headers'] = headers return response
6924b1326b664e405f926c36753192603204034e
salt/modules/nfs.py
salt/modules/nfs.py
''' Module for managing NFS. ''' # Import python libs import logging import salt.utils log = logging.getLogger(__name__) def __virtual__(): ''' Only work on posix-like systems ''' # Disable on these platorms, specific service modules exist: disable = [ 'Windows', ] if not salt.utils.which('showmount'): return False return 'nfs' def list_exports(exports='/etc/exports'): ''' List configured exports CLI Example:: salt '*' nfs.list_exports ''' ret = {} f = open(exports, 'r') for line in f.read().splitlines(): if not line: continue if line.startswith('#'): continue comps = line.split() ret[comps[0]] = {'hosts': [], 'options': []} for perm in comps[1:]: permcomps = perm.split('(') permcomps[1] = permcomps[1].replace(')', '') ret[comps[0]]['hosts'] = permcomps[0].split(',') ret[comps[0]]['options'] = permcomps[1].split(',') f.close() return ret
''' Module for managing NFS. ''' # Import python libs import logging import salt.utils log = logging.getLogger(__name__) def __virtual__(): ''' Only work on posix-like systems ''' # Disable on these platorms, specific service modules exist: disable = [ 'Windows', ] if not salt.utils.which('showmount'): return False return 'nfs' def list_exports(exports='/etc/exports'): ''' List configured exports CLI Example:: salt '*' nfs.list_exports ''' ret = {} f = open(exports, 'r') for line in f.read().splitlines(): if not line: continue if line.startswith('#'): continue comps = line.split() ret[comps[0]] = [] for perm in comps[1:]: permcomps = perm.split('(') permcomps[1] = permcomps[1].replace(')', '') hosts = permcomps[0].split(',') options = permcomps[1].split(',') ret[comps[0]].append({'hosts': hosts, 'options': options}) f.close() return ret
Add multiple permissions to a single export
Add multiple permissions to a single export
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
''' Module for managing NFS. ''' # Import python libs import logging import salt.utils log = logging.getLogger(__name__) def __virtual__(): ''' Only work on posix-like systems ''' # Disable on these platorms, specific service modules exist: disable = [ 'Windows', ] if not salt.utils.which('showmount'): return False return 'nfs' def list_exports(exports='/etc/exports'): ''' List configured exports CLI Example:: salt '*' nfs.list_exports ''' ret = {} f = open(exports, 'r') for line in f.read().splitlines(): if not line: continue if line.startswith('#'): continue comps = line.split() ret[comps[0]] = {'hosts': [], 'options': []} for perm in comps[1:]: permcomps = perm.split('(') permcomps[1] = permcomps[1].replace(')', '') ret[comps[0]]['hosts'] = permcomps[0].split(',') ret[comps[0]]['options'] = permcomps[1].split(',') f.close() return ret Add multiple permissions to a single export
''' Module for managing NFS. ''' # Import python libs import logging import salt.utils log = logging.getLogger(__name__) def __virtual__(): ''' Only work on posix-like systems ''' # Disable on these platorms, specific service modules exist: disable = [ 'Windows', ] if not salt.utils.which('showmount'): return False return 'nfs' def list_exports(exports='/etc/exports'): ''' List configured exports CLI Example:: salt '*' nfs.list_exports ''' ret = {} f = open(exports, 'r') for line in f.read().splitlines(): if not line: continue if line.startswith('#'): continue comps = line.split() ret[comps[0]] = [] for perm in comps[1:]: permcomps = perm.split('(') permcomps[1] = permcomps[1].replace(')', '') hosts = permcomps[0].split(',') options = permcomps[1].split(',') ret[comps[0]].append({'hosts': hosts, 'options': options}) f.close() return ret
<commit_before>''' Module for managing NFS. ''' # Import python libs import logging import salt.utils log = logging.getLogger(__name__) def __virtual__(): ''' Only work on posix-like systems ''' # Disable on these platorms, specific service modules exist: disable = [ 'Windows', ] if not salt.utils.which('showmount'): return False return 'nfs' def list_exports(exports='/etc/exports'): ''' List configured exports CLI Example:: salt '*' nfs.list_exports ''' ret = {} f = open(exports, 'r') for line in f.read().splitlines(): if not line: continue if line.startswith('#'): continue comps = line.split() ret[comps[0]] = {'hosts': [], 'options': []} for perm in comps[1:]: permcomps = perm.split('(') permcomps[1] = permcomps[1].replace(')', '') ret[comps[0]]['hosts'] = permcomps[0].split(',') ret[comps[0]]['options'] = permcomps[1].split(',') f.close() return ret <commit_msg>Add multiple permissions to a single export<commit_after>
''' Module for managing NFS. ''' # Import python libs import logging import salt.utils log = logging.getLogger(__name__) def __virtual__(): ''' Only work on posix-like systems ''' # Disable on these platorms, specific service modules exist: disable = [ 'Windows', ] if not salt.utils.which('showmount'): return False return 'nfs' def list_exports(exports='/etc/exports'): ''' List configured exports CLI Example:: salt '*' nfs.list_exports ''' ret = {} f = open(exports, 'r') for line in f.read().splitlines(): if not line: continue if line.startswith('#'): continue comps = line.split() ret[comps[0]] = [] for perm in comps[1:]: permcomps = perm.split('(') permcomps[1] = permcomps[1].replace(')', '') hosts = permcomps[0].split(',') options = permcomps[1].split(',') ret[comps[0]].append({'hosts': hosts, 'options': options}) f.close() return ret
''' Module for managing NFS. ''' # Import python libs import logging import salt.utils log = logging.getLogger(__name__) def __virtual__(): ''' Only work on posix-like systems ''' # Disable on these platorms, specific service modules exist: disable = [ 'Windows', ] if not salt.utils.which('showmount'): return False return 'nfs' def list_exports(exports='/etc/exports'): ''' List configured exports CLI Example:: salt '*' nfs.list_exports ''' ret = {} f = open(exports, 'r') for line in f.read().splitlines(): if not line: continue if line.startswith('#'): continue comps = line.split() ret[comps[0]] = {'hosts': [], 'options': []} for perm in comps[1:]: permcomps = perm.split('(') permcomps[1] = permcomps[1].replace(')', '') ret[comps[0]]['hosts'] = permcomps[0].split(',') ret[comps[0]]['options'] = permcomps[1].split(',') f.close() return ret Add multiple permissions to a single export''' Module for managing NFS. ''' # Import python libs import logging import salt.utils log = logging.getLogger(__name__) def __virtual__(): ''' Only work on posix-like systems ''' # Disable on these platorms, specific service modules exist: disable = [ 'Windows', ] if not salt.utils.which('showmount'): return False return 'nfs' def list_exports(exports='/etc/exports'): ''' List configured exports CLI Example:: salt '*' nfs.list_exports ''' ret = {} f = open(exports, 'r') for line in f.read().splitlines(): if not line: continue if line.startswith('#'): continue comps = line.split() ret[comps[0]] = [] for perm in comps[1:]: permcomps = perm.split('(') permcomps[1] = permcomps[1].replace(')', '') hosts = permcomps[0].split(',') options = permcomps[1].split(',') ret[comps[0]].append({'hosts': hosts, 'options': options}) f.close() return ret
<commit_before>''' Module for managing NFS. ''' # Import python libs import logging import salt.utils log = logging.getLogger(__name__) def __virtual__(): ''' Only work on posix-like systems ''' # Disable on these platorms, specific service modules exist: disable = [ 'Windows', ] if not salt.utils.which('showmount'): return False return 'nfs' def list_exports(exports='/etc/exports'): ''' List configured exports CLI Example:: salt '*' nfs.list_exports ''' ret = {} f = open(exports, 'r') for line in f.read().splitlines(): if not line: continue if line.startswith('#'): continue comps = line.split() ret[comps[0]] = {'hosts': [], 'options': []} for perm in comps[1:]: permcomps = perm.split('(') permcomps[1] = permcomps[1].replace(')', '') ret[comps[0]]['hosts'] = permcomps[0].split(',') ret[comps[0]]['options'] = permcomps[1].split(',') f.close() return ret <commit_msg>Add multiple permissions to a single export<commit_after>''' Module for managing NFS. ''' # Import python libs import logging import salt.utils log = logging.getLogger(__name__) def __virtual__(): ''' Only work on posix-like systems ''' # Disable on these platorms, specific service modules exist: disable = [ 'Windows', ] if not salt.utils.which('showmount'): return False return 'nfs' def list_exports(exports='/etc/exports'): ''' List configured exports CLI Example:: salt '*' nfs.list_exports ''' ret = {} f = open(exports, 'r') for line in f.read().splitlines(): if not line: continue if line.startswith('#'): continue comps = line.split() ret[comps[0]] = [] for perm in comps[1:]: permcomps = perm.split('(') permcomps[1] = permcomps[1].replace(')', '') hosts = permcomps[0].split(',') options = permcomps[1].split(',') ret[comps[0]].append({'hosts': hosts, 'options': options}) f.close() return ret
7492133cbf46c2bfcf07b18d4d68de896c9eac69
svs_interface.py
svs_interface.py
#!/usr/bin/env python import subprocess from Tkinter import * from tkFileDialog import * import os class GpgApp(object): def __init__(self, master): frame = Frame(master) frame.pack() self.text = Text() self.text.pack() menu = Menu(master) root.config(menu=menu) filemenu = Menu(menu, tearoff=0) menu.add_cascade(label="File", menu=filemenu) filemenu.add_command(label="Open", command=self.filename_open) filemenu.add_separator() filemenu.add_command(label="Exit", command=self.do_exit) def filename_open(self): fin = askopenfilenames() if fin: self.text.insert(END,fin) return fin def do_exit(self): root.destroy() root = Tk() root.title("a simple GnuPG interface") app = GpgApp(root) root.mainloop()
#!/usr/bin/env python import subprocess from Tkinter import * from tkFileDialog import * import os GPG = 'gpg2' SERVER_KEY = '' # replace with gpg key ID of server key class GpgApp(object): def __init__(self, master): frame = Frame(master) frame.pack() self.text = Text() self.text.pack() menu = Menu(master) root.config(menu=menu) filemenu = Menu(menu, tearoff=0) menu.add_cascade(label="File", menu=filemenu) filemenu.add_command(label="Open", command=self.filename_open) filemenu.add_separator() filemenu.add_command(label="Exit", command=self.do_exit) def filename_open(self): fin = askopenfilenames() if fin: self.text.insert(END,fin) return fin def encrypt_file(self, input_file, output_file, recipient): args = [GPG, '--output', output_file, '--recipient', recipient, '-sea', input_file] subprocess.call(args) def do_exit(self): root.destroy() root = Tk() root.title("a simple GnuPG interface") app = GpgApp(root) root.mainloop()
Add method to encrypt files
Add method to encrypt files
Python
agpl-3.0
jrosco/securedrop,heartsucker/securedrop,ehartsuyker/securedrop,chadmiller/securedrop,heartsucker/securedrop,garrettr/securedrop,jaseg/securedrop,chadmiller/securedrop,kelcecil/securedrop,jeann2013/securedrop,ageis/securedrop,harlo/securedrop,jeann2013/securedrop,conorsch/securedrop,conorsch/securedrop,chadmiller/securedrop,chadmiller/securedrop,GabeIsman/securedrop,pwplus/securedrop,jrosco/securedrop,pwplus/securedrop,jeann2013/securedrop,ehartsuyker/securedrop,harlo/securedrop,micahflee/securedrop,ehartsuyker/securedrop,kelcecil/securedrop,GabeIsman/securedrop,ageis/securedrop,pwplus/securedrop,harlo/securedrop,GabeIsman/securedrop,jrosco/securedrop,heartsucker/securedrop,garrettr/securedrop,jrosco/securedrop,harlo/securedrop,heartsucker/securedrop,jaseg/securedrop,ehartsuyker/securedrop,kelcecil/securedrop,jeann2013/securedrop,micahflee/securedrop,pwplus/securedrop,ageis/securedrop,conorsch/securedrop,jaseg/securedrop,conorsch/securedrop,jeann2013/securedrop,harlo/securedrop,jrosco/securedrop,mark-in/securedrop-prov-upstream,jrosco/securedrop,mark-in/securedrop-prov-upstream,pwplus/securedrop,garrettr/securedrop,ageis/securedrop,harlo/securedrop,jaseg/securedrop,GabeIsman/securedrop,ehartsuyker/securedrop,heartsucker/securedrop,kelcecil/securedrop,jaseg/securedrop,GabeIsman/securedrop,ehartsuyker/securedrop,kelcecil/securedrop,jaseg/securedrop,mark-in/securedrop-prov-upstream,garrettr/securedrop,kelcecil/securedrop,chadmiller/securedrop,micahflee/securedrop,pwplus/securedrop,mark-in/securedrop-prov-upstream,jeann2013/securedrop,chadmiller/securedrop,micahflee/securedrop,conorsch/securedrop,GabeIsman/securedrop
#!/usr/bin/env python import subprocess from Tkinter import * from tkFileDialog import * import os class GpgApp(object): def __init__(self, master): frame = Frame(master) frame.pack() self.text = Text() self.text.pack() menu = Menu(master) root.config(menu=menu) filemenu = Menu(menu, tearoff=0) menu.add_cascade(label="File", menu=filemenu) filemenu.add_command(label="Open", command=self.filename_open) filemenu.add_separator() filemenu.add_command(label="Exit", command=self.do_exit) def filename_open(self): fin = askopenfilenames() if fin: self.text.insert(END,fin) return fin def do_exit(self): root.destroy() root = Tk() root.title("a simple GnuPG interface") app = GpgApp(root) root.mainloop() Add method to encrypt files
#!/usr/bin/env python import subprocess from Tkinter import * from tkFileDialog import * import os GPG = 'gpg2' SERVER_KEY = '' # replace with gpg key ID of server key class GpgApp(object): def __init__(self, master): frame = Frame(master) frame.pack() self.text = Text() self.text.pack() menu = Menu(master) root.config(menu=menu) filemenu = Menu(menu, tearoff=0) menu.add_cascade(label="File", menu=filemenu) filemenu.add_command(label="Open", command=self.filename_open) filemenu.add_separator() filemenu.add_command(label="Exit", command=self.do_exit) def filename_open(self): fin = askopenfilenames() if fin: self.text.insert(END,fin) return fin def encrypt_file(self, input_file, output_file, recipient): args = [GPG, '--output', output_file, '--recipient', recipient, '-sea', input_file] subprocess.call(args) def do_exit(self): root.destroy() root = Tk() root.title("a simple GnuPG interface") app = GpgApp(root) root.mainloop()
<commit_before>#!/usr/bin/env python import subprocess from Tkinter import * from tkFileDialog import * import os class GpgApp(object): def __init__(self, master): frame = Frame(master) frame.pack() self.text = Text() self.text.pack() menu = Menu(master) root.config(menu=menu) filemenu = Menu(menu, tearoff=0) menu.add_cascade(label="File", menu=filemenu) filemenu.add_command(label="Open", command=self.filename_open) filemenu.add_separator() filemenu.add_command(label="Exit", command=self.do_exit) def filename_open(self): fin = askopenfilenames() if fin: self.text.insert(END,fin) return fin def do_exit(self): root.destroy() root = Tk() root.title("a simple GnuPG interface") app = GpgApp(root) root.mainloop() <commit_msg>Add method to encrypt files<commit_after>
#!/usr/bin/env python import subprocess from Tkinter import * from tkFileDialog import * import os GPG = 'gpg2' SERVER_KEY = '' # replace with gpg key ID of server key class GpgApp(object): def __init__(self, master): frame = Frame(master) frame.pack() self.text = Text() self.text.pack() menu = Menu(master) root.config(menu=menu) filemenu = Menu(menu, tearoff=0) menu.add_cascade(label="File", menu=filemenu) filemenu.add_command(label="Open", command=self.filename_open) filemenu.add_separator() filemenu.add_command(label="Exit", command=self.do_exit) def filename_open(self): fin = askopenfilenames() if fin: self.text.insert(END,fin) return fin def encrypt_file(self, input_file, output_file, recipient): args = [GPG, '--output', output_file, '--recipient', recipient, '-sea', input_file] subprocess.call(args) def do_exit(self): root.destroy() root = Tk() root.title("a simple GnuPG interface") app = GpgApp(root) root.mainloop()
#!/usr/bin/env python import subprocess from Tkinter import * from tkFileDialog import * import os class GpgApp(object): def __init__(self, master): frame = Frame(master) frame.pack() self.text = Text() self.text.pack() menu = Menu(master) root.config(menu=menu) filemenu = Menu(menu, tearoff=0) menu.add_cascade(label="File", menu=filemenu) filemenu.add_command(label="Open", command=self.filename_open) filemenu.add_separator() filemenu.add_command(label="Exit", command=self.do_exit) def filename_open(self): fin = askopenfilenames() if fin: self.text.insert(END,fin) return fin def do_exit(self): root.destroy() root = Tk() root.title("a simple GnuPG interface") app = GpgApp(root) root.mainloop() Add method to encrypt files#!/usr/bin/env python import subprocess from Tkinter import * from tkFileDialog import * import os GPG = 'gpg2' SERVER_KEY = '' # replace with gpg key ID of server key class GpgApp(object): def __init__(self, master): frame = Frame(master) frame.pack() self.text = Text() self.text.pack() menu = Menu(master) root.config(menu=menu) filemenu = Menu(menu, tearoff=0) menu.add_cascade(label="File", menu=filemenu) filemenu.add_command(label="Open", command=self.filename_open) filemenu.add_separator() filemenu.add_command(label="Exit", command=self.do_exit) def filename_open(self): fin = askopenfilenames() if fin: self.text.insert(END,fin) return fin def encrypt_file(self, input_file, output_file, recipient): args = [GPG, '--output', output_file, '--recipient', recipient, '-sea', input_file] subprocess.call(args) def do_exit(self): root.destroy() root = Tk() root.title("a simple GnuPG interface") app = GpgApp(root) root.mainloop()
<commit_before>#!/usr/bin/env python import subprocess from Tkinter import * from tkFileDialog import * import os class GpgApp(object): def __init__(self, master): frame = Frame(master) frame.pack() self.text = Text() self.text.pack() menu = Menu(master) root.config(menu=menu) filemenu = Menu(menu, tearoff=0) menu.add_cascade(label="File", menu=filemenu) filemenu.add_command(label="Open", command=self.filename_open) filemenu.add_separator() filemenu.add_command(label="Exit", command=self.do_exit) def filename_open(self): fin = askopenfilenames() if fin: self.text.insert(END,fin) return fin def do_exit(self): root.destroy() root = Tk() root.title("a simple GnuPG interface") app = GpgApp(root) root.mainloop() <commit_msg>Add method to encrypt files<commit_after>#!/usr/bin/env python import subprocess from Tkinter import * from tkFileDialog import * import os GPG = 'gpg2' SERVER_KEY = '' # replace with gpg key ID of server key class GpgApp(object): def __init__(self, master): frame = Frame(master) frame.pack() self.text = Text() self.text.pack() menu = Menu(master) root.config(menu=menu) filemenu = Menu(menu, tearoff=0) menu.add_cascade(label="File", menu=filemenu) filemenu.add_command(label="Open", command=self.filename_open) filemenu.add_separator() filemenu.add_command(label="Exit", command=self.do_exit) def filename_open(self): fin = askopenfilenames() if fin: self.text.insert(END,fin) return fin def encrypt_file(self, input_file, output_file, recipient): args = [GPG, '--output', output_file, '--recipient', recipient, '-sea', input_file] subprocess.call(args) def do_exit(self): root.destroy() root = Tk() root.title("a simple GnuPG interface") app = GpgApp(root) root.mainloop()
1c6d93d83b6979ca9c5bfb298efb6fdb3e0c27ee
systempay/app.py
systempay/app.py
from django.conf.urls import patterns, url from oscar.core.application import Application from systempay import views class SystemPayApplication(Application): name = 'systempay' place_order_view = views.PlaceOrderView cancel_response_view = views.CancelResponseView secure_redirect_view = views.SecureRedirectView handle_ipn_view = views.HandleIPN def __init__(self, *args, **kwargs): super(SystemPayApplication, self).__init__(*args, **kwargs) def get_urls(self): urlpatterns = super(SystemPayApplication, self).get_urls() urlpatterns += patterns('', url(r'^secure-redirect/', self.secure_redirect_view.as_view(), name='secure-redirect'), url(r'^preview/', self.place_order_view.as_view(preview=True), name='preview'), url(r'^cancel/', self.cancel_response_view.as_view(), name='cancel-response'), url(r'^place-order/', self.place_order_view.as_view(), name='place-order'), url(r'^handle-ipn/', self.handle_ipn_view.as_view(), name='handle-ipn'), ) return self.post_process_urls(urlpatterns) application = SystemPayApplication()
from django.conf.urls import patterns, url from oscar.core.application import Application from systempay import views class SystemPayApplication(Application): name = 'systempay' place_order_view = views.PlaceOrderView cancel_response_view = views.CancelResponseView secure_redirect_view = views.SecureRedirectView handle_ipn_view = views.HandleIPN def __init__(self, *args, **kwargs): super(SystemPayApplication, self).__init__(*args, **kwargs) def get_urls(self): urlpatterns = super(SystemPayApplication, self).get_urls() urlpatterns += patterns('', url(r'^secure-redirect/', self.secure_redirect_view.as_view(), name='secure-redirect'), url(r'^preview/', self.place_order_view.as_view(preview=True), name='preview'), url(r'^cancel/', self.cancel_response_view.as_view(), name='cancel-response'), url(r'^place-order/', self.place_order_view.as_view(), name='place-order'), url(r'^handle-ipn$', self.handle_ipn_view.as_view(), name='handle-ipn'), ) return self.post_process_urls(urlpatterns) application = SystemPayApplication()
Remove the ending slash for handle ipn url
Remove the ending slash for handle ipn url
Python
mit
dulaccc/django-oscar-systempay,bastien34/django-oscar-systempay,bastien34/django-oscar-systempay
from django.conf.urls import patterns, url from oscar.core.application import Application from systempay import views class SystemPayApplication(Application): name = 'systempay' place_order_view = views.PlaceOrderView cancel_response_view = views.CancelResponseView secure_redirect_view = views.SecureRedirectView handle_ipn_view = views.HandleIPN def __init__(self, *args, **kwargs): super(SystemPayApplication, self).__init__(*args, **kwargs) def get_urls(self): urlpatterns = super(SystemPayApplication, self).get_urls() urlpatterns += patterns('', url(r'^secure-redirect/', self.secure_redirect_view.as_view(), name='secure-redirect'), url(r'^preview/', self.place_order_view.as_view(preview=True), name='preview'), url(r'^cancel/', self.cancel_response_view.as_view(), name='cancel-response'), url(r'^place-order/', self.place_order_view.as_view(), name='place-order'), url(r'^handle-ipn/', self.handle_ipn_view.as_view(), name='handle-ipn'), ) return self.post_process_urls(urlpatterns) application = SystemPayApplication() Remove the ending slash for handle ipn url
from django.conf.urls import patterns, url from oscar.core.application import Application from systempay import views class SystemPayApplication(Application): name = 'systempay' place_order_view = views.PlaceOrderView cancel_response_view = views.CancelResponseView secure_redirect_view = views.SecureRedirectView handle_ipn_view = views.HandleIPN def __init__(self, *args, **kwargs): super(SystemPayApplication, self).__init__(*args, **kwargs) def get_urls(self): urlpatterns = super(SystemPayApplication, self).get_urls() urlpatterns += patterns('', url(r'^secure-redirect/', self.secure_redirect_view.as_view(), name='secure-redirect'), url(r'^preview/', self.place_order_view.as_view(preview=True), name='preview'), url(r'^cancel/', self.cancel_response_view.as_view(), name='cancel-response'), url(r'^place-order/', self.place_order_view.as_view(), name='place-order'), url(r'^handle-ipn$', self.handle_ipn_view.as_view(), name='handle-ipn'), ) return self.post_process_urls(urlpatterns) application = SystemPayApplication()
<commit_before>from django.conf.urls import patterns, url from oscar.core.application import Application from systempay import views class SystemPayApplication(Application): name = 'systempay' place_order_view = views.PlaceOrderView cancel_response_view = views.CancelResponseView secure_redirect_view = views.SecureRedirectView handle_ipn_view = views.HandleIPN def __init__(self, *args, **kwargs): super(SystemPayApplication, self).__init__(*args, **kwargs) def get_urls(self): urlpatterns = super(SystemPayApplication, self).get_urls() urlpatterns += patterns('', url(r'^secure-redirect/', self.secure_redirect_view.as_view(), name='secure-redirect'), url(r'^preview/', self.place_order_view.as_view(preview=True), name='preview'), url(r'^cancel/', self.cancel_response_view.as_view(), name='cancel-response'), url(r'^place-order/', self.place_order_view.as_view(), name='place-order'), url(r'^handle-ipn/', self.handle_ipn_view.as_view(), name='handle-ipn'), ) return self.post_process_urls(urlpatterns) application = SystemPayApplication() <commit_msg>Remove the ending slash for handle ipn url<commit_after>
from django.conf.urls import patterns, url from oscar.core.application import Application from systempay import views class SystemPayApplication(Application): name = 'systempay' place_order_view = views.PlaceOrderView cancel_response_view = views.CancelResponseView secure_redirect_view = views.SecureRedirectView handle_ipn_view = views.HandleIPN def __init__(self, *args, **kwargs): super(SystemPayApplication, self).__init__(*args, **kwargs) def get_urls(self): urlpatterns = super(SystemPayApplication, self).get_urls() urlpatterns += patterns('', url(r'^secure-redirect/', self.secure_redirect_view.as_view(), name='secure-redirect'), url(r'^preview/', self.place_order_view.as_view(preview=True), name='preview'), url(r'^cancel/', self.cancel_response_view.as_view(), name='cancel-response'), url(r'^place-order/', self.place_order_view.as_view(), name='place-order'), url(r'^handle-ipn$', self.handle_ipn_view.as_view(), name='handle-ipn'), ) return self.post_process_urls(urlpatterns) application = SystemPayApplication()
from django.conf.urls import patterns, url from oscar.core.application import Application from systempay import views class SystemPayApplication(Application): name = 'systempay' place_order_view = views.PlaceOrderView cancel_response_view = views.CancelResponseView secure_redirect_view = views.SecureRedirectView handle_ipn_view = views.HandleIPN def __init__(self, *args, **kwargs): super(SystemPayApplication, self).__init__(*args, **kwargs) def get_urls(self): urlpatterns = super(SystemPayApplication, self).get_urls() urlpatterns += patterns('', url(r'^secure-redirect/', self.secure_redirect_view.as_view(), name='secure-redirect'), url(r'^preview/', self.place_order_view.as_view(preview=True), name='preview'), url(r'^cancel/', self.cancel_response_view.as_view(), name='cancel-response'), url(r'^place-order/', self.place_order_view.as_view(), name='place-order'), url(r'^handle-ipn/', self.handle_ipn_view.as_view(), name='handle-ipn'), ) return self.post_process_urls(urlpatterns) application = SystemPayApplication() Remove the ending slash for handle ipn urlfrom django.conf.urls import patterns, url from oscar.core.application import Application from systempay import views class SystemPayApplication(Application): name = 'systempay' place_order_view = views.PlaceOrderView cancel_response_view = views.CancelResponseView secure_redirect_view = views.SecureRedirectView handle_ipn_view = views.HandleIPN def __init__(self, *args, **kwargs): super(SystemPayApplication, self).__init__(*args, **kwargs) def get_urls(self): urlpatterns = super(SystemPayApplication, self).get_urls() urlpatterns += patterns('', url(r'^secure-redirect/', self.secure_redirect_view.as_view(), name='secure-redirect'), url(r'^preview/', self.place_order_view.as_view(preview=True), name='preview'), url(r'^cancel/', self.cancel_response_view.as_view(), name='cancel-response'), url(r'^place-order/', self.place_order_view.as_view(), name='place-order'), url(r'^handle-ipn$', self.handle_ipn_view.as_view(), name='handle-ipn'), ) return self.post_process_urls(urlpatterns) application = SystemPayApplication()
<commit_before>from django.conf.urls import patterns, url from oscar.core.application import Application from systempay import views class SystemPayApplication(Application): name = 'systempay' place_order_view = views.PlaceOrderView cancel_response_view = views.CancelResponseView secure_redirect_view = views.SecureRedirectView handle_ipn_view = views.HandleIPN def __init__(self, *args, **kwargs): super(SystemPayApplication, self).__init__(*args, **kwargs) def get_urls(self): urlpatterns = super(SystemPayApplication, self).get_urls() urlpatterns += patterns('', url(r'^secure-redirect/', self.secure_redirect_view.as_view(), name='secure-redirect'), url(r'^preview/', self.place_order_view.as_view(preview=True), name='preview'), url(r'^cancel/', self.cancel_response_view.as_view(), name='cancel-response'), url(r'^place-order/', self.place_order_view.as_view(), name='place-order'), url(r'^handle-ipn/', self.handle_ipn_view.as_view(), name='handle-ipn'), ) return self.post_process_urls(urlpatterns) application = SystemPayApplication() <commit_msg>Remove the ending slash for handle ipn url<commit_after>from django.conf.urls import patterns, url from oscar.core.application import Application from systempay import views class SystemPayApplication(Application): name = 'systempay' place_order_view = views.PlaceOrderView cancel_response_view = views.CancelResponseView secure_redirect_view = views.SecureRedirectView handle_ipn_view = views.HandleIPN def __init__(self, *args, **kwargs): super(SystemPayApplication, self).__init__(*args, **kwargs) def get_urls(self): urlpatterns = super(SystemPayApplication, self).get_urls() urlpatterns += patterns('', url(r'^secure-redirect/', self.secure_redirect_view.as_view(), name='secure-redirect'), url(r'^preview/', self.place_order_view.as_view(preview=True), name='preview'), url(r'^cancel/', self.cancel_response_view.as_view(), name='cancel-response'), url(r'^place-order/', self.place_order_view.as_view(), name='place-order'), url(r'^handle-ipn$', self.handle_ipn_view.as_view(), name='handle-ipn'), ) return self.post_process_urls(urlpatterns) application = SystemPayApplication()
b89e210f95b8f41efa8019ee66d6449b7242d56f
tikplay/audio.py
tikplay/audio.py
import json import logging import pysoundcard import pysoundfile from tikplay.database import interface class API(): """ Implements the audio parsing interface for tikplay. Parses song metadata, handles database updating, and pushes the audio to soundcard Also implements basic song metadata fetching from the database """ def __init__(self, di=interface.DatabaseInterface): self.di = di() self.logger = logging.getLogger('AudioAPI') def play(self, song_hash): """ Play a song or add it to queue if a song is already playing Keyword arguments: song_hash: ... Return: true if started playing, false if added to queue """ soundcard = True for dev in list(pysoundcard.devices()): if '(hw:0,0)' in dev['name']: soundcard = dev break stream = pysoundcard.Stream(output_device=soundcard) soundfile = pysoundfile.SoundFile(song_hash) channels = soundfile.channels sample_rate = soundfile.sample_rate stream.output_channels = channels stream.start() stream.write(soundfile[:]) stream.end() def now_playing(self, queue_length=1): """ Shows the now playing or the queue if queue_length is defined Keyword arguments: queue_length (optional): integer stating the length of queue to return. Default: 1. Return: the song that is now playing in the format ("Artist - Title"[, "Artist - Title", ...]) or None if empty """ return None
import json import logging from pyglet import media from tikplay.database import interface class API(): """ Implements the audio parsing interface for tikplay. Parses song metadata, handles database updating, and pushes the audio to soundcard Also implements basic song metadata fetching from the database """ def __init__(self, di=interface.DatabaseInterface): self.player = media.Player() self.di = di() self.logger = logging.getLogger('AudioAPI') def play(self, song_hash): """ Play a song or add it to queue if a song is already playing Keyword arguments: song_hash: ... Return: true if started playing, false if added to queue """ # if cache: load audio metadata from cache # else: check that song_hash is actually a filename for an existing file audio_file = media.load(song_hash) self.player.queue(audio_file) if not self.player.playing: self.player.play() def next(self): self.player.next_source() def pause(self): self.player.pause() def resume(self): self.player.resume() def kill(self): while self.player.playing: self.player.next_source() def now_playing(self, queue_length=1): """ Shows the now playing or the queue if queue_length is defined Keyword arguments: queue_length (optional): integer stating the length of queue to return. Default: 1. Return: the song that is now playing in the format [(Artist, Title), (Artist, Title), ...) or None if empty """ src = self.player.source return [(src.info.author, src.info.title)]
Change pysoundcard and pysoundfile to pyglet
Change pysoundcard and pysoundfile to pyglet
Python
mit
tietokilta-saato/tikplay,tietokilta-saato/tikplay,tietokilta-saato/tikplay,tietokilta-saato/tikplay
import json import logging import pysoundcard import pysoundfile from tikplay.database import interface class API(): """ Implements the audio parsing interface for tikplay. Parses song metadata, handles database updating, and pushes the audio to soundcard Also implements basic song metadata fetching from the database """ def __init__(self, di=interface.DatabaseInterface): self.di = di() self.logger = logging.getLogger('AudioAPI') def play(self, song_hash): """ Play a song or add it to queue if a song is already playing Keyword arguments: song_hash: ... Return: true if started playing, false if added to queue """ soundcard = True for dev in list(pysoundcard.devices()): if '(hw:0,0)' in dev['name']: soundcard = dev break stream = pysoundcard.Stream(output_device=soundcard) soundfile = pysoundfile.SoundFile(song_hash) channels = soundfile.channels sample_rate = soundfile.sample_rate stream.output_channels = channels stream.start() stream.write(soundfile[:]) stream.end() def now_playing(self, queue_length=1): """ Shows the now playing or the queue if queue_length is defined Keyword arguments: queue_length (optional): integer stating the length of queue to return. Default: 1. Return: the song that is now playing in the format ("Artist - Title"[, "Artist - Title", ...]) or None if empty """ return None Change pysoundcard and pysoundfile to pyglet
import json import logging from pyglet import media from tikplay.database import interface class API(): """ Implements the audio parsing interface for tikplay. Parses song metadata, handles database updating, and pushes the audio to soundcard Also implements basic song metadata fetching from the database """ def __init__(self, di=interface.DatabaseInterface): self.player = media.Player() self.di = di() self.logger = logging.getLogger('AudioAPI') def play(self, song_hash): """ Play a song or add it to queue if a song is already playing Keyword arguments: song_hash: ... Return: true if started playing, false if added to queue """ # if cache: load audio metadata from cache # else: check that song_hash is actually a filename for an existing file audio_file = media.load(song_hash) self.player.queue(audio_file) if not self.player.playing: self.player.play() def next(self): self.player.next_source() def pause(self): self.player.pause() def resume(self): self.player.resume() def kill(self): while self.player.playing: self.player.next_source() def now_playing(self, queue_length=1): """ Shows the now playing or the queue if queue_length is defined Keyword arguments: queue_length (optional): integer stating the length of queue to return. Default: 1. Return: the song that is now playing in the format [(Artist, Title), (Artist, Title), ...) or None if empty """ src = self.player.source return [(src.info.author, src.info.title)]
<commit_before>import json import logging import pysoundcard import pysoundfile from tikplay.database import interface class API(): """ Implements the audio parsing interface for tikplay. Parses song metadata, handles database updating, and pushes the audio to soundcard Also implements basic song metadata fetching from the database """ def __init__(self, di=interface.DatabaseInterface): self.di = di() self.logger = logging.getLogger('AudioAPI') def play(self, song_hash): """ Play a song or add it to queue if a song is already playing Keyword arguments: song_hash: ... Return: true if started playing, false if added to queue """ soundcard = True for dev in list(pysoundcard.devices()): if '(hw:0,0)' in dev['name']: soundcard = dev break stream = pysoundcard.Stream(output_device=soundcard) soundfile = pysoundfile.SoundFile(song_hash) channels = soundfile.channels sample_rate = soundfile.sample_rate stream.output_channels = channels stream.start() stream.write(soundfile[:]) stream.end() def now_playing(self, queue_length=1): """ Shows the now playing or the queue if queue_length is defined Keyword arguments: queue_length (optional): integer stating the length of queue to return. Default: 1. Return: the song that is now playing in the format ("Artist - Title"[, "Artist - Title", ...]) or None if empty """ return None <commit_msg>Change pysoundcard and pysoundfile to pyglet<commit_after>
import json import logging from pyglet import media from tikplay.database import interface class API(): """ Implements the audio parsing interface for tikplay. Parses song metadata, handles database updating, and pushes the audio to soundcard Also implements basic song metadata fetching from the database """ def __init__(self, di=interface.DatabaseInterface): self.player = media.Player() self.di = di() self.logger = logging.getLogger('AudioAPI') def play(self, song_hash): """ Play a song or add it to queue if a song is already playing Keyword arguments: song_hash: ... Return: true if started playing, false if added to queue """ # if cache: load audio metadata from cache # else: check that song_hash is actually a filename for an existing file audio_file = media.load(song_hash) self.player.queue(audio_file) if not self.player.playing: self.player.play() def next(self): self.player.next_source() def pause(self): self.player.pause() def resume(self): self.player.resume() def kill(self): while self.player.playing: self.player.next_source() def now_playing(self, queue_length=1): """ Shows the now playing or the queue if queue_length is defined Keyword arguments: queue_length (optional): integer stating the length of queue to return. Default: 1. Return: the song that is now playing in the format [(Artist, Title), (Artist, Title), ...) or None if empty """ src = self.player.source return [(src.info.author, src.info.title)]
import json import logging import pysoundcard import pysoundfile from tikplay.database import interface class API(): """ Implements the audio parsing interface for tikplay. Parses song metadata, handles database updating, and pushes the audio to soundcard Also implements basic song metadata fetching from the database """ def __init__(self, di=interface.DatabaseInterface): self.di = di() self.logger = logging.getLogger('AudioAPI') def play(self, song_hash): """ Play a song or add it to queue if a song is already playing Keyword arguments: song_hash: ... Return: true if started playing, false if added to queue """ soundcard = True for dev in list(pysoundcard.devices()): if '(hw:0,0)' in dev['name']: soundcard = dev break stream = pysoundcard.Stream(output_device=soundcard) soundfile = pysoundfile.SoundFile(song_hash) channels = soundfile.channels sample_rate = soundfile.sample_rate stream.output_channels = channels stream.start() stream.write(soundfile[:]) stream.end() def now_playing(self, queue_length=1): """ Shows the now playing or the queue if queue_length is defined Keyword arguments: queue_length (optional): integer stating the length of queue to return. Default: 1. Return: the song that is now playing in the format ("Artist - Title"[, "Artist - Title", ...]) or None if empty """ return None Change pysoundcard and pysoundfile to pygletimport json import logging from pyglet import media from tikplay.database import interface class API(): """ Implements the audio parsing interface for tikplay. Parses song metadata, handles database updating, and pushes the audio to soundcard Also implements basic song metadata fetching from the database """ def __init__(self, di=interface.DatabaseInterface): self.player = media.Player() self.di = di() self.logger = logging.getLogger('AudioAPI') def play(self, song_hash): """ Play a song or add it to queue if a song is already playing Keyword arguments: song_hash: ... Return: true if started playing, false if added to queue """ # if cache: load audio metadata from cache # else: check that song_hash is actually a filename for an existing file audio_file = media.load(song_hash) self.player.queue(audio_file) if not self.player.playing: self.player.play() def next(self): self.player.next_source() def pause(self): self.player.pause() def resume(self): self.player.resume() def kill(self): while self.player.playing: self.player.next_source() def now_playing(self, queue_length=1): """ Shows the now playing or the queue if queue_length is defined Keyword arguments: queue_length (optional): integer stating the length of queue to return. Default: 1. Return: the song that is now playing in the format [(Artist, Title), (Artist, Title), ...) or None if empty """ src = self.player.source return [(src.info.author, src.info.title)]
<commit_before>import json import logging import pysoundcard import pysoundfile from tikplay.database import interface class API(): """ Implements the audio parsing interface for tikplay. Parses song metadata, handles database updating, and pushes the audio to soundcard Also implements basic song metadata fetching from the database """ def __init__(self, di=interface.DatabaseInterface): self.di = di() self.logger = logging.getLogger('AudioAPI') def play(self, song_hash): """ Play a song or add it to queue if a song is already playing Keyword arguments: song_hash: ... Return: true if started playing, false if added to queue """ soundcard = True for dev in list(pysoundcard.devices()): if '(hw:0,0)' in dev['name']: soundcard = dev break stream = pysoundcard.Stream(output_device=soundcard) soundfile = pysoundfile.SoundFile(song_hash) channels = soundfile.channels sample_rate = soundfile.sample_rate stream.output_channels = channels stream.start() stream.write(soundfile[:]) stream.end() def now_playing(self, queue_length=1): """ Shows the now playing or the queue if queue_length is defined Keyword arguments: queue_length (optional): integer stating the length of queue to return. Default: 1. Return: the song that is now playing in the format ("Artist - Title"[, "Artist - Title", ...]) or None if empty """ return None <commit_msg>Change pysoundcard and pysoundfile to pyglet<commit_after>import json import logging from pyglet import media from tikplay.database import interface class API(): """ Implements the audio parsing interface for tikplay. Parses song metadata, handles database updating, and pushes the audio to soundcard Also implements basic song metadata fetching from the database """ def __init__(self, di=interface.DatabaseInterface): self.player = media.Player() self.di = di() self.logger = logging.getLogger('AudioAPI') def play(self, song_hash): """ Play a song or add it to queue if a song is already playing Keyword arguments: song_hash: ... Return: true if started playing, false if added to queue """ # if cache: load audio metadata from cache # else: check that song_hash is actually a filename for an existing file audio_file = media.load(song_hash) self.player.queue(audio_file) if not self.player.playing: self.player.play() def next(self): self.player.next_source() def pause(self): self.player.pause() def resume(self): self.player.resume() def kill(self): while self.player.playing: self.player.next_source() def now_playing(self, queue_length=1): """ Shows the now playing or the queue if queue_length is defined Keyword arguments: queue_length (optional): integer stating the length of queue to return. Default: 1. Return: the song that is now playing in the format [(Artist, Title), (Artist, Title), ...) or None if empty """ src = self.player.source return [(src.info.author, src.info.title)]
336e81005deb485378fe594cf466773f36160d5e
demo/__init__.py
demo/__init__.py
"""Package for PythonTemplateDemo.""" import sys __project__ = 'PythonTemplateDemo' __version__ = '0.0.0' VERSION = "{0} v{1}".format(__project__, __version__) PYTHON_VERSION = 3, 5 if sys.version_info < PYTHON_VERSION: # pragma: no cover (manual test) exit("Python {}.{}+ is required.".format(*PYTHON_VERSION))
"""Package for PythonTemplateDemo.""" import sys __project__ = 'PythonTemplateDemo' __version__ = '0.0.0' VERSION = "{0} v{1}".format(__project__, __version__) PYTHON_VERSION = 3, 5 if sys.version_info < PYTHON_VERSION: # pragma: no cover (manual test) sys.exit("Python {}.{}+ is required.".format(*PYTHON_VERSION))
Deploy Travis CI build 646 to GitHub
Deploy Travis CI build 646 to GitHub
Python
mit
jacebrowning/template-python-demo
"""Package for PythonTemplateDemo.""" import sys __project__ = 'PythonTemplateDemo' __version__ = '0.0.0' VERSION = "{0} v{1}".format(__project__, __version__) PYTHON_VERSION = 3, 5 if sys.version_info < PYTHON_VERSION: # pragma: no cover (manual test) exit("Python {}.{}+ is required.".format(*PYTHON_VERSION)) Deploy Travis CI build 646 to GitHub
"""Package for PythonTemplateDemo.""" import sys __project__ = 'PythonTemplateDemo' __version__ = '0.0.0' VERSION = "{0} v{1}".format(__project__, __version__) PYTHON_VERSION = 3, 5 if sys.version_info < PYTHON_VERSION: # pragma: no cover (manual test) sys.exit("Python {}.{}+ is required.".format(*PYTHON_VERSION))
<commit_before>"""Package for PythonTemplateDemo.""" import sys __project__ = 'PythonTemplateDemo' __version__ = '0.0.0' VERSION = "{0} v{1}".format(__project__, __version__) PYTHON_VERSION = 3, 5 if sys.version_info < PYTHON_VERSION: # pragma: no cover (manual test) exit("Python {}.{}+ is required.".format(*PYTHON_VERSION)) <commit_msg>Deploy Travis CI build 646 to GitHub<commit_after>
"""Package for PythonTemplateDemo.""" import sys __project__ = 'PythonTemplateDemo' __version__ = '0.0.0' VERSION = "{0} v{1}".format(__project__, __version__) PYTHON_VERSION = 3, 5 if sys.version_info < PYTHON_VERSION: # pragma: no cover (manual test) sys.exit("Python {}.{}+ is required.".format(*PYTHON_VERSION))
"""Package for PythonTemplateDemo.""" import sys __project__ = 'PythonTemplateDemo' __version__ = '0.0.0' VERSION = "{0} v{1}".format(__project__, __version__) PYTHON_VERSION = 3, 5 if sys.version_info < PYTHON_VERSION: # pragma: no cover (manual test) exit("Python {}.{}+ is required.".format(*PYTHON_VERSION)) Deploy Travis CI build 646 to GitHub"""Package for PythonTemplateDemo.""" import sys __project__ = 'PythonTemplateDemo' __version__ = '0.0.0' VERSION = "{0} v{1}".format(__project__, __version__) PYTHON_VERSION = 3, 5 if sys.version_info < PYTHON_VERSION: # pragma: no cover (manual test) sys.exit("Python {}.{}+ is required.".format(*PYTHON_VERSION))
<commit_before>"""Package for PythonTemplateDemo.""" import sys __project__ = 'PythonTemplateDemo' __version__ = '0.0.0' VERSION = "{0} v{1}".format(__project__, __version__) PYTHON_VERSION = 3, 5 if sys.version_info < PYTHON_VERSION: # pragma: no cover (manual test) exit("Python {}.{}+ is required.".format(*PYTHON_VERSION)) <commit_msg>Deploy Travis CI build 646 to GitHub<commit_after>"""Package for PythonTemplateDemo.""" import sys __project__ = 'PythonTemplateDemo' __version__ = '0.0.0' VERSION = "{0} v{1}".format(__project__, __version__) PYTHON_VERSION = 3, 5 if sys.version_info < PYTHON_VERSION: # pragma: no cover (manual test) sys.exit("Python {}.{}+ is required.".format(*PYTHON_VERSION))
b1edf4678a57bb25220bd4c50f05ceb7fbd5e7fe
users/filters.py
users/filters.py
"""Filter classes corresponding to each one of the works app's models that has the same fields as the model for an equalTo filter. There can be added extra fields inside each class as gt, lt, gte, lte and so on for convinience. """ import django_filters from django.contrib.auth.models import User, Group class UserFilter(django_filters.rest_framework.FilterSet): user_group_name = django_filters.CharFilter(name='groups__name') class Meta: model = User fields = ['id', 'username', 'first_name', 'last_name', 'groups', 'user_group_name'] class GroupFilter(django_filters.rest_framework.FilterSet): class Meta: model = Group fields = ['id', 'name']
"""Filter classes corresponding to each one of the works app's models that has the same fields as the model for an equalTo filter. There can be added extra fields inside each class as gt, lt, gte, lte and so on for convinience. """ import django_filters from django.contrib.auth.models import User, Group class UserFilter(django_filters.rest_framework.FilterSet): groups_name = django_filters.CharFilter(name='groups__name') class Meta: model = User fields = ['id', 'username', 'first_name', 'last_name', 'groups', 'groups_name'] class GroupFilter(django_filters.rest_framework.FilterSet): class Meta: model = Group fields = ['id', 'name']
Change name of a filter field
Change name of a filter field
Python
mit
fernandolobato/balarco,fernandolobato/balarco,fernandolobato/balarco
"""Filter classes corresponding to each one of the works app's models that has the same fields as the model for an equalTo filter. There can be added extra fields inside each class as gt, lt, gte, lte and so on for convinience. """ import django_filters from django.contrib.auth.models import User, Group class UserFilter(django_filters.rest_framework.FilterSet): user_group_name = django_filters.CharFilter(name='groups__name') class Meta: model = User fields = ['id', 'username', 'first_name', 'last_name', 'groups', 'user_group_name'] class GroupFilter(django_filters.rest_framework.FilterSet): class Meta: model = Group fields = ['id', 'name'] Change name of a filter field
"""Filter classes corresponding to each one of the works app's models that has the same fields as the model for an equalTo filter. There can be added extra fields inside each class as gt, lt, gte, lte and so on for convinience. """ import django_filters from django.contrib.auth.models import User, Group class UserFilter(django_filters.rest_framework.FilterSet): groups_name = django_filters.CharFilter(name='groups__name') class Meta: model = User fields = ['id', 'username', 'first_name', 'last_name', 'groups', 'groups_name'] class GroupFilter(django_filters.rest_framework.FilterSet): class Meta: model = Group fields = ['id', 'name']
<commit_before>"""Filter classes corresponding to each one of the works app's models that has the same fields as the model for an equalTo filter. There can be added extra fields inside each class as gt, lt, gte, lte and so on for convinience. """ import django_filters from django.contrib.auth.models import User, Group class UserFilter(django_filters.rest_framework.FilterSet): user_group_name = django_filters.CharFilter(name='groups__name') class Meta: model = User fields = ['id', 'username', 'first_name', 'last_name', 'groups', 'user_group_name'] class GroupFilter(django_filters.rest_framework.FilterSet): class Meta: model = Group fields = ['id', 'name'] <commit_msg>Change name of a filter field<commit_after>
"""Filter classes corresponding to each one of the works app's models that has the same fields as the model for an equalTo filter. There can be added extra fields inside each class as gt, lt, gte, lte and so on for convinience. """ import django_filters from django.contrib.auth.models import User, Group class UserFilter(django_filters.rest_framework.FilterSet): groups_name = django_filters.CharFilter(name='groups__name') class Meta: model = User fields = ['id', 'username', 'first_name', 'last_name', 'groups', 'groups_name'] class GroupFilter(django_filters.rest_framework.FilterSet): class Meta: model = Group fields = ['id', 'name']
"""Filter classes corresponding to each one of the works app's models that has the same fields as the model for an equalTo filter. There can be added extra fields inside each class as gt, lt, gte, lte and so on for convinience. """ import django_filters from django.contrib.auth.models import User, Group class UserFilter(django_filters.rest_framework.FilterSet): user_group_name = django_filters.CharFilter(name='groups__name') class Meta: model = User fields = ['id', 'username', 'first_name', 'last_name', 'groups', 'user_group_name'] class GroupFilter(django_filters.rest_framework.FilterSet): class Meta: model = Group fields = ['id', 'name'] Change name of a filter field"""Filter classes corresponding to each one of the works app's models that has the same fields as the model for an equalTo filter. There can be added extra fields inside each class as gt, lt, gte, lte and so on for convinience. """ import django_filters from django.contrib.auth.models import User, Group class UserFilter(django_filters.rest_framework.FilterSet): groups_name = django_filters.CharFilter(name='groups__name') class Meta: model = User fields = ['id', 'username', 'first_name', 'last_name', 'groups', 'groups_name'] class GroupFilter(django_filters.rest_framework.FilterSet): class Meta: model = Group fields = ['id', 'name']
<commit_before>"""Filter classes corresponding to each one of the works app's models that has the same fields as the model for an equalTo filter. There can be added extra fields inside each class as gt, lt, gte, lte and so on for convinience. """ import django_filters from django.contrib.auth.models import User, Group class UserFilter(django_filters.rest_framework.FilterSet): user_group_name = django_filters.CharFilter(name='groups__name') class Meta: model = User fields = ['id', 'username', 'first_name', 'last_name', 'groups', 'user_group_name'] class GroupFilter(django_filters.rest_framework.FilterSet): class Meta: model = Group fields = ['id', 'name'] <commit_msg>Change name of a filter field<commit_after>"""Filter classes corresponding to each one of the works app's models that has the same fields as the model for an equalTo filter. There can be added extra fields inside each class as gt, lt, gte, lte and so on for convinience. """ import django_filters from django.contrib.auth.models import User, Group class UserFilter(django_filters.rest_framework.FilterSet): groups_name = django_filters.CharFilter(name='groups__name') class Meta: model = User fields = ['id', 'username', 'first_name', 'last_name', 'groups', 'groups_name'] class GroupFilter(django_filters.rest_framework.FilterSet): class Meta: model = Group fields = ['id', 'name']
4e4390db6ed35de4fb7ad42579be5180a95bb96f
src/settings.py
src/settings.py
import re import os # Root directory that we scan for music from # Do not change this unless you're not using the docker-compose # It is preferred you use just change the volume mapping on the docker-compose.yml MUSIC_DIRECTORY = os.environ.get("FTMP3_MUSIC", "/media/Music") # Tells flask to serve the mp3 files # Typically you'd want nginx to do this instead, as this is an # easy way to cause concurrent response issues with flask SERVE_FILES = True # acceptable standard html5 compatible formats FORMAT_MATCH = re.compile(r"\.(mp3|ogg|midi|mid)$") # number of directories upwards to limit recursive check for cover image COVER_IMG_RECURSION_LIMIT = 1
import re import os # Root directory that we scan for music from # Do not change this unless you're not using the docker-compose # It is preferred you use just change the volume mapping on the docker-compose.yml MUSIC_DIRECTORY = os.environ.get("FTMP3_MUSIC", r"/media/Music/") # Tells flask to serve the mp3 files # Typically you'd want nginx to do this instead, as this is an # easy way to cause concurrent response issues with flask SERVE_FILES = True # acceptable standard html5 compatible formats FORMAT_MATCH = re.compile(r"(?i)\.(mp3|m4a|ogg)$") # number of directories upwards to limit recursive check for cover image COVER_IMG_RECURSION_LIMIT = 1
Allow for case-insensitive checking of file formats. Support m4a
Allow for case-insensitive checking of file formats. Support m4a
Python
apache-2.0
nhydock/ftmp3,lunared/ftmp3,nhydock/ftmp3,lunared/ftmp3,lunared/ftmp3
import re import os # Root directory that we scan for music from # Do not change this unless you're not using the docker-compose # It is preferred you use just change the volume mapping on the docker-compose.yml MUSIC_DIRECTORY = os.environ.get("FTMP3_MUSIC", "/media/Music") # Tells flask to serve the mp3 files # Typically you'd want nginx to do this instead, as this is an # easy way to cause concurrent response issues with flask SERVE_FILES = True # acceptable standard html5 compatible formats FORMAT_MATCH = re.compile(r"\.(mp3|ogg|midi|mid)$") # number of directories upwards to limit recursive check for cover image COVER_IMG_RECURSION_LIMIT = 1 Allow for case-insensitive checking of file formats. Support m4a
import re import os # Root directory that we scan for music from # Do not change this unless you're not using the docker-compose # It is preferred you use just change the volume mapping on the docker-compose.yml MUSIC_DIRECTORY = os.environ.get("FTMP3_MUSIC", r"/media/Music/") # Tells flask to serve the mp3 files # Typically you'd want nginx to do this instead, as this is an # easy way to cause concurrent response issues with flask SERVE_FILES = True # acceptable standard html5 compatible formats FORMAT_MATCH = re.compile(r"(?i)\.(mp3|m4a|ogg)$") # number of directories upwards to limit recursive check for cover image COVER_IMG_RECURSION_LIMIT = 1
<commit_before>import re import os # Root directory that we scan for music from # Do not change this unless you're not using the docker-compose # It is preferred you use just change the volume mapping on the docker-compose.yml MUSIC_DIRECTORY = os.environ.get("FTMP3_MUSIC", "/media/Music") # Tells flask to serve the mp3 files # Typically you'd want nginx to do this instead, as this is an # easy way to cause concurrent response issues with flask SERVE_FILES = True # acceptable standard html5 compatible formats FORMAT_MATCH = re.compile(r"\.(mp3|ogg|midi|mid)$") # number of directories upwards to limit recursive check for cover image COVER_IMG_RECURSION_LIMIT = 1 <commit_msg>Allow for case-insensitive checking of file formats. Support m4a<commit_after>
import re import os # Root directory that we scan for music from # Do not change this unless you're not using the docker-compose # It is preferred you use just change the volume mapping on the docker-compose.yml MUSIC_DIRECTORY = os.environ.get("FTMP3_MUSIC", r"/media/Music/") # Tells flask to serve the mp3 files # Typically you'd want nginx to do this instead, as this is an # easy way to cause concurrent response issues with flask SERVE_FILES = True # acceptable standard html5 compatible formats FORMAT_MATCH = re.compile(r"(?i)\.(mp3|m4a|ogg)$") # number of directories upwards to limit recursive check for cover image COVER_IMG_RECURSION_LIMIT = 1
import re import os # Root directory that we scan for music from # Do not change this unless you're not using the docker-compose # It is preferred you use just change the volume mapping on the docker-compose.yml MUSIC_DIRECTORY = os.environ.get("FTMP3_MUSIC", "/media/Music") # Tells flask to serve the mp3 files # Typically you'd want nginx to do this instead, as this is an # easy way to cause concurrent response issues with flask SERVE_FILES = True # acceptable standard html5 compatible formats FORMAT_MATCH = re.compile(r"\.(mp3|ogg|midi|mid)$") # number of directories upwards to limit recursive check for cover image COVER_IMG_RECURSION_LIMIT = 1 Allow for case-insensitive checking of file formats. Support m4aimport re import os # Root directory that we scan for music from # Do not change this unless you're not using the docker-compose # It is preferred you use just change the volume mapping on the docker-compose.yml MUSIC_DIRECTORY = os.environ.get("FTMP3_MUSIC", r"/media/Music/") # Tells flask to serve the mp3 files # Typically you'd want nginx to do this instead, as this is an # easy way to cause concurrent response issues with flask SERVE_FILES = True # acceptable standard html5 compatible formats FORMAT_MATCH = re.compile(r"(?i)\.(mp3|m4a|ogg)$") # number of directories upwards to limit recursive check for cover image COVER_IMG_RECURSION_LIMIT = 1
<commit_before>import re import os # Root directory that we scan for music from # Do not change this unless you're not using the docker-compose # It is preferred you use just change the volume mapping on the docker-compose.yml MUSIC_DIRECTORY = os.environ.get("FTMP3_MUSIC", "/media/Music") # Tells flask to serve the mp3 files # Typically you'd want nginx to do this instead, as this is an # easy way to cause concurrent response issues with flask SERVE_FILES = True # acceptable standard html5 compatible formats FORMAT_MATCH = re.compile(r"\.(mp3|ogg|midi|mid)$") # number of directories upwards to limit recursive check for cover image COVER_IMG_RECURSION_LIMIT = 1 <commit_msg>Allow for case-insensitive checking of file formats. Support m4a<commit_after>import re import os # Root directory that we scan for music from # Do not change this unless you're not using the docker-compose # It is preferred you use just change the volume mapping on the docker-compose.yml MUSIC_DIRECTORY = os.environ.get("FTMP3_MUSIC", r"/media/Music/") # Tells flask to serve the mp3 files # Typically you'd want nginx to do this instead, as this is an # easy way to cause concurrent response issues with flask SERVE_FILES = True # acceptable standard html5 compatible formats FORMAT_MATCH = re.compile(r"(?i)\.(mp3|m4a|ogg)$") # number of directories upwards to limit recursive check for cover image COVER_IMG_RECURSION_LIMIT = 1
7fe1ce9b1c9d6368bdb0945c2ed820cdafdc53c2
scrapeOMDB.py
scrapeOMDB.py
#!/usr/bin/python3 # scrapeOMDB.py - parses a movie and year from arguments and returns JSON import json, requests URL_BASE = 'http://www.omdbapi.com/?' def OMDBmovie(mTitle, mYear): # Craft the URL url = URL_BASE + 't=' + mTitle + '&y=' + mYear + '&plot=full&r=json' # Try to get the url response = requests.get(url) response.raise_for_status() theJSON = json.loads(response.text) return(theJSON) def OMDBtv(tvTitle, tvSeason, tvEpisode): # Craft the URL url = URL_BASE + 't=' + str(tvTitle) + '&Season=' + str(tvSeason) '&Episode=' + str(tvEpisode) + '&plot=full&r=json' # Try to get the url response = requests.get(url) response.raise_for_status() theJSON = json.loads(response.text) return(theJSON)
#!/usr/bin/python3 # scrapeOMDB.py - parses a movie and year from arguments and returns JSON import json, requests URL_BASE = 'http://www.omdbapi.com/?' def OMDBmovie(mTitle, mYear): # Craft the URL url = URL_BASE + 't=' + mTitle + '&y=' + mYear + '&plot=full&r=json' # Try to get the url response = requests.get(url) response.raise_for_status() theJSON = json.loads(response.text) return(theJSON) def OMDBtv(tvTitle, tvSeason, tvEpisode): # Craft the URL url = URL_BASE + 't=' + tvTitle + '&Season=' + str(tvSeason) + '&Episode=' + str(tvEpisode) + '&plot=full&r=json' # Try to get the url response = requests.get(url) response.raise_for_status() theJSON = json.loads(response.text) return(theJSON)
Fix typo and convert TV season/ep to str
Fix typo and convert TV season/ep to str
Python
mit
samcheck/PyMedia,samcheck/PyMedia,samcheck/PyMedia
#!/usr/bin/python3 # scrapeOMDB.py - parses a movie and year from arguments and returns JSON import json, requests URL_BASE = 'http://www.omdbapi.com/?' def OMDBmovie(mTitle, mYear): # Craft the URL url = URL_BASE + 't=' + mTitle + '&y=' + mYear + '&plot=full&r=json' # Try to get the url response = requests.get(url) response.raise_for_status() theJSON = json.loads(response.text) return(theJSON) def OMDBtv(tvTitle, tvSeason, tvEpisode): # Craft the URL url = URL_BASE + 't=' + str(tvTitle) + '&Season=' + str(tvSeason) '&Episode=' + str(tvEpisode) + '&plot=full&r=json' # Try to get the url response = requests.get(url) response.raise_for_status() theJSON = json.loads(response.text) return(theJSON) Fix typo and convert TV season/ep to str
#!/usr/bin/python3 # scrapeOMDB.py - parses a movie and year from arguments and returns JSON import json, requests URL_BASE = 'http://www.omdbapi.com/?' def OMDBmovie(mTitle, mYear): # Craft the URL url = URL_BASE + 't=' + mTitle + '&y=' + mYear + '&plot=full&r=json' # Try to get the url response = requests.get(url) response.raise_for_status() theJSON = json.loads(response.text) return(theJSON) def OMDBtv(tvTitle, tvSeason, tvEpisode): # Craft the URL url = URL_BASE + 't=' + tvTitle + '&Season=' + str(tvSeason) + '&Episode=' + str(tvEpisode) + '&plot=full&r=json' # Try to get the url response = requests.get(url) response.raise_for_status() theJSON = json.loads(response.text) return(theJSON)
<commit_before>#!/usr/bin/python3 # scrapeOMDB.py - parses a movie and year from arguments and returns JSON import json, requests URL_BASE = 'http://www.omdbapi.com/?' def OMDBmovie(mTitle, mYear): # Craft the URL url = URL_BASE + 't=' + mTitle + '&y=' + mYear + '&plot=full&r=json' # Try to get the url response = requests.get(url) response.raise_for_status() theJSON = json.loads(response.text) return(theJSON) def OMDBtv(tvTitle, tvSeason, tvEpisode): # Craft the URL url = URL_BASE + 't=' + str(tvTitle) + '&Season=' + str(tvSeason) '&Episode=' + str(tvEpisode) + '&plot=full&r=json' # Try to get the url response = requests.get(url) response.raise_for_status() theJSON = json.loads(response.text) return(theJSON) <commit_msg>Fix typo and convert TV season/ep to str<commit_after>
#!/usr/bin/python3 # scrapeOMDB.py - parses a movie and year from arguments and returns JSON import json, requests URL_BASE = 'http://www.omdbapi.com/?' def OMDBmovie(mTitle, mYear): # Craft the URL url = URL_BASE + 't=' + mTitle + '&y=' + mYear + '&plot=full&r=json' # Try to get the url response = requests.get(url) response.raise_for_status() theJSON = json.loads(response.text) return(theJSON) def OMDBtv(tvTitle, tvSeason, tvEpisode): # Craft the URL url = URL_BASE + 't=' + tvTitle + '&Season=' + str(tvSeason) + '&Episode=' + str(tvEpisode) + '&plot=full&r=json' # Try to get the url response = requests.get(url) response.raise_for_status() theJSON = json.loads(response.text) return(theJSON)
#!/usr/bin/python3 # scrapeOMDB.py - parses a movie and year from arguments and returns JSON import json, requests URL_BASE = 'http://www.omdbapi.com/?' def OMDBmovie(mTitle, mYear): # Craft the URL url = URL_BASE + 't=' + mTitle + '&y=' + mYear + '&plot=full&r=json' # Try to get the url response = requests.get(url) response.raise_for_status() theJSON = json.loads(response.text) return(theJSON) def OMDBtv(tvTitle, tvSeason, tvEpisode): # Craft the URL url = URL_BASE + 't=' + str(tvTitle) + '&Season=' + str(tvSeason) '&Episode=' + str(tvEpisode) + '&plot=full&r=json' # Try to get the url response = requests.get(url) response.raise_for_status() theJSON = json.loads(response.text) return(theJSON) Fix typo and convert TV season/ep to str#!/usr/bin/python3 # scrapeOMDB.py - parses a movie and year from arguments and returns JSON import json, requests URL_BASE = 'http://www.omdbapi.com/?' def OMDBmovie(mTitle, mYear): # Craft the URL url = URL_BASE + 't=' + mTitle + '&y=' + mYear + '&plot=full&r=json' # Try to get the url response = requests.get(url) response.raise_for_status() theJSON = json.loads(response.text) return(theJSON) def OMDBtv(tvTitle, tvSeason, tvEpisode): # Craft the URL url = URL_BASE + 't=' + tvTitle + '&Season=' + str(tvSeason) + '&Episode=' + str(tvEpisode) + '&plot=full&r=json' # Try to get the url response = requests.get(url) response.raise_for_status() theJSON = json.loads(response.text) return(theJSON)
<commit_before>#!/usr/bin/python3 # scrapeOMDB.py - parses a movie and year from arguments and returns JSON import json, requests URL_BASE = 'http://www.omdbapi.com/?' def OMDBmovie(mTitle, mYear): # Craft the URL url = URL_BASE + 't=' + mTitle + '&y=' + mYear + '&plot=full&r=json' # Try to get the url response = requests.get(url) response.raise_for_status() theJSON = json.loads(response.text) return(theJSON) def OMDBtv(tvTitle, tvSeason, tvEpisode): # Craft the URL url = URL_BASE + 't=' + str(tvTitle) + '&Season=' + str(tvSeason) '&Episode=' + str(tvEpisode) + '&plot=full&r=json' # Try to get the url response = requests.get(url) response.raise_for_status() theJSON = json.loads(response.text) return(theJSON) <commit_msg>Fix typo and convert TV season/ep to str<commit_after>#!/usr/bin/python3 # scrapeOMDB.py - parses a movie and year from arguments and returns JSON import json, requests URL_BASE = 'http://www.omdbapi.com/?' def OMDBmovie(mTitle, mYear): # Craft the URL url = URL_BASE + 't=' + mTitle + '&y=' + mYear + '&plot=full&r=json' # Try to get the url response = requests.get(url) response.raise_for_status() theJSON = json.loads(response.text) return(theJSON) def OMDBtv(tvTitle, tvSeason, tvEpisode): # Craft the URL url = URL_BASE + 't=' + tvTitle + '&Season=' + str(tvSeason) + '&Episode=' + str(tvEpisode) + '&plot=full&r=json' # Try to get the url response = requests.get(url) response.raise_for_status() theJSON = json.loads(response.text) return(theJSON)
ac3db8b26bd6ac2e0db2c8221521aead9c996ec0
blog/views.py
blog/views.py
from django.shortcuts import ( get_object_or_404, render) from django.views.generic import View from .models import Post def post_detail(request, year, month, slug): post = get_object_or_404( Post, pub_date__year=year, pub_date__month=month, slug=slug) return render( request, 'blog/post_detail.html', {'post': post}) class PostList(View): def get(self, request): return render( request, 'blog/post_list.html', {'post_list': Post.objects.all()})
from django.shortcuts import ( get_object_or_404, render) from django.views.generic import View from .models import Post def post_detail(request, year, month, slug): post = get_object_or_404( Post, pub_date__year=year, pub_date__month=month, slug=slug) return render( request, 'blog/post_detail.html', {'post': post}) class PostList(View): template_name = 'blog/post_list.html' def get(self, request): return render( request, self.template_name, {'post_list': Post.objects.all()})
Use attribute for template in Post List.
Ch05: Use attribute for template in Post List.
Python
bsd-2-clause
jambonrose/DjangoUnleashed-1.8,jambonrose/DjangoUnleashed-1.8
from django.shortcuts import ( get_object_or_404, render) from django.views.generic import View from .models import Post def post_detail(request, year, month, slug): post = get_object_or_404( Post, pub_date__year=year, pub_date__month=month, slug=slug) return render( request, 'blog/post_detail.html', {'post': post}) class PostList(View): def get(self, request): return render( request, 'blog/post_list.html', {'post_list': Post.objects.all()}) Ch05: Use attribute for template in Post List.
from django.shortcuts import ( get_object_or_404, render) from django.views.generic import View from .models import Post def post_detail(request, year, month, slug): post = get_object_or_404( Post, pub_date__year=year, pub_date__month=month, slug=slug) return render( request, 'blog/post_detail.html', {'post': post}) class PostList(View): template_name = 'blog/post_list.html' def get(self, request): return render( request, self.template_name, {'post_list': Post.objects.all()})
<commit_before>from django.shortcuts import ( get_object_or_404, render) from django.views.generic import View from .models import Post def post_detail(request, year, month, slug): post = get_object_or_404( Post, pub_date__year=year, pub_date__month=month, slug=slug) return render( request, 'blog/post_detail.html', {'post': post}) class PostList(View): def get(self, request): return render( request, 'blog/post_list.html', {'post_list': Post.objects.all()}) <commit_msg>Ch05: Use attribute for template in Post List.<commit_after>
from django.shortcuts import ( get_object_or_404, render) from django.views.generic import View from .models import Post def post_detail(request, year, month, slug): post = get_object_or_404( Post, pub_date__year=year, pub_date__month=month, slug=slug) return render( request, 'blog/post_detail.html', {'post': post}) class PostList(View): template_name = 'blog/post_list.html' def get(self, request): return render( request, self.template_name, {'post_list': Post.objects.all()})
from django.shortcuts import ( get_object_or_404, render) from django.views.generic import View from .models import Post def post_detail(request, year, month, slug): post = get_object_or_404( Post, pub_date__year=year, pub_date__month=month, slug=slug) return render( request, 'blog/post_detail.html', {'post': post}) class PostList(View): def get(self, request): return render( request, 'blog/post_list.html', {'post_list': Post.objects.all()}) Ch05: Use attribute for template in Post List.from django.shortcuts import ( get_object_or_404, render) from django.views.generic import View from .models import Post def post_detail(request, year, month, slug): post = get_object_or_404( Post, pub_date__year=year, pub_date__month=month, slug=slug) return render( request, 'blog/post_detail.html', {'post': post}) class PostList(View): template_name = 'blog/post_list.html' def get(self, request): return render( request, self.template_name, {'post_list': Post.objects.all()})
<commit_before>from django.shortcuts import ( get_object_or_404, render) from django.views.generic import View from .models import Post def post_detail(request, year, month, slug): post = get_object_or_404( Post, pub_date__year=year, pub_date__month=month, slug=slug) return render( request, 'blog/post_detail.html', {'post': post}) class PostList(View): def get(self, request): return render( request, 'blog/post_list.html', {'post_list': Post.objects.all()}) <commit_msg>Ch05: Use attribute for template in Post List.<commit_after>from django.shortcuts import ( get_object_or_404, render) from django.views.generic import View from .models import Post def post_detail(request, year, month, slug): post = get_object_or_404( Post, pub_date__year=year, pub_date__month=month, slug=slug) return render( request, 'blog/post_detail.html', {'post': post}) class PostList(View): template_name = 'blog/post_list.html' def get(self, request): return render( request, self.template_name, {'post_list': Post.objects.all()})
8a778750c2284045566c6f67b2aedffd2811f1ce
api/base/settings/__init__.py
api/base/settings/__init__.py
# -*- coding: utf-8 -*- '''Consolidates settings from defaults.py and local.py. :: >>> from api.base import settings >>> settings.API_BASE 'v2/' ''' from .defaults import * # noqa try: from .local import * # noqa except ImportError as error: raise ImportError("No api/base/settings/local.py settings file found. Did you remember to " "copy local-dist.py to local.py?")
# -*- coding: utf-8 -*- '''Consolidates settings from defaults.py and local.py. :: >>> from api.base import settings >>> settings.API_BASE 'v2/' ''' from .defaults import * # noqa try: from .local import * # noqa except ImportError as error: raise ImportError("No api/base/settings/local.py settings file found. Did you remember to " "copy local-dist.py to local.py?")
Put in at least two spaces before inline comment
Put in at least two spaces before inline comment
Python
apache-2.0
leb2dg/osf.io,jinluyuan/osf.io,ckc6cz/osf.io,brandonPurvis/osf.io,kch8qx/osf.io,KAsante95/osf.io,billyhunt/osf.io,abought/osf.io,emetsger/osf.io,felliott/osf.io,TomBaxter/osf.io,bdyetton/prettychart,alexschiller/osf.io,doublebits/osf.io,leb2dg/osf.io,ticklemepierce/osf.io,erinspace/osf.io,brianjgeiger/osf.io,samanehsan/osf.io,adlius/osf.io,laurenrevere/osf.io,crcresearch/osf.io,jnayak1/osf.io,asanfilippo7/osf.io,cosenal/osf.io,njantrania/osf.io,barbour-em/osf.io,ZobairAlijan/osf.io,Johnetordoff/osf.io,petermalcolm/osf.io,brandonPurvis/osf.io,sbt9uc/osf.io,Nesiehr/osf.io,mluo613/osf.io,caseyrygt/osf.io,caneruguz/osf.io,icereval/osf.io,lyndsysimon/osf.io,njantrania/osf.io,barbour-em/osf.io,monikagrabowska/osf.io,caseyrollins/osf.io,RomanZWang/osf.io,TomBaxter/osf.io,mluo613/osf.io,pattisdr/osf.io,ckc6cz/osf.io,Nesiehr/osf.io,DanielSBrown/osf.io,KAsante95/osf.io,fabianvf/osf.io,RomanZWang/osf.io,doublebits/osf.io,mfraezz/osf.io,njantrania/osf.io,danielneis/osf.io,kwierman/osf.io,jolene-esposito/osf.io,adlius/osf.io,emetsger/osf.io,CenterForOpenScience/osf.io,lyndsysimon/osf.io,TomBaxter/osf.io,monikagrabowska/osf.io,fabianvf/osf.io,TomHeatwole/osf.io,caseyrygt/osf.io,brianjgeiger/osf.io,reinaH/osf.io,sloria/osf.io,mattclark/osf.io,TomHeatwole/osf.io,chrisseto/osf.io,crcresearch/osf.io,abought/osf.io,brianjgeiger/osf.io,sloria/osf.io,zachjanicki/osf.io,samanehsan/osf.io,ticklemepierce/osf.io,acshi/osf.io,felliott/osf.io,caseyrollins/osf.io,jnayak1/osf.io,zamattiac/osf.io,kch8qx/osf.io,Ghalko/osf.io,leb2dg/osf.io,doublebits/osf.io,leb2dg/osf.io,billyhunt/osf.io,acshi/osf.io,monikagrabowska/osf.io,samchrisinger/osf.io,danielneis/osf.io,felliott/osf.io,GageGaskins/osf.io,arpitar/osf.io,saradbowman/osf.io,wearpants/osf.io,cldershem/osf.io,HarryRybacki/osf.io,mluo613/osf.io,jeffreyliu3230/osf.io,cosenal/osf.io,acshi/osf.io,danielneis/osf.io,TomHeatwole/osf.io,chrisseto/osf.io,jmcarp/osf.io,baylee-d/osf.io,sbt9uc/osf.io,zachjanicki/osf.io,cwisecarver/osf.io,caneruguz/osf.io,hmoco/osf.io,caseyrollins/osf.io,ticklemepierce/osf.io,Ghalko/osf.io,mluo613/osf.io,kch8qx/osf.io,haoyuchen1992/osf.io,amyshi188/osf.io,chrisseto/osf.io,rdhyee/osf.io,ticklemepierce/osf.io,danielneis/osf.io,abought/osf.io,jnayak1/osf.io,samchrisinger/osf.io,GageGaskins/osf.io,Johnetordoff/osf.io,hmoco/osf.io,ckc6cz/osf.io,KAsante95/osf.io,amyshi188/osf.io,MerlinZhang/osf.io,HalcyonChimera/osf.io,icereval/osf.io,arpitar/osf.io,KAsante95/osf.io,caneruguz/osf.io,mluke93/osf.io,jolene-esposito/osf.io,caneruguz/osf.io,reinaH/osf.io,dplorimer/osf,HalcyonChimera/osf.io,amyshi188/osf.io,mattclark/osf.io,lyndsysimon/osf.io,asanfilippo7/osf.io,kch8qx/osf.io,sbt9uc/osf.io,cwisecarver/osf.io,mluke93/osf.io,chrisseto/osf.io,zamattiac/osf.io,amyshi188/osf.io,dplorimer/osf,aaxelb/osf.io,KAsante95/osf.io,dplorimer/osf,SSJohns/osf.io,ckc6cz/osf.io,cslzchen/osf.io,cldershem/osf.io,cosenal/osf.io,chennan47/osf.io,dplorimer/osf,adlius/osf.io,Ghalko/osf.io,haoyuchen1992/osf.io,cslzchen/osf.io,samanehsan/osf.io,zamattiac/osf.io,MerlinZhang/osf.io,bdyetton/prettychart,doublebits/osf.io,jeffreyliu3230/osf.io,emetsger/osf.io,zachjanicki/osf.io,njantrania/osf.io,Nesiehr/osf.io,brandonPurvis/osf.io,acshi/osf.io,sbt9uc/osf.io,cldershem/osf.io,CenterForOpenScience/osf.io,alexschiller/osf.io,jmcarp/osf.io,arpitar/osf.io,adlius/osf.io,asanfilippo7/osf.io,cslzchen/osf.io,GageGaskins/osf.io,saradbowman/osf.io,DanielSBrown/osf.io,zachjanicki/osf.io,kch8qx/osf.io,ZobairAlijan/osf.io,chennan47/osf.io,cwisecarver/osf.io,Nesiehr/osf.io,chennan47/osf.io,jinluyuan/osf.io,asanfilippo7/osf.io,SSJohns/osf.io,MerlinZhang/osf.io,jolene-esposito/osf.io,cwisecarver/osf.io,CenterForOpenScience/osf.io,wearpants/osf.io,jinluyuan/osf.io,aaxelb/osf.io,pattisdr/osf.io,SSJohns/osf.io,DanielSBrown/osf.io,RomanZWang/osf.io,TomHeatwole/osf.io,mfraezz/osf.io,kwierman/osf.io,HalcyonChimera/osf.io,baylee-d/osf.io,rdhyee/osf.io,hmoco/osf.io,erinspace/osf.io,mluke93/osf.io,DanielSBrown/osf.io,reinaH/osf.io,acshi/osf.io,ZobairAlijan/osf.io,icereval/osf.io,caseyrygt/osf.io,pattisdr/osf.io,sloria/osf.io,binoculars/osf.io,haoyuchen1992/osf.io,jinluyuan/osf.io,alexschiller/osf.io,doublebits/osf.io,jolene-esposito/osf.io,brandonPurvis/osf.io,haoyuchen1992/osf.io,jmcarp/osf.io,GageGaskins/osf.io,brianjgeiger/osf.io,jeffreyliu3230/osf.io,cldershem/osf.io,petermalcolm/osf.io,felliott/osf.io,wearpants/osf.io,GageGaskins/osf.io,cosenal/osf.io,alexschiller/osf.io,erinspace/osf.io,petermalcolm/osf.io,bdyetton/prettychart,CenterForOpenScience/osf.io,caseyrygt/osf.io,brandonPurvis/osf.io,barbour-em/osf.io,billyhunt/osf.io,petermalcolm/osf.io,bdyetton/prettychart,hmoco/osf.io,kwierman/osf.io,mluo613/osf.io,ZobairAlijan/osf.io,arpitar/osf.io,HalcyonChimera/osf.io,mfraezz/osf.io,jeffreyliu3230/osf.io,kwierman/osf.io,fabianvf/osf.io,monikagrabowska/osf.io,aaxelb/osf.io,monikagrabowska/osf.io,jmcarp/osf.io,HarryRybacki/osf.io,rdhyee/osf.io,reinaH/osf.io,jnayak1/osf.io,HarryRybacki/osf.io,billyhunt/osf.io,samchrisinger/osf.io,lyndsysimon/osf.io,crcresearch/osf.io,samanehsan/osf.io,barbour-em/osf.io,alexschiller/osf.io,RomanZWang/osf.io,samchrisinger/osf.io,binoculars/osf.io,billyhunt/osf.io,laurenrevere/osf.io,baylee-d/osf.io,Johnetordoff/osf.io,mluke93/osf.io,aaxelb/osf.io,SSJohns/osf.io,binoculars/osf.io,rdhyee/osf.io,cslzchen/osf.io,zamattiac/osf.io,abought/osf.io,RomanZWang/osf.io,emetsger/osf.io,wearpants/osf.io,laurenrevere/osf.io,Johnetordoff/osf.io,mfraezz/osf.io,MerlinZhang/osf.io,mattclark/osf.io,fabianvf/osf.io,Ghalko/osf.io,HarryRybacki/osf.io
# -*- coding: utf-8 -*- '''Consolidates settings from defaults.py and local.py. :: >>> from api.base import settings >>> settings.API_BASE 'v2/' ''' from .defaults import * # noqa try: from .local import * # noqa except ImportError as error: raise ImportError("No api/base/settings/local.py settings file found. Did you remember to " "copy local-dist.py to local.py?") Put in at least two spaces before inline comment
# -*- coding: utf-8 -*- '''Consolidates settings from defaults.py and local.py. :: >>> from api.base import settings >>> settings.API_BASE 'v2/' ''' from .defaults import * # noqa try: from .local import * # noqa except ImportError as error: raise ImportError("No api/base/settings/local.py settings file found. Did you remember to " "copy local-dist.py to local.py?")
<commit_before># -*- coding: utf-8 -*- '''Consolidates settings from defaults.py and local.py. :: >>> from api.base import settings >>> settings.API_BASE 'v2/' ''' from .defaults import * # noqa try: from .local import * # noqa except ImportError as error: raise ImportError("No api/base/settings/local.py settings file found. Did you remember to " "copy local-dist.py to local.py?") <commit_msg>Put in at least two spaces before inline comment<commit_after>
# -*- coding: utf-8 -*- '''Consolidates settings from defaults.py and local.py. :: >>> from api.base import settings >>> settings.API_BASE 'v2/' ''' from .defaults import * # noqa try: from .local import * # noqa except ImportError as error: raise ImportError("No api/base/settings/local.py settings file found. Did you remember to " "copy local-dist.py to local.py?")
# -*- coding: utf-8 -*- '''Consolidates settings from defaults.py and local.py. :: >>> from api.base import settings >>> settings.API_BASE 'v2/' ''' from .defaults import * # noqa try: from .local import * # noqa except ImportError as error: raise ImportError("No api/base/settings/local.py settings file found. Did you remember to " "copy local-dist.py to local.py?") Put in at least two spaces before inline comment# -*- coding: utf-8 -*- '''Consolidates settings from defaults.py and local.py. :: >>> from api.base import settings >>> settings.API_BASE 'v2/' ''' from .defaults import * # noqa try: from .local import * # noqa except ImportError as error: raise ImportError("No api/base/settings/local.py settings file found. Did you remember to " "copy local-dist.py to local.py?")
<commit_before># -*- coding: utf-8 -*- '''Consolidates settings from defaults.py and local.py. :: >>> from api.base import settings >>> settings.API_BASE 'v2/' ''' from .defaults import * # noqa try: from .local import * # noqa except ImportError as error: raise ImportError("No api/base/settings/local.py settings file found. Did you remember to " "copy local-dist.py to local.py?") <commit_msg>Put in at least two spaces before inline comment<commit_after># -*- coding: utf-8 -*- '''Consolidates settings from defaults.py and local.py. :: >>> from api.base import settings >>> settings.API_BASE 'v2/' ''' from .defaults import * # noqa try: from .local import * # noqa except ImportError as error: raise ImportError("No api/base/settings/local.py settings file found. Did you remember to " "copy local-dist.py to local.py?")
ef43e04970151ec5bba9688f268b2f85b5debd3f
bfg9000/builtins/__init__.py
bfg9000/builtins/__init__.py
import functools import glob import os import pkgutil _all_builtins = {} _loaded_builtins = False class Binder(object): def __init__(self, fn): self.fn = fn def bind(self, build_inputs, env): return functools.partial(self.fn, build_inputs, env) def builtin(fn): bound = Binder(fn) _all_builtins[fn.__name__] = bound return bound def _load_builtins(): for loader, name, ispkg in pkgutil.walk_packages(__path__, __name__ + '.'): loader.find_module(name).load_module(name) def bind(build_inputs, env): global _loaded_builtins if not _loaded_builtins: _load_builtins() _loaded_builtins = True result = {} for k, v in _all_builtins.iteritems(): result[k] = v.bind(build_inputs, env) return result
import functools import glob import os import pkgutil _all_builtins = {} _loaded_builtins = False class Binder(object): def __init__(self, fn): self.fn = fn def bind(self, build_inputs, env): return functools.partial(self.fn, build_inputs, env) def builtin(fn): bound = Binder(fn) _all_builtins[fn.__name__] = bound return bound def _load_builtins(): for loader, name, ispkg in pkgutil.walk_packages(__path__, __name__ + '.'): loader.find_module(name).load_module(name) def bind(build_inputs, env): global _loaded_builtins if not _loaded_builtins: _load_builtins() _loaded_builtins = True result = {} for k, v in _all_builtins.iteritems(): result[k] = v.bind(build_inputs, env) result['env'] = env return result
Make the Environment object available to build.bfg files
Make the Environment object available to build.bfg files
Python
bsd-3-clause
jimporter/bfg9000,jimporter/bfg9000,jimporter/bfg9000,jimporter/bfg9000
import functools import glob import os import pkgutil _all_builtins = {} _loaded_builtins = False class Binder(object): def __init__(self, fn): self.fn = fn def bind(self, build_inputs, env): return functools.partial(self.fn, build_inputs, env) def builtin(fn): bound = Binder(fn) _all_builtins[fn.__name__] = bound return bound def _load_builtins(): for loader, name, ispkg in pkgutil.walk_packages(__path__, __name__ + '.'): loader.find_module(name).load_module(name) def bind(build_inputs, env): global _loaded_builtins if not _loaded_builtins: _load_builtins() _loaded_builtins = True result = {} for k, v in _all_builtins.iteritems(): result[k] = v.bind(build_inputs, env) return result Make the Environment object available to build.bfg files
import functools import glob import os import pkgutil _all_builtins = {} _loaded_builtins = False class Binder(object): def __init__(self, fn): self.fn = fn def bind(self, build_inputs, env): return functools.partial(self.fn, build_inputs, env) def builtin(fn): bound = Binder(fn) _all_builtins[fn.__name__] = bound return bound def _load_builtins(): for loader, name, ispkg in pkgutil.walk_packages(__path__, __name__ + '.'): loader.find_module(name).load_module(name) def bind(build_inputs, env): global _loaded_builtins if not _loaded_builtins: _load_builtins() _loaded_builtins = True result = {} for k, v in _all_builtins.iteritems(): result[k] = v.bind(build_inputs, env) result['env'] = env return result
<commit_before>import functools import glob import os import pkgutil _all_builtins = {} _loaded_builtins = False class Binder(object): def __init__(self, fn): self.fn = fn def bind(self, build_inputs, env): return functools.partial(self.fn, build_inputs, env) def builtin(fn): bound = Binder(fn) _all_builtins[fn.__name__] = bound return bound def _load_builtins(): for loader, name, ispkg in pkgutil.walk_packages(__path__, __name__ + '.'): loader.find_module(name).load_module(name) def bind(build_inputs, env): global _loaded_builtins if not _loaded_builtins: _load_builtins() _loaded_builtins = True result = {} for k, v in _all_builtins.iteritems(): result[k] = v.bind(build_inputs, env) return result <commit_msg>Make the Environment object available to build.bfg files<commit_after>
import functools import glob import os import pkgutil _all_builtins = {} _loaded_builtins = False class Binder(object): def __init__(self, fn): self.fn = fn def bind(self, build_inputs, env): return functools.partial(self.fn, build_inputs, env) def builtin(fn): bound = Binder(fn) _all_builtins[fn.__name__] = bound return bound def _load_builtins(): for loader, name, ispkg in pkgutil.walk_packages(__path__, __name__ + '.'): loader.find_module(name).load_module(name) def bind(build_inputs, env): global _loaded_builtins if not _loaded_builtins: _load_builtins() _loaded_builtins = True result = {} for k, v in _all_builtins.iteritems(): result[k] = v.bind(build_inputs, env) result['env'] = env return result
import functools import glob import os import pkgutil _all_builtins = {} _loaded_builtins = False class Binder(object): def __init__(self, fn): self.fn = fn def bind(self, build_inputs, env): return functools.partial(self.fn, build_inputs, env) def builtin(fn): bound = Binder(fn) _all_builtins[fn.__name__] = bound return bound def _load_builtins(): for loader, name, ispkg in pkgutil.walk_packages(__path__, __name__ + '.'): loader.find_module(name).load_module(name) def bind(build_inputs, env): global _loaded_builtins if not _loaded_builtins: _load_builtins() _loaded_builtins = True result = {} for k, v in _all_builtins.iteritems(): result[k] = v.bind(build_inputs, env) return result Make the Environment object available to build.bfg filesimport functools import glob import os import pkgutil _all_builtins = {} _loaded_builtins = False class Binder(object): def __init__(self, fn): self.fn = fn def bind(self, build_inputs, env): return functools.partial(self.fn, build_inputs, env) def builtin(fn): bound = Binder(fn) _all_builtins[fn.__name__] = bound return bound def _load_builtins(): for loader, name, ispkg in pkgutil.walk_packages(__path__, __name__ + '.'): loader.find_module(name).load_module(name) def bind(build_inputs, env): global _loaded_builtins if not _loaded_builtins: _load_builtins() _loaded_builtins = True result = {} for k, v in _all_builtins.iteritems(): result[k] = v.bind(build_inputs, env) result['env'] = env return result
<commit_before>import functools import glob import os import pkgutil _all_builtins = {} _loaded_builtins = False class Binder(object): def __init__(self, fn): self.fn = fn def bind(self, build_inputs, env): return functools.partial(self.fn, build_inputs, env) def builtin(fn): bound = Binder(fn) _all_builtins[fn.__name__] = bound return bound def _load_builtins(): for loader, name, ispkg in pkgutil.walk_packages(__path__, __name__ + '.'): loader.find_module(name).load_module(name) def bind(build_inputs, env): global _loaded_builtins if not _loaded_builtins: _load_builtins() _loaded_builtins = True result = {} for k, v in _all_builtins.iteritems(): result[k] = v.bind(build_inputs, env) return result <commit_msg>Make the Environment object available to build.bfg files<commit_after>import functools import glob import os import pkgutil _all_builtins = {} _loaded_builtins = False class Binder(object): def __init__(self, fn): self.fn = fn def bind(self, build_inputs, env): return functools.partial(self.fn, build_inputs, env) def builtin(fn): bound = Binder(fn) _all_builtins[fn.__name__] = bound return bound def _load_builtins(): for loader, name, ispkg in pkgutil.walk_packages(__path__, __name__ + '.'): loader.find_module(name).load_module(name) def bind(build_inputs, env): global _loaded_builtins if not _loaded_builtins: _load_builtins() _loaded_builtins = True result = {} for k, v in _all_builtins.iteritems(): result[k] = v.bind(build_inputs, env) result['env'] = env return result
c30b4aa0d577e545193229d0f33b55998405cba2
trex/urls.py
trex/urls.py
# -*- coding: utf-8 -*- # # (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com> # # See LICENSE comming with the source of 'trex' for details. # from django.conf.urls import patterns, url from django.views.generic import TemplateView from trex.views import project urlpatterns = patterns( '', url(r"^$", TemplateView.as_view(template_name="index.html"), name="index", ), url(r"^api/1/projects/$", project.ProjectListCreateAPIView.as_view(), name="project-list"), url(r"^api/1/projects/(?P<pk>[0-9]+)/$", project.ProjectDetailAPIView.as_view(), name="project-detail"), url(r"^api/1/projects/(?P<pk>[0-9]+)/entries$", project.ProjectEntriesListAPIView.as_view(), name="project-entries-list"), url(r"^api/1/projects/(?P<pk>[0-9]+)/zeiterfassung/$", project.ProjectZeiterfassungAPIView.as_view(), name="project-zeiterfassung"), url(r"^api/1/entries/(?P<pk>[0-9]+)/$", project.EntryDetailAPIView.as_view(), name="entry-detail"), )
# -*- coding: utf-8 -*- # # (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com> # # See LICENSE comming with the source of 'trex' for details. # from django.conf.urls import patterns, url from django.views.generic import TemplateView from trex.views import project urlpatterns = patterns( '', url(r"^$", TemplateView.as_view(template_name="index.html"), name="index", ), url(r"^api/1/projects/$", project.ProjectListCreateAPIView.as_view(), name="project-list"), url(r"^api/1/projects/(?P<pk>[0-9]+)/$", project.ProjectDetailAPIView.as_view(), name="project-detail"), url(r"^api/1/projects/(?P<pk>[0-9]+)/entries$", project.ProjectEntriesListAPIView.as_view(), name="project-entries-list"), url(r"^api/1/projects/(?P<pk>[0-9]+)/zeiterfassung/$", project.ProjectZeiterfassungAPIView.as_view(), name="project-zeiterfassung"), url(r"^api/1/entries/(?P<pk>[0-9]+)/$", project.EntryDetailAPIView.as_view(), name="entry-detail"), url(r"^api/1/tags/(?P<pk>[0-9]+)/$", project.TagDetailAPIView.as_view(), name="tag-detail"), )
Add url mapping for the tag details view
Add url mapping for the tag details view
Python
mit
bjoernricks/trex,bjoernricks/trex
# -*- coding: utf-8 -*- # # (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com> # # See LICENSE comming with the source of 'trex' for details. # from django.conf.urls import patterns, url from django.views.generic import TemplateView from trex.views import project urlpatterns = patterns( '', url(r"^$", TemplateView.as_view(template_name="index.html"), name="index", ), url(r"^api/1/projects/$", project.ProjectListCreateAPIView.as_view(), name="project-list"), url(r"^api/1/projects/(?P<pk>[0-9]+)/$", project.ProjectDetailAPIView.as_view(), name="project-detail"), url(r"^api/1/projects/(?P<pk>[0-9]+)/entries$", project.ProjectEntriesListAPIView.as_view(), name="project-entries-list"), url(r"^api/1/projects/(?P<pk>[0-9]+)/zeiterfassung/$", project.ProjectZeiterfassungAPIView.as_view(), name="project-zeiterfassung"), url(r"^api/1/entries/(?P<pk>[0-9]+)/$", project.EntryDetailAPIView.as_view(), name="entry-detail"), ) Add url mapping for the tag details view
# -*- coding: utf-8 -*- # # (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com> # # See LICENSE comming with the source of 'trex' for details. # from django.conf.urls import patterns, url from django.views.generic import TemplateView from trex.views import project urlpatterns = patterns( '', url(r"^$", TemplateView.as_view(template_name="index.html"), name="index", ), url(r"^api/1/projects/$", project.ProjectListCreateAPIView.as_view(), name="project-list"), url(r"^api/1/projects/(?P<pk>[0-9]+)/$", project.ProjectDetailAPIView.as_view(), name="project-detail"), url(r"^api/1/projects/(?P<pk>[0-9]+)/entries$", project.ProjectEntriesListAPIView.as_view(), name="project-entries-list"), url(r"^api/1/projects/(?P<pk>[0-9]+)/zeiterfassung/$", project.ProjectZeiterfassungAPIView.as_view(), name="project-zeiterfassung"), url(r"^api/1/entries/(?P<pk>[0-9]+)/$", project.EntryDetailAPIView.as_view(), name="entry-detail"), url(r"^api/1/tags/(?P<pk>[0-9]+)/$", project.TagDetailAPIView.as_view(), name="tag-detail"), )
<commit_before># -*- coding: utf-8 -*- # # (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com> # # See LICENSE comming with the source of 'trex' for details. # from django.conf.urls import patterns, url from django.views.generic import TemplateView from trex.views import project urlpatterns = patterns( '', url(r"^$", TemplateView.as_view(template_name="index.html"), name="index", ), url(r"^api/1/projects/$", project.ProjectListCreateAPIView.as_view(), name="project-list"), url(r"^api/1/projects/(?P<pk>[0-9]+)/$", project.ProjectDetailAPIView.as_view(), name="project-detail"), url(r"^api/1/projects/(?P<pk>[0-9]+)/entries$", project.ProjectEntriesListAPIView.as_view(), name="project-entries-list"), url(r"^api/1/projects/(?P<pk>[0-9]+)/zeiterfassung/$", project.ProjectZeiterfassungAPIView.as_view(), name="project-zeiterfassung"), url(r"^api/1/entries/(?P<pk>[0-9]+)/$", project.EntryDetailAPIView.as_view(), name="entry-detail"), ) <commit_msg>Add url mapping for the tag details view<commit_after>
# -*- coding: utf-8 -*- # # (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com> # # See LICENSE comming with the source of 'trex' for details. # from django.conf.urls import patterns, url from django.views.generic import TemplateView from trex.views import project urlpatterns = patterns( '', url(r"^$", TemplateView.as_view(template_name="index.html"), name="index", ), url(r"^api/1/projects/$", project.ProjectListCreateAPIView.as_view(), name="project-list"), url(r"^api/1/projects/(?P<pk>[0-9]+)/$", project.ProjectDetailAPIView.as_view(), name="project-detail"), url(r"^api/1/projects/(?P<pk>[0-9]+)/entries$", project.ProjectEntriesListAPIView.as_view(), name="project-entries-list"), url(r"^api/1/projects/(?P<pk>[0-9]+)/zeiterfassung/$", project.ProjectZeiterfassungAPIView.as_view(), name="project-zeiterfassung"), url(r"^api/1/entries/(?P<pk>[0-9]+)/$", project.EntryDetailAPIView.as_view(), name="entry-detail"), url(r"^api/1/tags/(?P<pk>[0-9]+)/$", project.TagDetailAPIView.as_view(), name="tag-detail"), )
# -*- coding: utf-8 -*- # # (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com> # # See LICENSE comming with the source of 'trex' for details. # from django.conf.urls import patterns, url from django.views.generic import TemplateView from trex.views import project urlpatterns = patterns( '', url(r"^$", TemplateView.as_view(template_name="index.html"), name="index", ), url(r"^api/1/projects/$", project.ProjectListCreateAPIView.as_view(), name="project-list"), url(r"^api/1/projects/(?P<pk>[0-9]+)/$", project.ProjectDetailAPIView.as_view(), name="project-detail"), url(r"^api/1/projects/(?P<pk>[0-9]+)/entries$", project.ProjectEntriesListAPIView.as_view(), name="project-entries-list"), url(r"^api/1/projects/(?P<pk>[0-9]+)/zeiterfassung/$", project.ProjectZeiterfassungAPIView.as_view(), name="project-zeiterfassung"), url(r"^api/1/entries/(?P<pk>[0-9]+)/$", project.EntryDetailAPIView.as_view(), name="entry-detail"), ) Add url mapping for the tag details view# -*- coding: utf-8 -*- # # (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com> # # See LICENSE comming with the source of 'trex' for details. # from django.conf.urls import patterns, url from django.views.generic import TemplateView from trex.views import project urlpatterns = patterns( '', url(r"^$", TemplateView.as_view(template_name="index.html"), name="index", ), url(r"^api/1/projects/$", project.ProjectListCreateAPIView.as_view(), name="project-list"), url(r"^api/1/projects/(?P<pk>[0-9]+)/$", project.ProjectDetailAPIView.as_view(), name="project-detail"), url(r"^api/1/projects/(?P<pk>[0-9]+)/entries$", project.ProjectEntriesListAPIView.as_view(), name="project-entries-list"), url(r"^api/1/projects/(?P<pk>[0-9]+)/zeiterfassung/$", project.ProjectZeiterfassungAPIView.as_view(), name="project-zeiterfassung"), url(r"^api/1/entries/(?P<pk>[0-9]+)/$", project.EntryDetailAPIView.as_view(), name="entry-detail"), url(r"^api/1/tags/(?P<pk>[0-9]+)/$", project.TagDetailAPIView.as_view(), name="tag-detail"), )
<commit_before># -*- coding: utf-8 -*- # # (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com> # # See LICENSE comming with the source of 'trex' for details. # from django.conf.urls import patterns, url from django.views.generic import TemplateView from trex.views import project urlpatterns = patterns( '', url(r"^$", TemplateView.as_view(template_name="index.html"), name="index", ), url(r"^api/1/projects/$", project.ProjectListCreateAPIView.as_view(), name="project-list"), url(r"^api/1/projects/(?P<pk>[0-9]+)/$", project.ProjectDetailAPIView.as_view(), name="project-detail"), url(r"^api/1/projects/(?P<pk>[0-9]+)/entries$", project.ProjectEntriesListAPIView.as_view(), name="project-entries-list"), url(r"^api/1/projects/(?P<pk>[0-9]+)/zeiterfassung/$", project.ProjectZeiterfassungAPIView.as_view(), name="project-zeiterfassung"), url(r"^api/1/entries/(?P<pk>[0-9]+)/$", project.EntryDetailAPIView.as_view(), name="entry-detail"), ) <commit_msg>Add url mapping for the tag details view<commit_after># -*- coding: utf-8 -*- # # (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com> # # See LICENSE comming with the source of 'trex' for details. # from django.conf.urls import patterns, url from django.views.generic import TemplateView from trex.views import project urlpatterns = patterns( '', url(r"^$", TemplateView.as_view(template_name="index.html"), name="index", ), url(r"^api/1/projects/$", project.ProjectListCreateAPIView.as_view(), name="project-list"), url(r"^api/1/projects/(?P<pk>[0-9]+)/$", project.ProjectDetailAPIView.as_view(), name="project-detail"), url(r"^api/1/projects/(?P<pk>[0-9]+)/entries$", project.ProjectEntriesListAPIView.as_view(), name="project-entries-list"), url(r"^api/1/projects/(?P<pk>[0-9]+)/zeiterfassung/$", project.ProjectZeiterfassungAPIView.as_view(), name="project-zeiterfassung"), url(r"^api/1/entries/(?P<pk>[0-9]+)/$", project.EntryDetailAPIView.as_view(), name="entry-detail"), url(r"^api/1/tags/(?P<pk>[0-9]+)/$", project.TagDetailAPIView.as_view(), name="tag-detail"), )
c7d2e917df5e0c2182e351b5157271b6e62a06cd
app/soc/modules/gsoc/models/timeline.py
app/soc/modules/gsoc/models/timeline.py
#!/usr/bin/env python2.5 # # Copyright 2009 the Melange authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module contains the GSoC specific Timeline Model. """ from google.appengine.ext import db from django.utils.translation import ugettext import soc.models.timeline class GSoCTimeline(soc.models.timeline.Timeline): """GSoC Timeline model extends the basic Program Timeline model. """ application_review_deadline = db.DateTimeProperty( verbose_name=ugettext('Application Review Deadline')) student_application_matched_deadline = db.DateTimeProperty( verbose_name=ugettext('Student Application Matched Deadline')) accepted_students_announced_deadline = db.DateTimeProperty( verbose_name=ugettext('Accepted Students Announced Deadline'))
#!/usr/bin/env python2.5 # # Copyright 2009 the Melange authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module contains the GSoC specific Timeline Model. """ from google.appengine.ext import db from django.utils.translation import ugettext import soc.models.timeline class GSoCTimeline(soc.models.timeline.Timeline): """GSoC Timeline model extends the basic Program Timeline model. """ application_review_deadline = db.DateTimeProperty( verbose_name=ugettext('Organizations Review Student Applications Deadline')) student_application_matched_deadline = db.DateTimeProperty( verbose_name=ugettext('Students Matched to Mentors Deadline')) accepted_students_announced_deadline = db.DateTimeProperty( verbose_name=ugettext('Accepted Students Announced Deadline'))
Change verbage on program profile info.
Change verbage on program profile info. Fixes issue 1601.
Python
apache-2.0
rhyolight/nupic.son,rhyolight/nupic.son,rhyolight/nupic.son
#!/usr/bin/env python2.5 # # Copyright 2009 the Melange authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module contains the GSoC specific Timeline Model. """ from google.appengine.ext import db from django.utils.translation import ugettext import soc.models.timeline class GSoCTimeline(soc.models.timeline.Timeline): """GSoC Timeline model extends the basic Program Timeline model. """ application_review_deadline = db.DateTimeProperty( verbose_name=ugettext('Application Review Deadline')) student_application_matched_deadline = db.DateTimeProperty( verbose_name=ugettext('Student Application Matched Deadline')) accepted_students_announced_deadline = db.DateTimeProperty( verbose_name=ugettext('Accepted Students Announced Deadline')) Change verbage on program profile info. Fixes issue 1601.
#!/usr/bin/env python2.5 # # Copyright 2009 the Melange authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module contains the GSoC specific Timeline Model. """ from google.appengine.ext import db from django.utils.translation import ugettext import soc.models.timeline class GSoCTimeline(soc.models.timeline.Timeline): """GSoC Timeline model extends the basic Program Timeline model. """ application_review_deadline = db.DateTimeProperty( verbose_name=ugettext('Organizations Review Student Applications Deadline')) student_application_matched_deadline = db.DateTimeProperty( verbose_name=ugettext('Students Matched to Mentors Deadline')) accepted_students_announced_deadline = db.DateTimeProperty( verbose_name=ugettext('Accepted Students Announced Deadline'))
<commit_before>#!/usr/bin/env python2.5 # # Copyright 2009 the Melange authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module contains the GSoC specific Timeline Model. """ from google.appengine.ext import db from django.utils.translation import ugettext import soc.models.timeline class GSoCTimeline(soc.models.timeline.Timeline): """GSoC Timeline model extends the basic Program Timeline model. """ application_review_deadline = db.DateTimeProperty( verbose_name=ugettext('Application Review Deadline')) student_application_matched_deadline = db.DateTimeProperty( verbose_name=ugettext('Student Application Matched Deadline')) accepted_students_announced_deadline = db.DateTimeProperty( verbose_name=ugettext('Accepted Students Announced Deadline')) <commit_msg>Change verbage on program profile info. Fixes issue 1601.<commit_after>
#!/usr/bin/env python2.5 # # Copyright 2009 the Melange authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module contains the GSoC specific Timeline Model. """ from google.appengine.ext import db from django.utils.translation import ugettext import soc.models.timeline class GSoCTimeline(soc.models.timeline.Timeline): """GSoC Timeline model extends the basic Program Timeline model. """ application_review_deadline = db.DateTimeProperty( verbose_name=ugettext('Organizations Review Student Applications Deadline')) student_application_matched_deadline = db.DateTimeProperty( verbose_name=ugettext('Students Matched to Mentors Deadline')) accepted_students_announced_deadline = db.DateTimeProperty( verbose_name=ugettext('Accepted Students Announced Deadline'))
#!/usr/bin/env python2.5 # # Copyright 2009 the Melange authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module contains the GSoC specific Timeline Model. """ from google.appengine.ext import db from django.utils.translation import ugettext import soc.models.timeline class GSoCTimeline(soc.models.timeline.Timeline): """GSoC Timeline model extends the basic Program Timeline model. """ application_review_deadline = db.DateTimeProperty( verbose_name=ugettext('Application Review Deadline')) student_application_matched_deadline = db.DateTimeProperty( verbose_name=ugettext('Student Application Matched Deadline')) accepted_students_announced_deadline = db.DateTimeProperty( verbose_name=ugettext('Accepted Students Announced Deadline')) Change verbage on program profile info. Fixes issue 1601.#!/usr/bin/env python2.5 # # Copyright 2009 the Melange authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module contains the GSoC specific Timeline Model. """ from google.appengine.ext import db from django.utils.translation import ugettext import soc.models.timeline class GSoCTimeline(soc.models.timeline.Timeline): """GSoC Timeline model extends the basic Program Timeline model. """ application_review_deadline = db.DateTimeProperty( verbose_name=ugettext('Organizations Review Student Applications Deadline')) student_application_matched_deadline = db.DateTimeProperty( verbose_name=ugettext('Students Matched to Mentors Deadline')) accepted_students_announced_deadline = db.DateTimeProperty( verbose_name=ugettext('Accepted Students Announced Deadline'))
<commit_before>#!/usr/bin/env python2.5 # # Copyright 2009 the Melange authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module contains the GSoC specific Timeline Model. """ from google.appengine.ext import db from django.utils.translation import ugettext import soc.models.timeline class GSoCTimeline(soc.models.timeline.Timeline): """GSoC Timeline model extends the basic Program Timeline model. """ application_review_deadline = db.DateTimeProperty( verbose_name=ugettext('Application Review Deadline')) student_application_matched_deadline = db.DateTimeProperty( verbose_name=ugettext('Student Application Matched Deadline')) accepted_students_announced_deadline = db.DateTimeProperty( verbose_name=ugettext('Accepted Students Announced Deadline')) <commit_msg>Change verbage on program profile info. Fixes issue 1601.<commit_after>#!/usr/bin/env python2.5 # # Copyright 2009 the Melange authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module contains the GSoC specific Timeline Model. """ from google.appengine.ext import db from django.utils.translation import ugettext import soc.models.timeline class GSoCTimeline(soc.models.timeline.Timeline): """GSoC Timeline model extends the basic Program Timeline model. """ application_review_deadline = db.DateTimeProperty( verbose_name=ugettext('Organizations Review Student Applications Deadline')) student_application_matched_deadline = db.DateTimeProperty( verbose_name=ugettext('Students Matched to Mentors Deadline')) accepted_students_announced_deadline = db.DateTimeProperty( verbose_name=ugettext('Accepted Students Announced Deadline'))
0e2dbbd204d9c1c9bd31f4be78b0a76ce39786d2
test/test_ev3_lcd.py
test/test_ev3_lcd.py
from ev3.ev3dev import Lcd # -*- coding: utf-8 -*- import unittest from util import get_input import time from PIL import Image,ImageDraw,ImageFont class TestLcd(unittest.TestCase): def test_lcd(self): get_input('Test lcd') d= Lcd() d.draw.ellipse((20, 20, 60, 60)) d.update() time.sleep(2) d.reset() font = ImageFont.load_default() d.draw.text((10, 10), "hello", font=font) try: font = ImageFont.truetype('/usr/share/fonts/truetype/arphic/uming.ttc',15) d.draw.text((20, 20), u'你好,世界', font=font) except IOError: print('No uming.ttc found. Skip the CJK test') d.update() if __name__ == '__main__': unittest.main()
# -*- coding: utf-8 -*- import unittest from ev3.ev3dev import Lcd from util import get_input import time from PIL import Image,ImageDraw,ImageFont class TestLcd(unittest.TestCase): def test_lcd(self): get_input('Test lcd') d= Lcd() d.draw.ellipse((20, 20, 60, 60)) d.update() time.sleep(2) d.reset() font = ImageFont.load_default() d.draw.text((10, 10), "hello", font=font) try: font = ImageFont.truetype('/usr/share/fonts/truetype/arphic/uming.ttc',15) d.draw.text((20, 20), u'你好,世界', font=font) except IOError: print('No uming.ttc found. Skip the CJK test') d.update() if __name__ == '__main__': unittest.main()
Fix encoding issue when test lcd
Fix encoding issue when test lcd
Python
apache-2.0
MaxNoe/python-ev3,evz/python-ev3,topikachu/python-ev3,MaxNoe/python-ev3,evz/python-ev3,topikachu/python-ev3
from ev3.ev3dev import Lcd # -*- coding: utf-8 -*- import unittest from util import get_input import time from PIL import Image,ImageDraw,ImageFont class TestLcd(unittest.TestCase): def test_lcd(self): get_input('Test lcd') d= Lcd() d.draw.ellipse((20, 20, 60, 60)) d.update() time.sleep(2) d.reset() font = ImageFont.load_default() d.draw.text((10, 10), "hello", font=font) try: font = ImageFont.truetype('/usr/share/fonts/truetype/arphic/uming.ttc',15) d.draw.text((20, 20), u'你好,世界', font=font) except IOError: print('No uming.ttc found. Skip the CJK test') d.update() if __name__ == '__main__': unittest.main() Fix encoding issue when test lcd
# -*- coding: utf-8 -*- import unittest from ev3.ev3dev import Lcd from util import get_input import time from PIL import Image,ImageDraw,ImageFont class TestLcd(unittest.TestCase): def test_lcd(self): get_input('Test lcd') d= Lcd() d.draw.ellipse((20, 20, 60, 60)) d.update() time.sleep(2) d.reset() font = ImageFont.load_default() d.draw.text((10, 10), "hello", font=font) try: font = ImageFont.truetype('/usr/share/fonts/truetype/arphic/uming.ttc',15) d.draw.text((20, 20), u'你好,世界', font=font) except IOError: print('No uming.ttc found. Skip the CJK test') d.update() if __name__ == '__main__': unittest.main()
<commit_before>from ev3.ev3dev import Lcd # -*- coding: utf-8 -*- import unittest from util import get_input import time from PIL import Image,ImageDraw,ImageFont class TestLcd(unittest.TestCase): def test_lcd(self): get_input('Test lcd') d= Lcd() d.draw.ellipse((20, 20, 60, 60)) d.update() time.sleep(2) d.reset() font = ImageFont.load_default() d.draw.text((10, 10), "hello", font=font) try: font = ImageFont.truetype('/usr/share/fonts/truetype/arphic/uming.ttc',15) d.draw.text((20, 20), u'你好,世界', font=font) except IOError: print('No uming.ttc found. Skip the CJK test') d.update() if __name__ == '__main__': unittest.main() <commit_msg>Fix encoding issue when test lcd<commit_after>
# -*- coding: utf-8 -*- import unittest from ev3.ev3dev import Lcd from util import get_input import time from PIL import Image,ImageDraw,ImageFont class TestLcd(unittest.TestCase): def test_lcd(self): get_input('Test lcd') d= Lcd() d.draw.ellipse((20, 20, 60, 60)) d.update() time.sleep(2) d.reset() font = ImageFont.load_default() d.draw.text((10, 10), "hello", font=font) try: font = ImageFont.truetype('/usr/share/fonts/truetype/arphic/uming.ttc',15) d.draw.text((20, 20), u'你好,世界', font=font) except IOError: print('No uming.ttc found. Skip the CJK test') d.update() if __name__ == '__main__': unittest.main()
from ev3.ev3dev import Lcd # -*- coding: utf-8 -*- import unittest from util import get_input import time from PIL import Image,ImageDraw,ImageFont class TestLcd(unittest.TestCase): def test_lcd(self): get_input('Test lcd') d= Lcd() d.draw.ellipse((20, 20, 60, 60)) d.update() time.sleep(2) d.reset() font = ImageFont.load_default() d.draw.text((10, 10), "hello", font=font) try: font = ImageFont.truetype('/usr/share/fonts/truetype/arphic/uming.ttc',15) d.draw.text((20, 20), u'你好,世界', font=font) except IOError: print('No uming.ttc found. Skip the CJK test') d.update() if __name__ == '__main__': unittest.main() Fix encoding issue when test lcd# -*- coding: utf-8 -*- import unittest from ev3.ev3dev import Lcd from util import get_input import time from PIL import Image,ImageDraw,ImageFont class TestLcd(unittest.TestCase): def test_lcd(self): get_input('Test lcd') d= Lcd() d.draw.ellipse((20, 20, 60, 60)) d.update() time.sleep(2) d.reset() font = ImageFont.load_default() d.draw.text((10, 10), "hello", font=font) try: font = ImageFont.truetype('/usr/share/fonts/truetype/arphic/uming.ttc',15) d.draw.text((20, 20), u'你好,世界', font=font) except IOError: print('No uming.ttc found. Skip the CJK test') d.update() if __name__ == '__main__': unittest.main()
<commit_before>from ev3.ev3dev import Lcd # -*- coding: utf-8 -*- import unittest from util import get_input import time from PIL import Image,ImageDraw,ImageFont class TestLcd(unittest.TestCase): def test_lcd(self): get_input('Test lcd') d= Lcd() d.draw.ellipse((20, 20, 60, 60)) d.update() time.sleep(2) d.reset() font = ImageFont.load_default() d.draw.text((10, 10), "hello", font=font) try: font = ImageFont.truetype('/usr/share/fonts/truetype/arphic/uming.ttc',15) d.draw.text((20, 20), u'你好,世界', font=font) except IOError: print('No uming.ttc found. Skip the CJK test') d.update() if __name__ == '__main__': unittest.main() <commit_msg>Fix encoding issue when test lcd<commit_after># -*- coding: utf-8 -*- import unittest from ev3.ev3dev import Lcd from util import get_input import time from PIL import Image,ImageDraw,ImageFont class TestLcd(unittest.TestCase): def test_lcd(self): get_input('Test lcd') d= Lcd() d.draw.ellipse((20, 20, 60, 60)) d.update() time.sleep(2) d.reset() font = ImageFont.load_default() d.draw.text((10, 10), "hello", font=font) try: font = ImageFont.truetype('/usr/share/fonts/truetype/arphic/uming.ttc',15) d.draw.text((20, 20), u'你好,世界', font=font) except IOError: print('No uming.ttc found. Skip the CJK test') d.update() if __name__ == '__main__': unittest.main()
89cb9f325403e3094a5fb2090ef4ea5f804b9d20
pq.py
pq.py
# Chapter 2: The pq-system def make_axiom(n): assert type(n) == int assert n > 0 x = '-' * n return x + 'p' + '-q' + x + '-' def next_theorem(theorem): assert 'p' in theorem assert 'q' in theorem iq = theorem.find('q') return theorem[:iq] + '-' + theorem[iq:] + '-' # make a basic axiom a1 = make_axiom(1) print a1 # use the rule to find another theorem t2 = next_theorem(a1) print t2
# Chapter 2: The pq-system import re import random axiom_pattern = re.compile('(-*)p-q(-*)-') theorem_pattern = re.compile('(-*)p(-*)q(-*)') def make_axiom(n): assert type(n) == int assert n > 0 x = '-' * n return x + 'p' + '-q' + x + '-' def next_theorem(theorem): assert 'p' in theorem assert 'q' in theorem iq = theorem.find('q') return theorem[:iq] + '-' + theorem[iq:] + '-' def is_axiom(s): match = axiom_pattern.match(s) if match: return match.groups()[0] == match.groups()[1] return False def is_theorem(s): match = theorem_pattern.match(s) if match: g = match.groups() return len(g[0]) + len(g[1]) == len(g[2]) return False if __name__ == '__main__': # make a basic axiom a1 = make_axiom(1) print a1, is_axiom(a1), is_theorem(a1) # use the rule to find another theorem t2 = next_theorem(a1) print t2, is_axiom(t2), is_theorem(t2) # Test a random axiom ra = make_axiom(random.randint(0, 100)) print is_axiom(ra), is_theorem(ra) rt = next_theorem(ra) print is_axiom(rt), is_theorem(rt) # Test an an arbitrary string print is_axiom('-pq-')
Add axiom and theorem checks
Add axiom and theorem checks
Python
mit
ericfs/geb
# Chapter 2: The pq-system def make_axiom(n): assert type(n) == int assert n > 0 x = '-' * n return x + 'p' + '-q' + x + '-' def next_theorem(theorem): assert 'p' in theorem assert 'q' in theorem iq = theorem.find('q') return theorem[:iq] + '-' + theorem[iq:] + '-' # make a basic axiom a1 = make_axiom(1) print a1 # use the rule to find another theorem t2 = next_theorem(a1) print t2 Add axiom and theorem checks
# Chapter 2: The pq-system import re import random axiom_pattern = re.compile('(-*)p-q(-*)-') theorem_pattern = re.compile('(-*)p(-*)q(-*)') def make_axiom(n): assert type(n) == int assert n > 0 x = '-' * n return x + 'p' + '-q' + x + '-' def next_theorem(theorem): assert 'p' in theorem assert 'q' in theorem iq = theorem.find('q') return theorem[:iq] + '-' + theorem[iq:] + '-' def is_axiom(s): match = axiom_pattern.match(s) if match: return match.groups()[0] == match.groups()[1] return False def is_theorem(s): match = theorem_pattern.match(s) if match: g = match.groups() return len(g[0]) + len(g[1]) == len(g[2]) return False if __name__ == '__main__': # make a basic axiom a1 = make_axiom(1) print a1, is_axiom(a1), is_theorem(a1) # use the rule to find another theorem t2 = next_theorem(a1) print t2, is_axiom(t2), is_theorem(t2) # Test a random axiom ra = make_axiom(random.randint(0, 100)) print is_axiom(ra), is_theorem(ra) rt = next_theorem(ra) print is_axiom(rt), is_theorem(rt) # Test an an arbitrary string print is_axiom('-pq-')
<commit_before># Chapter 2: The pq-system def make_axiom(n): assert type(n) == int assert n > 0 x = '-' * n return x + 'p' + '-q' + x + '-' def next_theorem(theorem): assert 'p' in theorem assert 'q' in theorem iq = theorem.find('q') return theorem[:iq] + '-' + theorem[iq:] + '-' # make a basic axiom a1 = make_axiom(1) print a1 # use the rule to find another theorem t2 = next_theorem(a1) print t2 <commit_msg>Add axiom and theorem checks<commit_after>
# Chapter 2: The pq-system import re import random axiom_pattern = re.compile('(-*)p-q(-*)-') theorem_pattern = re.compile('(-*)p(-*)q(-*)') def make_axiom(n): assert type(n) == int assert n > 0 x = '-' * n return x + 'p' + '-q' + x + '-' def next_theorem(theorem): assert 'p' in theorem assert 'q' in theorem iq = theorem.find('q') return theorem[:iq] + '-' + theorem[iq:] + '-' def is_axiom(s): match = axiom_pattern.match(s) if match: return match.groups()[0] == match.groups()[1] return False def is_theorem(s): match = theorem_pattern.match(s) if match: g = match.groups() return len(g[0]) + len(g[1]) == len(g[2]) return False if __name__ == '__main__': # make a basic axiom a1 = make_axiom(1) print a1, is_axiom(a1), is_theorem(a1) # use the rule to find another theorem t2 = next_theorem(a1) print t2, is_axiom(t2), is_theorem(t2) # Test a random axiom ra = make_axiom(random.randint(0, 100)) print is_axiom(ra), is_theorem(ra) rt = next_theorem(ra) print is_axiom(rt), is_theorem(rt) # Test an an arbitrary string print is_axiom('-pq-')
# Chapter 2: The pq-system def make_axiom(n): assert type(n) == int assert n > 0 x = '-' * n return x + 'p' + '-q' + x + '-' def next_theorem(theorem): assert 'p' in theorem assert 'q' in theorem iq = theorem.find('q') return theorem[:iq] + '-' + theorem[iq:] + '-' # make a basic axiom a1 = make_axiom(1) print a1 # use the rule to find another theorem t2 = next_theorem(a1) print t2 Add axiom and theorem checks# Chapter 2: The pq-system import re import random axiom_pattern = re.compile('(-*)p-q(-*)-') theorem_pattern = re.compile('(-*)p(-*)q(-*)') def make_axiom(n): assert type(n) == int assert n > 0 x = '-' * n return x + 'p' + '-q' + x + '-' def next_theorem(theorem): assert 'p' in theorem assert 'q' in theorem iq = theorem.find('q') return theorem[:iq] + '-' + theorem[iq:] + '-' def is_axiom(s): match = axiom_pattern.match(s) if match: return match.groups()[0] == match.groups()[1] return False def is_theorem(s): match = theorem_pattern.match(s) if match: g = match.groups() return len(g[0]) + len(g[1]) == len(g[2]) return False if __name__ == '__main__': # make a basic axiom a1 = make_axiom(1) print a1, is_axiom(a1), is_theorem(a1) # use the rule to find another theorem t2 = next_theorem(a1) print t2, is_axiom(t2), is_theorem(t2) # Test a random axiom ra = make_axiom(random.randint(0, 100)) print is_axiom(ra), is_theorem(ra) rt = next_theorem(ra) print is_axiom(rt), is_theorem(rt) # Test an an arbitrary string print is_axiom('-pq-')
<commit_before># Chapter 2: The pq-system def make_axiom(n): assert type(n) == int assert n > 0 x = '-' * n return x + 'p' + '-q' + x + '-' def next_theorem(theorem): assert 'p' in theorem assert 'q' in theorem iq = theorem.find('q') return theorem[:iq] + '-' + theorem[iq:] + '-' # make a basic axiom a1 = make_axiom(1) print a1 # use the rule to find another theorem t2 = next_theorem(a1) print t2 <commit_msg>Add axiom and theorem checks<commit_after># Chapter 2: The pq-system import re import random axiom_pattern = re.compile('(-*)p-q(-*)-') theorem_pattern = re.compile('(-*)p(-*)q(-*)') def make_axiom(n): assert type(n) == int assert n > 0 x = '-' * n return x + 'p' + '-q' + x + '-' def next_theorem(theorem): assert 'p' in theorem assert 'q' in theorem iq = theorem.find('q') return theorem[:iq] + '-' + theorem[iq:] + '-' def is_axiom(s): match = axiom_pattern.match(s) if match: return match.groups()[0] == match.groups()[1] return False def is_theorem(s): match = theorem_pattern.match(s) if match: g = match.groups() return len(g[0]) + len(g[1]) == len(g[2]) return False if __name__ == '__main__': # make a basic axiom a1 = make_axiom(1) print a1, is_axiom(a1), is_theorem(a1) # use the rule to find another theorem t2 = next_theorem(a1) print t2, is_axiom(t2), is_theorem(t2) # Test a random axiom ra = make_axiom(random.randint(0, 100)) print is_axiom(ra), is_theorem(ra) rt = next_theorem(ra) print is_axiom(rt), is_theorem(rt) # Test an an arbitrary string print is_axiom('-pq-')
0d8bcbde2ca0e6596bb110649babda58bc66b273
CI/syntaxCheck.py
CI/syntaxCheck.py
import sys from CITests import CITests # Libs in Application Examples appExamples = { #"KundurSMIB":"/ApplicationExamples/KundurSMIB/package.mo", #"TwoAreas":"/ApplicationExamples/TwoAreas/package.mo", #"SevenBus":"/ApplicationExamples/SevenBus/package.mo", #"IEEE9":"/ApplicationExamples/IEEE9/package.mo", #"IEEE14":"/ApplicationExamples/IEEE14/package.mo", #"AKD":"/ApplicationExamples/AKD/package.mo", #"N44":"/ApplicationExamples/N44/package.mo", #"OpenCPSD5d3B":"/ApplicationExamples/OpenCPSD5d3B/package.mo", #"RaPIdExperiments":"/ApplicationExamples/RaPIdExperiments/package.mo" } # Instance of CITests ci = CITests("/OpenIPSL") # Run Check on OpenIPSL passLib = ci.runSyntaxCheck("OpenIPSL","/OpenIPSL/OpenIPSL/package.mo") if not passLib: # Error in OpenIPSL sys.exit(1) else: # Run Check on App Examples passAppEx = 1 for package in appExamples.keys(): passAppEx = passAppEx * ci.runSyntaxCheck(package,appExamples[package]) # The tests are failing if the number of failed check > 0 if passAppEx: # Everything is fine sys.exit(0) else: # Exit with error sys.exit(1)
import sys from CITests import CITests # Libs in Application Examples appExamples = { #"KundurSMIB":"/ApplicationExamples/KundurSMIB/package.mo", #"TwoAreas":"/ApplicationExamples/TwoAreas/package.mo", #"SevenBus":"/ApplicationExamples/SevenBus/package.mo", #"IEEE9":"/ApplicationExamples/IEEE9/package.mo", #"IEEE14":"/ApplicationExamples/IEEE14/package.mo", #"AKD":"/ApplicationExamples/AKD/package.mo", #"N44":"/ApplicationExamples/N44/package.mo", #"OpenCPSD5d3B":"/ApplicationExamples/OpenCPSD5d3B/package.mo", #"RaPIdExperiments":"/ApplicationExamples/RaPIdExperiments/package.mo" } # Instance of CITests ci = CITests("/OpenIPSL") # Run Check on OpenIPSL passLib = ci.runSyntaxCheck("OpenIPSL","/OpenIPSL/package.mo") if not passLib: # Error in OpenIPSL sys.exit(1) else: # Run Check on App Examples passAppEx = 1 for package in appExamples.keys(): passAppEx = passAppEx * ci.runSyntaxCheck(package,appExamples[package]) # The tests are failing if the number of failed check > 0 if passAppEx: # Everything is fine sys.exit(0) else: # Exit with error sys.exit(1)
Revert "Fix the location path of OpenIPSL"
Revert "Fix the location path of OpenIPSL" This reverts commit 5b3af4a6c1c77c651867ee2b5f5cef5100944ba6.
Python
bsd-3-clause
tinrabuzin/OpenIPSL,SmarTS-Lab/OpenIPSL,OpenIPSL/OpenIPSL,SmarTS-Lab/OpenIPSL
import sys from CITests import CITests # Libs in Application Examples appExamples = { #"KundurSMIB":"/ApplicationExamples/KundurSMIB/package.mo", #"TwoAreas":"/ApplicationExamples/TwoAreas/package.mo", #"SevenBus":"/ApplicationExamples/SevenBus/package.mo", #"IEEE9":"/ApplicationExamples/IEEE9/package.mo", #"IEEE14":"/ApplicationExamples/IEEE14/package.mo", #"AKD":"/ApplicationExamples/AKD/package.mo", #"N44":"/ApplicationExamples/N44/package.mo", #"OpenCPSD5d3B":"/ApplicationExamples/OpenCPSD5d3B/package.mo", #"RaPIdExperiments":"/ApplicationExamples/RaPIdExperiments/package.mo" } # Instance of CITests ci = CITests("/OpenIPSL") # Run Check on OpenIPSL passLib = ci.runSyntaxCheck("OpenIPSL","/OpenIPSL/OpenIPSL/package.mo") if not passLib: # Error in OpenIPSL sys.exit(1) else: # Run Check on App Examples passAppEx = 1 for package in appExamples.keys(): passAppEx = passAppEx * ci.runSyntaxCheck(package,appExamples[package]) # The tests are failing if the number of failed check > 0 if passAppEx: # Everything is fine sys.exit(0) else: # Exit with error sys.exit(1) Revert "Fix the location path of OpenIPSL" This reverts commit 5b3af4a6c1c77c651867ee2b5f5cef5100944ba6.
import sys from CITests import CITests # Libs in Application Examples appExamples = { #"KundurSMIB":"/ApplicationExamples/KundurSMIB/package.mo", #"TwoAreas":"/ApplicationExamples/TwoAreas/package.mo", #"SevenBus":"/ApplicationExamples/SevenBus/package.mo", #"IEEE9":"/ApplicationExamples/IEEE9/package.mo", #"IEEE14":"/ApplicationExamples/IEEE14/package.mo", #"AKD":"/ApplicationExamples/AKD/package.mo", #"N44":"/ApplicationExamples/N44/package.mo", #"OpenCPSD5d3B":"/ApplicationExamples/OpenCPSD5d3B/package.mo", #"RaPIdExperiments":"/ApplicationExamples/RaPIdExperiments/package.mo" } # Instance of CITests ci = CITests("/OpenIPSL") # Run Check on OpenIPSL passLib = ci.runSyntaxCheck("OpenIPSL","/OpenIPSL/package.mo") if not passLib: # Error in OpenIPSL sys.exit(1) else: # Run Check on App Examples passAppEx = 1 for package in appExamples.keys(): passAppEx = passAppEx * ci.runSyntaxCheck(package,appExamples[package]) # The tests are failing if the number of failed check > 0 if passAppEx: # Everything is fine sys.exit(0) else: # Exit with error sys.exit(1)
<commit_before>import sys from CITests import CITests # Libs in Application Examples appExamples = { #"KundurSMIB":"/ApplicationExamples/KundurSMIB/package.mo", #"TwoAreas":"/ApplicationExamples/TwoAreas/package.mo", #"SevenBus":"/ApplicationExamples/SevenBus/package.mo", #"IEEE9":"/ApplicationExamples/IEEE9/package.mo", #"IEEE14":"/ApplicationExamples/IEEE14/package.mo", #"AKD":"/ApplicationExamples/AKD/package.mo", #"N44":"/ApplicationExamples/N44/package.mo", #"OpenCPSD5d3B":"/ApplicationExamples/OpenCPSD5d3B/package.mo", #"RaPIdExperiments":"/ApplicationExamples/RaPIdExperiments/package.mo" } # Instance of CITests ci = CITests("/OpenIPSL") # Run Check on OpenIPSL passLib = ci.runSyntaxCheck("OpenIPSL","/OpenIPSL/OpenIPSL/package.mo") if not passLib: # Error in OpenIPSL sys.exit(1) else: # Run Check on App Examples passAppEx = 1 for package in appExamples.keys(): passAppEx = passAppEx * ci.runSyntaxCheck(package,appExamples[package]) # The tests are failing if the number of failed check > 0 if passAppEx: # Everything is fine sys.exit(0) else: # Exit with error sys.exit(1) <commit_msg>Revert "Fix the location path of OpenIPSL" This reverts commit 5b3af4a6c1c77c651867ee2b5f5cef5100944ba6.<commit_after>
import sys from CITests import CITests # Libs in Application Examples appExamples = { #"KundurSMIB":"/ApplicationExamples/KundurSMIB/package.mo", #"TwoAreas":"/ApplicationExamples/TwoAreas/package.mo", #"SevenBus":"/ApplicationExamples/SevenBus/package.mo", #"IEEE9":"/ApplicationExamples/IEEE9/package.mo", #"IEEE14":"/ApplicationExamples/IEEE14/package.mo", #"AKD":"/ApplicationExamples/AKD/package.mo", #"N44":"/ApplicationExamples/N44/package.mo", #"OpenCPSD5d3B":"/ApplicationExamples/OpenCPSD5d3B/package.mo", #"RaPIdExperiments":"/ApplicationExamples/RaPIdExperiments/package.mo" } # Instance of CITests ci = CITests("/OpenIPSL") # Run Check on OpenIPSL passLib = ci.runSyntaxCheck("OpenIPSL","/OpenIPSL/package.mo") if not passLib: # Error in OpenIPSL sys.exit(1) else: # Run Check on App Examples passAppEx = 1 for package in appExamples.keys(): passAppEx = passAppEx * ci.runSyntaxCheck(package,appExamples[package]) # The tests are failing if the number of failed check > 0 if passAppEx: # Everything is fine sys.exit(0) else: # Exit with error sys.exit(1)
import sys from CITests import CITests # Libs in Application Examples appExamples = { #"KundurSMIB":"/ApplicationExamples/KundurSMIB/package.mo", #"TwoAreas":"/ApplicationExamples/TwoAreas/package.mo", #"SevenBus":"/ApplicationExamples/SevenBus/package.mo", #"IEEE9":"/ApplicationExamples/IEEE9/package.mo", #"IEEE14":"/ApplicationExamples/IEEE14/package.mo", #"AKD":"/ApplicationExamples/AKD/package.mo", #"N44":"/ApplicationExamples/N44/package.mo", #"OpenCPSD5d3B":"/ApplicationExamples/OpenCPSD5d3B/package.mo", #"RaPIdExperiments":"/ApplicationExamples/RaPIdExperiments/package.mo" } # Instance of CITests ci = CITests("/OpenIPSL") # Run Check on OpenIPSL passLib = ci.runSyntaxCheck("OpenIPSL","/OpenIPSL/OpenIPSL/package.mo") if not passLib: # Error in OpenIPSL sys.exit(1) else: # Run Check on App Examples passAppEx = 1 for package in appExamples.keys(): passAppEx = passAppEx * ci.runSyntaxCheck(package,appExamples[package]) # The tests are failing if the number of failed check > 0 if passAppEx: # Everything is fine sys.exit(0) else: # Exit with error sys.exit(1) Revert "Fix the location path of OpenIPSL" This reverts commit 5b3af4a6c1c77c651867ee2b5f5cef5100944ba6.import sys from CITests import CITests # Libs in Application Examples appExamples = { #"KundurSMIB":"/ApplicationExamples/KundurSMIB/package.mo", #"TwoAreas":"/ApplicationExamples/TwoAreas/package.mo", #"SevenBus":"/ApplicationExamples/SevenBus/package.mo", #"IEEE9":"/ApplicationExamples/IEEE9/package.mo", #"IEEE14":"/ApplicationExamples/IEEE14/package.mo", #"AKD":"/ApplicationExamples/AKD/package.mo", #"N44":"/ApplicationExamples/N44/package.mo", #"OpenCPSD5d3B":"/ApplicationExamples/OpenCPSD5d3B/package.mo", #"RaPIdExperiments":"/ApplicationExamples/RaPIdExperiments/package.mo" } # Instance of CITests ci = CITests("/OpenIPSL") # Run Check on OpenIPSL passLib = ci.runSyntaxCheck("OpenIPSL","/OpenIPSL/package.mo") if not passLib: # Error in OpenIPSL sys.exit(1) else: # Run Check on App Examples passAppEx = 1 for package in appExamples.keys(): passAppEx = passAppEx * ci.runSyntaxCheck(package,appExamples[package]) # The tests are failing if the number of failed check > 0 if passAppEx: # Everything is fine sys.exit(0) else: # Exit with error sys.exit(1)
<commit_before>import sys from CITests import CITests # Libs in Application Examples appExamples = { #"KundurSMIB":"/ApplicationExamples/KundurSMIB/package.mo", #"TwoAreas":"/ApplicationExamples/TwoAreas/package.mo", #"SevenBus":"/ApplicationExamples/SevenBus/package.mo", #"IEEE9":"/ApplicationExamples/IEEE9/package.mo", #"IEEE14":"/ApplicationExamples/IEEE14/package.mo", #"AKD":"/ApplicationExamples/AKD/package.mo", #"N44":"/ApplicationExamples/N44/package.mo", #"OpenCPSD5d3B":"/ApplicationExamples/OpenCPSD5d3B/package.mo", #"RaPIdExperiments":"/ApplicationExamples/RaPIdExperiments/package.mo" } # Instance of CITests ci = CITests("/OpenIPSL") # Run Check on OpenIPSL passLib = ci.runSyntaxCheck("OpenIPSL","/OpenIPSL/OpenIPSL/package.mo") if not passLib: # Error in OpenIPSL sys.exit(1) else: # Run Check on App Examples passAppEx = 1 for package in appExamples.keys(): passAppEx = passAppEx * ci.runSyntaxCheck(package,appExamples[package]) # The tests are failing if the number of failed check > 0 if passAppEx: # Everything is fine sys.exit(0) else: # Exit with error sys.exit(1) <commit_msg>Revert "Fix the location path of OpenIPSL" This reverts commit 5b3af4a6c1c77c651867ee2b5f5cef5100944ba6.<commit_after>import sys from CITests import CITests # Libs in Application Examples appExamples = { #"KundurSMIB":"/ApplicationExamples/KundurSMIB/package.mo", #"TwoAreas":"/ApplicationExamples/TwoAreas/package.mo", #"SevenBus":"/ApplicationExamples/SevenBus/package.mo", #"IEEE9":"/ApplicationExamples/IEEE9/package.mo", #"IEEE14":"/ApplicationExamples/IEEE14/package.mo", #"AKD":"/ApplicationExamples/AKD/package.mo", #"N44":"/ApplicationExamples/N44/package.mo", #"OpenCPSD5d3B":"/ApplicationExamples/OpenCPSD5d3B/package.mo", #"RaPIdExperiments":"/ApplicationExamples/RaPIdExperiments/package.mo" } # Instance of CITests ci = CITests("/OpenIPSL") # Run Check on OpenIPSL passLib = ci.runSyntaxCheck("OpenIPSL","/OpenIPSL/package.mo") if not passLib: # Error in OpenIPSL sys.exit(1) else: # Run Check on App Examples passAppEx = 1 for package in appExamples.keys(): passAppEx = passAppEx * ci.runSyntaxCheck(package,appExamples[package]) # The tests are failing if the number of failed check > 0 if passAppEx: # Everything is fine sys.exit(0) else: # Exit with error sys.exit(1)
48d234fffe052454356e09d7b3c69c938f1f7f87
all/hyperhelpcore/__init__.py
all/hyperhelpcore/__init__.py
### --------------------------------------------------------------------------- from .startup import initialize __version_tuple = (1, 0, 0) __version__ = ".".join([str(num) for num in __version_tuple]) ### --------------------------------------------------------------------------- __all__ = [ "common", "core", "data", "help", "initialize", "version" "view", ] ### --------------------------------------------------------------------------- def version(): """ Get the version of the installed dependency package as a tuple. This is used during the bootstrap check to see if the version of the dependency has changed. """ return __version_tuple ### ---------------------------------------------------------------------------
### --------------------------------------------------------------------------- from .startup import initialize __version_tuple = (0, 0, 1) __version__ = ".".join([str(num) for num in __version_tuple]) ### --------------------------------------------------------------------------- __all__ = [ "common", "core", "data", "help", "initialize", "version" "view", ] ### --------------------------------------------------------------------------- def version(): """ Get the version of the installed dependency package as a tuple. This is used during the bootstrap check to see if the version of the dependency has changed. """ return __version_tuple ### ---------------------------------------------------------------------------
Set the initial dependency version information
Set the initial dependency version information This sets our initial version tuple to 0.0.1, which is as far as I know the smallest possible version, or at least the smallest semver that makes any sense. From this point forward, changes to anything that we want anyone to see need to have the version tuple bumped and a new release created.
Python
mit
OdatNurd/hyperhelp
### --------------------------------------------------------------------------- from .startup import initialize __version_tuple = (1, 0, 0) __version__ = ".".join([str(num) for num in __version_tuple]) ### --------------------------------------------------------------------------- __all__ = [ "common", "core", "data", "help", "initialize", "version" "view", ] ### --------------------------------------------------------------------------- def version(): """ Get the version of the installed dependency package as a tuple. This is used during the bootstrap check to see if the version of the dependency has changed. """ return __version_tuple ### ---------------------------------------------------------------------------Set the initial dependency version information This sets our initial version tuple to 0.0.1, which is as far as I know the smallest possible version, or at least the smallest semver that makes any sense. From this point forward, changes to anything that we want anyone to see need to have the version tuple bumped and a new release created.
### --------------------------------------------------------------------------- from .startup import initialize __version_tuple = (0, 0, 1) __version__ = ".".join([str(num) for num in __version_tuple]) ### --------------------------------------------------------------------------- __all__ = [ "common", "core", "data", "help", "initialize", "version" "view", ] ### --------------------------------------------------------------------------- def version(): """ Get the version of the installed dependency package as a tuple. This is used during the bootstrap check to see if the version of the dependency has changed. """ return __version_tuple ### ---------------------------------------------------------------------------
<commit_before>### --------------------------------------------------------------------------- from .startup import initialize __version_tuple = (1, 0, 0) __version__ = ".".join([str(num) for num in __version_tuple]) ### --------------------------------------------------------------------------- __all__ = [ "common", "core", "data", "help", "initialize", "version" "view", ] ### --------------------------------------------------------------------------- def version(): """ Get the version of the installed dependency package as a tuple. This is used during the bootstrap check to see if the version of the dependency has changed. """ return __version_tuple ### ---------------------------------------------------------------------------<commit_msg>Set the initial dependency version information This sets our initial version tuple to 0.0.1, which is as far as I know the smallest possible version, or at least the smallest semver that makes any sense. From this point forward, changes to anything that we want anyone to see need to have the version tuple bumped and a new release created.<commit_after>
### --------------------------------------------------------------------------- from .startup import initialize __version_tuple = (0, 0, 1) __version__ = ".".join([str(num) for num in __version_tuple]) ### --------------------------------------------------------------------------- __all__ = [ "common", "core", "data", "help", "initialize", "version" "view", ] ### --------------------------------------------------------------------------- def version(): """ Get the version of the installed dependency package as a tuple. This is used during the bootstrap check to see if the version of the dependency has changed. """ return __version_tuple ### ---------------------------------------------------------------------------
### --------------------------------------------------------------------------- from .startup import initialize __version_tuple = (1, 0, 0) __version__ = ".".join([str(num) for num in __version_tuple]) ### --------------------------------------------------------------------------- __all__ = [ "common", "core", "data", "help", "initialize", "version" "view", ] ### --------------------------------------------------------------------------- def version(): """ Get the version of the installed dependency package as a tuple. This is used during the bootstrap check to see if the version of the dependency has changed. """ return __version_tuple ### ---------------------------------------------------------------------------Set the initial dependency version information This sets our initial version tuple to 0.0.1, which is as far as I know the smallest possible version, or at least the smallest semver that makes any sense. From this point forward, changes to anything that we want anyone to see need to have the version tuple bumped and a new release created.### --------------------------------------------------------------------------- from .startup import initialize __version_tuple = (0, 0, 1) __version__ = ".".join([str(num) for num in __version_tuple]) ### --------------------------------------------------------------------------- __all__ = [ "common", "core", "data", "help", "initialize", "version" "view", ] ### --------------------------------------------------------------------------- def version(): """ Get the version of the installed dependency package as a tuple. This is used during the bootstrap check to see if the version of the dependency has changed. """ return __version_tuple ### ---------------------------------------------------------------------------
<commit_before>### --------------------------------------------------------------------------- from .startup import initialize __version_tuple = (1, 0, 0) __version__ = ".".join([str(num) for num in __version_tuple]) ### --------------------------------------------------------------------------- __all__ = [ "common", "core", "data", "help", "initialize", "version" "view", ] ### --------------------------------------------------------------------------- def version(): """ Get the version of the installed dependency package as a tuple. This is used during the bootstrap check to see if the version of the dependency has changed. """ return __version_tuple ### ---------------------------------------------------------------------------<commit_msg>Set the initial dependency version information This sets our initial version tuple to 0.0.1, which is as far as I know the smallest possible version, or at least the smallest semver that makes any sense. From this point forward, changes to anything that we want anyone to see need to have the version tuple bumped and a new release created.<commit_after>### --------------------------------------------------------------------------- from .startup import initialize __version_tuple = (0, 0, 1) __version__ = ".".join([str(num) for num in __version_tuple]) ### --------------------------------------------------------------------------- __all__ = [ "common", "core", "data", "help", "initialize", "version" "view", ] ### --------------------------------------------------------------------------- def version(): """ Get the version of the installed dependency package as a tuple. This is used during the bootstrap check to see if the version of the dependency has changed. """ return __version_tuple ### ---------------------------------------------------------------------------
b0e21495e0421a3656ed4507fe7b43b65601f16f
bluebottle/settings/travis.py
bluebottle/settings/travis.py
# SECRET_KEY and DATABASES needs to be defined before the base settings is imported. SECRET_KEY = 'hbqnTEq+m7Tk61bvRV/TLANr3i0WZ6hgBXDh3aYpSU8m+E1iCtlU3Q==' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', }, } from .base import * # # Put the travis-ci environment specific overrides below. #
# SECRET_KEY and DATABASES needs to be defined before the base settings is imported. SECRET_KEY = 'hbqnTEq+m7Tk61bvRV/TLANr3i0WZ6hgBXDh3aYpSU8m+E1iCtlU3Q==' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', }, } from .base import * # # Put the travis-ci environment specific overrides below. # SELENIUM_TESTS = True
Enable Selenium tests for Travis.
Enable Selenium tests for Travis.
Python
bsd-3-clause
onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site
# SECRET_KEY and DATABASES needs to be defined before the base settings is imported. SECRET_KEY = 'hbqnTEq+m7Tk61bvRV/TLANr3i0WZ6hgBXDh3aYpSU8m+E1iCtlU3Q==' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', }, } from .base import * # # Put the travis-ci environment specific overrides below. # Enable Selenium tests for Travis.
# SECRET_KEY and DATABASES needs to be defined before the base settings is imported. SECRET_KEY = 'hbqnTEq+m7Tk61bvRV/TLANr3i0WZ6hgBXDh3aYpSU8m+E1iCtlU3Q==' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', }, } from .base import * # # Put the travis-ci environment specific overrides below. # SELENIUM_TESTS = True
<commit_before> # SECRET_KEY and DATABASES needs to be defined before the base settings is imported. SECRET_KEY = 'hbqnTEq+m7Tk61bvRV/TLANr3i0WZ6hgBXDh3aYpSU8m+E1iCtlU3Q==' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', }, } from .base import * # # Put the travis-ci environment specific overrides below. # <commit_msg>Enable Selenium tests for Travis.<commit_after>
# SECRET_KEY and DATABASES needs to be defined before the base settings is imported. SECRET_KEY = 'hbqnTEq+m7Tk61bvRV/TLANr3i0WZ6hgBXDh3aYpSU8m+E1iCtlU3Q==' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', }, } from .base import * # # Put the travis-ci environment specific overrides below. # SELENIUM_TESTS = True
# SECRET_KEY and DATABASES needs to be defined before the base settings is imported. SECRET_KEY = 'hbqnTEq+m7Tk61bvRV/TLANr3i0WZ6hgBXDh3aYpSU8m+E1iCtlU3Q==' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', }, } from .base import * # # Put the travis-ci environment specific overrides below. # Enable Selenium tests for Travis. # SECRET_KEY and DATABASES needs to be defined before the base settings is imported. SECRET_KEY = 'hbqnTEq+m7Tk61bvRV/TLANr3i0WZ6hgBXDh3aYpSU8m+E1iCtlU3Q==' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', }, } from .base import * # # Put the travis-ci environment specific overrides below. # SELENIUM_TESTS = True
<commit_before> # SECRET_KEY and DATABASES needs to be defined before the base settings is imported. SECRET_KEY = 'hbqnTEq+m7Tk61bvRV/TLANr3i0WZ6hgBXDh3aYpSU8m+E1iCtlU3Q==' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', }, } from .base import * # # Put the travis-ci environment specific overrides below. # <commit_msg>Enable Selenium tests for Travis.<commit_after> # SECRET_KEY and DATABASES needs to be defined before the base settings is imported. SECRET_KEY = 'hbqnTEq+m7Tk61bvRV/TLANr3i0WZ6hgBXDh3aYpSU8m+E1iCtlU3Q==' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', }, } from .base import * # # Put the travis-ci environment specific overrides below. # SELENIUM_TESTS = True
f5b085878b6bc9b461811a9083fdcaab5546497b
tests/test_server.py
tests/test_server.py
import os import threading import numpy as np import pytest from skimage import io from gala import serve, evaluate as ev D = os.path.dirname(os.path.abspath(__file__)) os.chdir(os.path.join(D, 'example-data/snemi-mini')) @pytest.fixture def data(): frag, gt, pr = map(io.imread, sorted(os.listdir('.'))) return frag, gt, pr def test_server(data): frag, gt, pr = data host, port = 'tcp://localhost', 5590 solver = serve.Solver(frag, pr, port=port, host='tcp://*') thread = threading.Thread(target=solver.listen, name='solver') thread.start() _, dst = serve.proofread(frag, gt, host=host, port=port, stop_when_finished=True, random_state=0) result = np.array(dst)[frag] # test: resulting segmentation should be improvement over fragments alone assert (ev.vi(result, gt, ignore_x=[], ignore_y=[]) < ev.vi(frag, gt, ignore_x=[], ignore_y=[]))
Add test for solver/proofread pair
Add test for solver/proofread pair
Python
bsd-3-clause
jni/gala,janelia-flyem/gala
Add test for solver/proofread pair
import os import threading import numpy as np import pytest from skimage import io from gala import serve, evaluate as ev D = os.path.dirname(os.path.abspath(__file__)) os.chdir(os.path.join(D, 'example-data/snemi-mini')) @pytest.fixture def data(): frag, gt, pr = map(io.imread, sorted(os.listdir('.'))) return frag, gt, pr def test_server(data): frag, gt, pr = data host, port = 'tcp://localhost', 5590 solver = serve.Solver(frag, pr, port=port, host='tcp://*') thread = threading.Thread(target=solver.listen, name='solver') thread.start() _, dst = serve.proofread(frag, gt, host=host, port=port, stop_when_finished=True, random_state=0) result = np.array(dst)[frag] # test: resulting segmentation should be improvement over fragments alone assert (ev.vi(result, gt, ignore_x=[], ignore_y=[]) < ev.vi(frag, gt, ignore_x=[], ignore_y=[]))
<commit_before><commit_msg>Add test for solver/proofread pair<commit_after>
import os import threading import numpy as np import pytest from skimage import io from gala import serve, evaluate as ev D = os.path.dirname(os.path.abspath(__file__)) os.chdir(os.path.join(D, 'example-data/snemi-mini')) @pytest.fixture def data(): frag, gt, pr = map(io.imread, sorted(os.listdir('.'))) return frag, gt, pr def test_server(data): frag, gt, pr = data host, port = 'tcp://localhost', 5590 solver = serve.Solver(frag, pr, port=port, host='tcp://*') thread = threading.Thread(target=solver.listen, name='solver') thread.start() _, dst = serve.proofread(frag, gt, host=host, port=port, stop_when_finished=True, random_state=0) result = np.array(dst)[frag] # test: resulting segmentation should be improvement over fragments alone assert (ev.vi(result, gt, ignore_x=[], ignore_y=[]) < ev.vi(frag, gt, ignore_x=[], ignore_y=[]))
Add test for solver/proofread pairimport os import threading import numpy as np import pytest from skimage import io from gala import serve, evaluate as ev D = os.path.dirname(os.path.abspath(__file__)) os.chdir(os.path.join(D, 'example-data/snemi-mini')) @pytest.fixture def data(): frag, gt, pr = map(io.imread, sorted(os.listdir('.'))) return frag, gt, pr def test_server(data): frag, gt, pr = data host, port = 'tcp://localhost', 5590 solver = serve.Solver(frag, pr, port=port, host='tcp://*') thread = threading.Thread(target=solver.listen, name='solver') thread.start() _, dst = serve.proofread(frag, gt, host=host, port=port, stop_when_finished=True, random_state=0) result = np.array(dst)[frag] # test: resulting segmentation should be improvement over fragments alone assert (ev.vi(result, gt, ignore_x=[], ignore_y=[]) < ev.vi(frag, gt, ignore_x=[], ignore_y=[]))
<commit_before><commit_msg>Add test for solver/proofread pair<commit_after>import os import threading import numpy as np import pytest from skimage import io from gala import serve, evaluate as ev D = os.path.dirname(os.path.abspath(__file__)) os.chdir(os.path.join(D, 'example-data/snemi-mini')) @pytest.fixture def data(): frag, gt, pr = map(io.imread, sorted(os.listdir('.'))) return frag, gt, pr def test_server(data): frag, gt, pr = data host, port = 'tcp://localhost', 5590 solver = serve.Solver(frag, pr, port=port, host='tcp://*') thread = threading.Thread(target=solver.listen, name='solver') thread.start() _, dst = serve.proofread(frag, gt, host=host, port=port, stop_when_finished=True, random_state=0) result = np.array(dst)[frag] # test: resulting segmentation should be improvement over fragments alone assert (ev.vi(result, gt, ignore_x=[], ignore_y=[]) < ev.vi(frag, gt, ignore_x=[], ignore_y=[]))
1f25d3a8d73fe776a2182ee68c027105fd15ab04
tiamat/decorators.py
tiamat/decorators.py
import json from functools import wraps from django.http import HttpResponse from django.shortcuts import render_to_response from django.template import RequestContext def as_json(func): def decorator(request, *ar, **kw): output = func(request, *ar, **kw) if not isinstance(output, dict): return output return HttpResponse(json.dumps(output), 'application/json') return decorator def as_jsonp(functionCallKey='callback'): def decorator(func): def wrapper(request, *ar, **kw): output = func(request, *ar, **kw) if not isinstance(output, dict): return output return HttpResponse( "%s(%s)" % (request.GET.get(functionCallKey), json.dumps(output)), 'application/json' ) return wrapper return decorator def as_html(template_path): """ Decorator with the same functionality as render_to_response has, but uses decorator syntax. """ def decorator(func): @wraps(func) def wrapper(request, *args, **kwargs): output = func(request, *args, **kwargs) if not isinstance(output, dict): return output return render_to_response( template_path, output, context_instance=RequestContext(request) ) return wrapper return decorator
import json from functools import wraps from django.http import HttpResponse from django.shortcuts import render_to_response from django.template import RequestContext def as_json(func): def decorator(request, *ar, **kw): output = func(request, *ar, **kw) return HttpResponse(json.dumps(output), 'application/json') return decorator def as_jsonp(functionCallKey='callback'): def decorator(func): def wrapper(request, *ar, **kw): output = func(request, *ar, **kw) return HttpResponse( "%s(%s)" % (request.GET.get(functionCallKey, functionCallKey), json.dumps(output)), 'application/json' ) return wrapper return decorator def as_html(template_path): """ Decorator with the same functionality as render_to_response has, but uses decorator syntax. """ def decorator(func): @wraps(func) def wrapper(request, *args, **kwargs): output = func(request, *args, **kwargs) if not isinstance(output, dict): return output return render_to_response( template_path, output, context_instance=RequestContext(request) ) return wrapper return decorator
Fix problem in as_json and as_jsonp
Fix problem in as_json and as_jsonp
Python
bsd-2-clause
rvause/django-tiamat
import json from functools import wraps from django.http import HttpResponse from django.shortcuts import render_to_response from django.template import RequestContext def as_json(func): def decorator(request, *ar, **kw): output = func(request, *ar, **kw) if not isinstance(output, dict): return output return HttpResponse(json.dumps(output), 'application/json') return decorator def as_jsonp(functionCallKey='callback'): def decorator(func): def wrapper(request, *ar, **kw): output = func(request, *ar, **kw) if not isinstance(output, dict): return output return HttpResponse( "%s(%s)" % (request.GET.get(functionCallKey), json.dumps(output)), 'application/json' ) return wrapper return decorator def as_html(template_path): """ Decorator with the same functionality as render_to_response has, but uses decorator syntax. """ def decorator(func): @wraps(func) def wrapper(request, *args, **kwargs): output = func(request, *args, **kwargs) if not isinstance(output, dict): return output return render_to_response( template_path, output, context_instance=RequestContext(request) ) return wrapper return decorator Fix problem in as_json and as_jsonp
import json from functools import wraps from django.http import HttpResponse from django.shortcuts import render_to_response from django.template import RequestContext def as_json(func): def decorator(request, *ar, **kw): output = func(request, *ar, **kw) return HttpResponse(json.dumps(output), 'application/json') return decorator def as_jsonp(functionCallKey='callback'): def decorator(func): def wrapper(request, *ar, **kw): output = func(request, *ar, **kw) return HttpResponse( "%s(%s)" % (request.GET.get(functionCallKey, functionCallKey), json.dumps(output)), 'application/json' ) return wrapper return decorator def as_html(template_path): """ Decorator with the same functionality as render_to_response has, but uses decorator syntax. """ def decorator(func): @wraps(func) def wrapper(request, *args, **kwargs): output = func(request, *args, **kwargs) if not isinstance(output, dict): return output return render_to_response( template_path, output, context_instance=RequestContext(request) ) return wrapper return decorator
<commit_before>import json from functools import wraps from django.http import HttpResponse from django.shortcuts import render_to_response from django.template import RequestContext def as_json(func): def decorator(request, *ar, **kw): output = func(request, *ar, **kw) if not isinstance(output, dict): return output return HttpResponse(json.dumps(output), 'application/json') return decorator def as_jsonp(functionCallKey='callback'): def decorator(func): def wrapper(request, *ar, **kw): output = func(request, *ar, **kw) if not isinstance(output, dict): return output return HttpResponse( "%s(%s)" % (request.GET.get(functionCallKey), json.dumps(output)), 'application/json' ) return wrapper return decorator def as_html(template_path): """ Decorator with the same functionality as render_to_response has, but uses decorator syntax. """ def decorator(func): @wraps(func) def wrapper(request, *args, **kwargs): output = func(request, *args, **kwargs) if not isinstance(output, dict): return output return render_to_response( template_path, output, context_instance=RequestContext(request) ) return wrapper return decorator <commit_msg>Fix problem in as_json and as_jsonp<commit_after>
import json from functools import wraps from django.http import HttpResponse from django.shortcuts import render_to_response from django.template import RequestContext def as_json(func): def decorator(request, *ar, **kw): output = func(request, *ar, **kw) return HttpResponse(json.dumps(output), 'application/json') return decorator def as_jsonp(functionCallKey='callback'): def decorator(func): def wrapper(request, *ar, **kw): output = func(request, *ar, **kw) return HttpResponse( "%s(%s)" % (request.GET.get(functionCallKey, functionCallKey), json.dumps(output)), 'application/json' ) return wrapper return decorator def as_html(template_path): """ Decorator with the same functionality as render_to_response has, but uses decorator syntax. """ def decorator(func): @wraps(func) def wrapper(request, *args, **kwargs): output = func(request, *args, **kwargs) if not isinstance(output, dict): return output return render_to_response( template_path, output, context_instance=RequestContext(request) ) return wrapper return decorator
import json from functools import wraps from django.http import HttpResponse from django.shortcuts import render_to_response from django.template import RequestContext def as_json(func): def decorator(request, *ar, **kw): output = func(request, *ar, **kw) if not isinstance(output, dict): return output return HttpResponse(json.dumps(output), 'application/json') return decorator def as_jsonp(functionCallKey='callback'): def decorator(func): def wrapper(request, *ar, **kw): output = func(request, *ar, **kw) if not isinstance(output, dict): return output return HttpResponse( "%s(%s)" % (request.GET.get(functionCallKey), json.dumps(output)), 'application/json' ) return wrapper return decorator def as_html(template_path): """ Decorator with the same functionality as render_to_response has, but uses decorator syntax. """ def decorator(func): @wraps(func) def wrapper(request, *args, **kwargs): output = func(request, *args, **kwargs) if not isinstance(output, dict): return output return render_to_response( template_path, output, context_instance=RequestContext(request) ) return wrapper return decorator Fix problem in as_json and as_jsonpimport json from functools import wraps from django.http import HttpResponse from django.shortcuts import render_to_response from django.template import RequestContext def as_json(func): def decorator(request, *ar, **kw): output = func(request, *ar, **kw) return HttpResponse(json.dumps(output), 'application/json') return decorator def as_jsonp(functionCallKey='callback'): def decorator(func): def wrapper(request, *ar, **kw): output = func(request, *ar, **kw) return HttpResponse( "%s(%s)" % (request.GET.get(functionCallKey, functionCallKey), json.dumps(output)), 'application/json' ) return wrapper return decorator def as_html(template_path): """ Decorator with the same functionality as render_to_response has, but uses decorator syntax. """ def decorator(func): @wraps(func) def wrapper(request, *args, **kwargs): output = func(request, *args, **kwargs) if not isinstance(output, dict): return output return render_to_response( template_path, output, context_instance=RequestContext(request) ) return wrapper return decorator
<commit_before>import json from functools import wraps from django.http import HttpResponse from django.shortcuts import render_to_response from django.template import RequestContext def as_json(func): def decorator(request, *ar, **kw): output = func(request, *ar, **kw) if not isinstance(output, dict): return output return HttpResponse(json.dumps(output), 'application/json') return decorator def as_jsonp(functionCallKey='callback'): def decorator(func): def wrapper(request, *ar, **kw): output = func(request, *ar, **kw) if not isinstance(output, dict): return output return HttpResponse( "%s(%s)" % (request.GET.get(functionCallKey), json.dumps(output)), 'application/json' ) return wrapper return decorator def as_html(template_path): """ Decorator with the same functionality as render_to_response has, but uses decorator syntax. """ def decorator(func): @wraps(func) def wrapper(request, *args, **kwargs): output = func(request, *args, **kwargs) if not isinstance(output, dict): return output return render_to_response( template_path, output, context_instance=RequestContext(request) ) return wrapper return decorator <commit_msg>Fix problem in as_json and as_jsonp<commit_after>import json from functools import wraps from django.http import HttpResponse from django.shortcuts import render_to_response from django.template import RequestContext def as_json(func): def decorator(request, *ar, **kw): output = func(request, *ar, **kw) return HttpResponse(json.dumps(output), 'application/json') return decorator def as_jsonp(functionCallKey='callback'): def decorator(func): def wrapper(request, *ar, **kw): output = func(request, *ar, **kw) return HttpResponse( "%s(%s)" % (request.GET.get(functionCallKey, functionCallKey), json.dumps(output)), 'application/json' ) return wrapper return decorator def as_html(template_path): """ Decorator with the same functionality as render_to_response has, but uses decorator syntax. """ def decorator(func): @wraps(func) def wrapper(request, *args, **kwargs): output = func(request, *args, **kwargs) if not isinstance(output, dict): return output return render_to_response( template_path, output, context_instance=RequestContext(request) ) return wrapper return decorator
6fd5e51a797f3d85954f6a4c97eacc008b0e4d48
tohu/v5/namespace.py
tohu/v5/namespace.py
from bidict import bidict, ValueDuplicationError def is_anonymous(name): return name.startswith("ANONYMOUS_ANONYMOUS_ANONYMOUS_") class TohuNamespaceError(Exception): """ Custom exception. """ class TohuNamespace: def __init__(self): self.generators = bidict() def __len__(self): return len(self.generators) def __getitem__(self, key): return self.generators[key] def add_generator(self, g, name=None): if name is None: name = f"ANONYMOUS_ANONYMOUS_ANONYMOUS_{g.tohu_id}" if name in self.generators and self.generators[name] is not g: raise TohuNamespaceError("A different generator with the same name already exists.") try: self.generators[name] = g except ValueDuplicationError: existing_name = self.generators.inv[g] if is_anonymous(existing_name) and not is_anonymous(name): self.generators.inv[g] = name def add_generator_with_dependencies(self, g, name=None): self.add_generator(g, name=name) for c in g._input_generators: self.add_generator(c)
from mako.template import Template import textwrap from bidict import bidict, ValueDuplicationError def is_anonymous(name): return name.startswith("ANONYMOUS_ANONYMOUS_ANONYMOUS_") class TohuNamespaceError(Exception): """ Custom exception. """ class TohuNamespace: def __init__(self): self.generators = bidict() def __repr__(self): s = Template(textwrap.dedent("""\ <TohuNameSpace: %for name, g in items: ${name}: ${g} %endfor > """)).render(items=self.generators.items()) return s def __len__(self): return len(self.generators) def __getitem__(self, key): return self.generators[key] def add_generator(self, g, name=None): if name is None: name = f"ANONYMOUS_ANONYMOUS_ANONYMOUS_{g.tohu_id}" if name in self.generators and self.generators[name] is not g: raise TohuNamespaceError("A different generator with the same name already exists.") try: self.generators[name] = g except ValueDuplicationError: existing_name = self.generators.inv[g] if is_anonymous(existing_name) and not is_anonymous(name): self.generators.inv[g] = name def add_generator_with_dependencies(self, g, name=None): self.add_generator(g, name=name) for c in g._input_generators: self.add_generator(c)
Add repr method for TohuNamespace
Add repr method for TohuNamespace
Python
mit
maxalbert/tohu
from bidict import bidict, ValueDuplicationError def is_anonymous(name): return name.startswith("ANONYMOUS_ANONYMOUS_ANONYMOUS_") class TohuNamespaceError(Exception): """ Custom exception. """ class TohuNamespace: def __init__(self): self.generators = bidict() def __len__(self): return len(self.generators) def __getitem__(self, key): return self.generators[key] def add_generator(self, g, name=None): if name is None: name = f"ANONYMOUS_ANONYMOUS_ANONYMOUS_{g.tohu_id}" if name in self.generators and self.generators[name] is not g: raise TohuNamespaceError("A different generator with the same name already exists.") try: self.generators[name] = g except ValueDuplicationError: existing_name = self.generators.inv[g] if is_anonymous(existing_name) and not is_anonymous(name): self.generators.inv[g] = name def add_generator_with_dependencies(self, g, name=None): self.add_generator(g, name=name) for c in g._input_generators: self.add_generator(c)Add repr method for TohuNamespace
from mako.template import Template import textwrap from bidict import bidict, ValueDuplicationError def is_anonymous(name): return name.startswith("ANONYMOUS_ANONYMOUS_ANONYMOUS_") class TohuNamespaceError(Exception): """ Custom exception. """ class TohuNamespace: def __init__(self): self.generators = bidict() def __repr__(self): s = Template(textwrap.dedent("""\ <TohuNameSpace: %for name, g in items: ${name}: ${g} %endfor > """)).render(items=self.generators.items()) return s def __len__(self): return len(self.generators) def __getitem__(self, key): return self.generators[key] def add_generator(self, g, name=None): if name is None: name = f"ANONYMOUS_ANONYMOUS_ANONYMOUS_{g.tohu_id}" if name in self.generators and self.generators[name] is not g: raise TohuNamespaceError("A different generator with the same name already exists.") try: self.generators[name] = g except ValueDuplicationError: existing_name = self.generators.inv[g] if is_anonymous(existing_name) and not is_anonymous(name): self.generators.inv[g] = name def add_generator_with_dependencies(self, g, name=None): self.add_generator(g, name=name) for c in g._input_generators: self.add_generator(c)
<commit_before>from bidict import bidict, ValueDuplicationError def is_anonymous(name): return name.startswith("ANONYMOUS_ANONYMOUS_ANONYMOUS_") class TohuNamespaceError(Exception): """ Custom exception. """ class TohuNamespace: def __init__(self): self.generators = bidict() def __len__(self): return len(self.generators) def __getitem__(self, key): return self.generators[key] def add_generator(self, g, name=None): if name is None: name = f"ANONYMOUS_ANONYMOUS_ANONYMOUS_{g.tohu_id}" if name in self.generators and self.generators[name] is not g: raise TohuNamespaceError("A different generator with the same name already exists.") try: self.generators[name] = g except ValueDuplicationError: existing_name = self.generators.inv[g] if is_anonymous(existing_name) and not is_anonymous(name): self.generators.inv[g] = name def add_generator_with_dependencies(self, g, name=None): self.add_generator(g, name=name) for c in g._input_generators: self.add_generator(c)<commit_msg>Add repr method for TohuNamespace<commit_after>
from mako.template import Template import textwrap from bidict import bidict, ValueDuplicationError def is_anonymous(name): return name.startswith("ANONYMOUS_ANONYMOUS_ANONYMOUS_") class TohuNamespaceError(Exception): """ Custom exception. """ class TohuNamespace: def __init__(self): self.generators = bidict() def __repr__(self): s = Template(textwrap.dedent("""\ <TohuNameSpace: %for name, g in items: ${name}: ${g} %endfor > """)).render(items=self.generators.items()) return s def __len__(self): return len(self.generators) def __getitem__(self, key): return self.generators[key] def add_generator(self, g, name=None): if name is None: name = f"ANONYMOUS_ANONYMOUS_ANONYMOUS_{g.tohu_id}" if name in self.generators and self.generators[name] is not g: raise TohuNamespaceError("A different generator with the same name already exists.") try: self.generators[name] = g except ValueDuplicationError: existing_name = self.generators.inv[g] if is_anonymous(existing_name) and not is_anonymous(name): self.generators.inv[g] = name def add_generator_with_dependencies(self, g, name=None): self.add_generator(g, name=name) for c in g._input_generators: self.add_generator(c)
from bidict import bidict, ValueDuplicationError def is_anonymous(name): return name.startswith("ANONYMOUS_ANONYMOUS_ANONYMOUS_") class TohuNamespaceError(Exception): """ Custom exception. """ class TohuNamespace: def __init__(self): self.generators = bidict() def __len__(self): return len(self.generators) def __getitem__(self, key): return self.generators[key] def add_generator(self, g, name=None): if name is None: name = f"ANONYMOUS_ANONYMOUS_ANONYMOUS_{g.tohu_id}" if name in self.generators and self.generators[name] is not g: raise TohuNamespaceError("A different generator with the same name already exists.") try: self.generators[name] = g except ValueDuplicationError: existing_name = self.generators.inv[g] if is_anonymous(existing_name) and not is_anonymous(name): self.generators.inv[g] = name def add_generator_with_dependencies(self, g, name=None): self.add_generator(g, name=name) for c in g._input_generators: self.add_generator(c)Add repr method for TohuNamespacefrom mako.template import Template import textwrap from bidict import bidict, ValueDuplicationError def is_anonymous(name): return name.startswith("ANONYMOUS_ANONYMOUS_ANONYMOUS_") class TohuNamespaceError(Exception): """ Custom exception. """ class TohuNamespace: def __init__(self): self.generators = bidict() def __repr__(self): s = Template(textwrap.dedent("""\ <TohuNameSpace: %for name, g in items: ${name}: ${g} %endfor > """)).render(items=self.generators.items()) return s def __len__(self): return len(self.generators) def __getitem__(self, key): return self.generators[key] def add_generator(self, g, name=None): if name is None: name = f"ANONYMOUS_ANONYMOUS_ANONYMOUS_{g.tohu_id}" if name in self.generators and self.generators[name] is not g: raise TohuNamespaceError("A different generator with the same name already exists.") try: self.generators[name] = g except ValueDuplicationError: existing_name = self.generators.inv[g] if is_anonymous(existing_name) and not is_anonymous(name): self.generators.inv[g] = name def add_generator_with_dependencies(self, g, name=None): self.add_generator(g, name=name) for c in g._input_generators: self.add_generator(c)
<commit_before>from bidict import bidict, ValueDuplicationError def is_anonymous(name): return name.startswith("ANONYMOUS_ANONYMOUS_ANONYMOUS_") class TohuNamespaceError(Exception): """ Custom exception. """ class TohuNamespace: def __init__(self): self.generators = bidict() def __len__(self): return len(self.generators) def __getitem__(self, key): return self.generators[key] def add_generator(self, g, name=None): if name is None: name = f"ANONYMOUS_ANONYMOUS_ANONYMOUS_{g.tohu_id}" if name in self.generators and self.generators[name] is not g: raise TohuNamespaceError("A different generator with the same name already exists.") try: self.generators[name] = g except ValueDuplicationError: existing_name = self.generators.inv[g] if is_anonymous(existing_name) and not is_anonymous(name): self.generators.inv[g] = name def add_generator_with_dependencies(self, g, name=None): self.add_generator(g, name=name) for c in g._input_generators: self.add_generator(c)<commit_msg>Add repr method for TohuNamespace<commit_after>from mako.template import Template import textwrap from bidict import bidict, ValueDuplicationError def is_anonymous(name): return name.startswith("ANONYMOUS_ANONYMOUS_ANONYMOUS_") class TohuNamespaceError(Exception): """ Custom exception. """ class TohuNamespace: def __init__(self): self.generators = bidict() def __repr__(self): s = Template(textwrap.dedent("""\ <TohuNameSpace: %for name, g in items: ${name}: ${g} %endfor > """)).render(items=self.generators.items()) return s def __len__(self): return len(self.generators) def __getitem__(self, key): return self.generators[key] def add_generator(self, g, name=None): if name is None: name = f"ANONYMOUS_ANONYMOUS_ANONYMOUS_{g.tohu_id}" if name in self.generators and self.generators[name] is not g: raise TohuNamespaceError("A different generator with the same name already exists.") try: self.generators[name] = g except ValueDuplicationError: existing_name = self.generators.inv[g] if is_anonymous(existing_name) and not is_anonymous(name): self.generators.inv[g] = name def add_generator_with_dependencies(self, g, name=None): self.add_generator(g, name=name) for c in g._input_generators: self.add_generator(c)
e9862c50c1d71800602ca78bf9bdd8aad2def0a2
run.py
run.py
import os tag = 'celebA_dcgan' dataset = 'celebA' command = 'python main.py --dataset %s --is_train True ' \ '--sample_dir samples_%s --checkpoint_dir checkpoint_%s --tensorboard_run %s '%(dataset, tag, tag, tag) os.system(command)
import os tag = 'celebA_dcgan' dataset = 'celebA' command = 'python main.py --dataset %s --is_train True --is_crop ' \ '--sample_dir samples_%s --checkpoint_dir checkpoint_%s --tensorboard_run %s '%(dataset, tag, tag, tag) os.system(command)
Add is_crop for celebA example
Add is_crop for celebA example
Python
mit
MustafaMustafa/WassersteinGAN-TensorFlow
import os tag = 'celebA_dcgan' dataset = 'celebA' command = 'python main.py --dataset %s --is_train True ' \ '--sample_dir samples_%s --checkpoint_dir checkpoint_%s --tensorboard_run %s '%(dataset, tag, tag, tag) os.system(command) Add is_crop for celebA example
import os tag = 'celebA_dcgan' dataset = 'celebA' command = 'python main.py --dataset %s --is_train True --is_crop ' \ '--sample_dir samples_%s --checkpoint_dir checkpoint_%s --tensorboard_run %s '%(dataset, tag, tag, tag) os.system(command)
<commit_before>import os tag = 'celebA_dcgan' dataset = 'celebA' command = 'python main.py --dataset %s --is_train True ' \ '--sample_dir samples_%s --checkpoint_dir checkpoint_%s --tensorboard_run %s '%(dataset, tag, tag, tag) os.system(command) <commit_msg>Add is_crop for celebA example<commit_after>
import os tag = 'celebA_dcgan' dataset = 'celebA' command = 'python main.py --dataset %s --is_train True --is_crop ' \ '--sample_dir samples_%s --checkpoint_dir checkpoint_%s --tensorboard_run %s '%(dataset, tag, tag, tag) os.system(command)
import os tag = 'celebA_dcgan' dataset = 'celebA' command = 'python main.py --dataset %s --is_train True ' \ '--sample_dir samples_%s --checkpoint_dir checkpoint_%s --tensorboard_run %s '%(dataset, tag, tag, tag) os.system(command) Add is_crop for celebA exampleimport os tag = 'celebA_dcgan' dataset = 'celebA' command = 'python main.py --dataset %s --is_train True --is_crop ' \ '--sample_dir samples_%s --checkpoint_dir checkpoint_%s --tensorboard_run %s '%(dataset, tag, tag, tag) os.system(command)
<commit_before>import os tag = 'celebA_dcgan' dataset = 'celebA' command = 'python main.py --dataset %s --is_train True ' \ '--sample_dir samples_%s --checkpoint_dir checkpoint_%s --tensorboard_run %s '%(dataset, tag, tag, tag) os.system(command) <commit_msg>Add is_crop for celebA example<commit_after>import os tag = 'celebA_dcgan' dataset = 'celebA' command = 'python main.py --dataset %s --is_train True --is_crop ' \ '--sample_dir samples_%s --checkpoint_dir checkpoint_%s --tensorboard_run %s '%(dataset, tag, tag, tag) os.system(command)
96db3441a0cc2e3010606b2017c900a16c6a8f2f
astropy/nddata/tests/test_nddatabase.py
astropy/nddata/tests/test_nddatabase.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst # Tests of NDDataBase from __future__ import (absolute_import, division, print_function, unicode_literals) from ..nddatabase import NDDataBase from ...tests.helper import pytest class MinimalSubclass(NDDataBase): def __init__(self): super(MinimalSubclass, self).__init__() @property def data(self): return None @property def mask(self): super(MinimalSubclass, self).mask @property def unit(self): super(MinimalSubclass, self).unit @property def wcs(self): super(MinimalSubclass, self).wcs @property def meta(self): super(MinimalSubclass, self).meta class MinimalUncertainty(object): """ Define the minimum attributes acceptable as an uncertainty object. """ def __init__(self, value): self._uncertainty = value @property def uncertainty_type(self): return "totally and completely fake" def test_nddatabase_subclass(): a = MinimalSubclass() assert a.meta is None assert a.data is None assert a.mask is None assert a.unit is None assert a.wcs is None good_uncertainty = MinimalUncertainty(5) a.uncertainty = good_uncertainty assert a.uncertainty is good_uncertainty bad_uncertainty = 5 with pytest.raises(TypeError): a.uncertainty = bad_uncertainty
# Licensed under a 3-clause BSD style license - see LICENSE.rst # Tests of NDDataBase from __future__ import (absolute_import, division, print_function, unicode_literals) from ..nddatabase import NDDataBase from ...tests.helper import pytest class MinimalSubclass(NDDataBase): def __init__(self): super(MinimalSubclass, self).__init__() @property def data(self): return None @property def mask(self): return super(MinimalSubclass, self).mask @property def unit(self): return super(MinimalSubclass, self).unit @property def wcs(self): return super(MinimalSubclass, self).wcs @property def meta(self): return super(MinimalSubclass, self).meta class MinimalUncertainty(object): """ Define the minimum attributes acceptable as an uncertainty object. """ def __init__(self, value): self._uncertainty = value @property def uncertainty_type(self): return "totally and completely fake" def test_nddatabase_subclass(): a = MinimalSubclass() assert a.meta is None assert a.data is None assert a.mask is None assert a.unit is None assert a.wcs is None good_uncertainty = MinimalUncertainty(5) a.uncertainty = good_uncertainty assert a.uncertainty is good_uncertainty bad_uncertainty = 5 with pytest.raises(TypeError): a.uncertainty = bad_uncertainty
Add returns to test class properties
Add returns to test class properties
Python
bsd-3-clause
tbabej/astropy,lpsinger/astropy,dhomeier/astropy,larrybradley/astropy,pllim/astropy,dhomeier/astropy,AustereCuriosity/astropy,stargaser/astropy,mhvk/astropy,astropy/astropy,AustereCuriosity/astropy,pllim/astropy,lpsinger/astropy,MSeifert04/astropy,tbabej/astropy,stargaser/astropy,bsipocz/astropy,joergdietrich/astropy,joergdietrich/astropy,astropy/astropy,aleksandr-bakanov/astropy,bsipocz/astropy,joergdietrich/astropy,bsipocz/astropy,astropy/astropy,mhvk/astropy,mhvk/astropy,kelle/astropy,saimn/astropy,dhomeier/astropy,aleksandr-bakanov/astropy,AustereCuriosity/astropy,DougBurke/astropy,DougBurke/astropy,MSeifert04/astropy,kelle/astropy,astropy/astropy,dhomeier/astropy,larrybradley/astropy,pllim/astropy,funbaker/astropy,AustereCuriosity/astropy,DougBurke/astropy,StuartLittlefair/astropy,StuartLittlefair/astropy,stargaser/astropy,aleksandr-bakanov/astropy,tbabej/astropy,bsipocz/astropy,mhvk/astropy,kelle/astropy,MSeifert04/astropy,stargaser/astropy,aleksandr-bakanov/astropy,saimn/astropy,tbabej/astropy,saimn/astropy,saimn/astropy,MSeifert04/astropy,joergdietrich/astropy,StuartLittlefair/astropy,lpsinger/astropy,larrybradley/astropy,larrybradley/astropy,StuartLittlefair/astropy,mhvk/astropy,funbaker/astropy,tbabej/astropy,larrybradley/astropy,pllim/astropy,pllim/astropy,funbaker/astropy,astropy/astropy,dhomeier/astropy,AustereCuriosity/astropy,kelle/astropy,funbaker/astropy,StuartLittlefair/astropy,kelle/astropy,saimn/astropy,lpsinger/astropy,DougBurke/astropy,lpsinger/astropy,joergdietrich/astropy
# Licensed under a 3-clause BSD style license - see LICENSE.rst # Tests of NDDataBase from __future__ import (absolute_import, division, print_function, unicode_literals) from ..nddatabase import NDDataBase from ...tests.helper import pytest class MinimalSubclass(NDDataBase): def __init__(self): super(MinimalSubclass, self).__init__() @property def data(self): return None @property def mask(self): super(MinimalSubclass, self).mask @property def unit(self): super(MinimalSubclass, self).unit @property def wcs(self): super(MinimalSubclass, self).wcs @property def meta(self): super(MinimalSubclass, self).meta class MinimalUncertainty(object): """ Define the minimum attributes acceptable as an uncertainty object. """ def __init__(self, value): self._uncertainty = value @property def uncertainty_type(self): return "totally and completely fake" def test_nddatabase_subclass(): a = MinimalSubclass() assert a.meta is None assert a.data is None assert a.mask is None assert a.unit is None assert a.wcs is None good_uncertainty = MinimalUncertainty(5) a.uncertainty = good_uncertainty assert a.uncertainty is good_uncertainty bad_uncertainty = 5 with pytest.raises(TypeError): a.uncertainty = bad_uncertainty Add returns to test class properties
# Licensed under a 3-clause BSD style license - see LICENSE.rst # Tests of NDDataBase from __future__ import (absolute_import, division, print_function, unicode_literals) from ..nddatabase import NDDataBase from ...tests.helper import pytest class MinimalSubclass(NDDataBase): def __init__(self): super(MinimalSubclass, self).__init__() @property def data(self): return None @property def mask(self): return super(MinimalSubclass, self).mask @property def unit(self): return super(MinimalSubclass, self).unit @property def wcs(self): return super(MinimalSubclass, self).wcs @property def meta(self): return super(MinimalSubclass, self).meta class MinimalUncertainty(object): """ Define the minimum attributes acceptable as an uncertainty object. """ def __init__(self, value): self._uncertainty = value @property def uncertainty_type(self): return "totally and completely fake" def test_nddatabase_subclass(): a = MinimalSubclass() assert a.meta is None assert a.data is None assert a.mask is None assert a.unit is None assert a.wcs is None good_uncertainty = MinimalUncertainty(5) a.uncertainty = good_uncertainty assert a.uncertainty is good_uncertainty bad_uncertainty = 5 with pytest.raises(TypeError): a.uncertainty = bad_uncertainty
<commit_before># Licensed under a 3-clause BSD style license - see LICENSE.rst # Tests of NDDataBase from __future__ import (absolute_import, division, print_function, unicode_literals) from ..nddatabase import NDDataBase from ...tests.helper import pytest class MinimalSubclass(NDDataBase): def __init__(self): super(MinimalSubclass, self).__init__() @property def data(self): return None @property def mask(self): super(MinimalSubclass, self).mask @property def unit(self): super(MinimalSubclass, self).unit @property def wcs(self): super(MinimalSubclass, self).wcs @property def meta(self): super(MinimalSubclass, self).meta class MinimalUncertainty(object): """ Define the minimum attributes acceptable as an uncertainty object. """ def __init__(self, value): self._uncertainty = value @property def uncertainty_type(self): return "totally and completely fake" def test_nddatabase_subclass(): a = MinimalSubclass() assert a.meta is None assert a.data is None assert a.mask is None assert a.unit is None assert a.wcs is None good_uncertainty = MinimalUncertainty(5) a.uncertainty = good_uncertainty assert a.uncertainty is good_uncertainty bad_uncertainty = 5 with pytest.raises(TypeError): a.uncertainty = bad_uncertainty <commit_msg>Add returns to test class properties<commit_after>
# Licensed under a 3-clause BSD style license - see LICENSE.rst # Tests of NDDataBase from __future__ import (absolute_import, division, print_function, unicode_literals) from ..nddatabase import NDDataBase from ...tests.helper import pytest class MinimalSubclass(NDDataBase): def __init__(self): super(MinimalSubclass, self).__init__() @property def data(self): return None @property def mask(self): return super(MinimalSubclass, self).mask @property def unit(self): return super(MinimalSubclass, self).unit @property def wcs(self): return super(MinimalSubclass, self).wcs @property def meta(self): return super(MinimalSubclass, self).meta class MinimalUncertainty(object): """ Define the minimum attributes acceptable as an uncertainty object. """ def __init__(self, value): self._uncertainty = value @property def uncertainty_type(self): return "totally and completely fake" def test_nddatabase_subclass(): a = MinimalSubclass() assert a.meta is None assert a.data is None assert a.mask is None assert a.unit is None assert a.wcs is None good_uncertainty = MinimalUncertainty(5) a.uncertainty = good_uncertainty assert a.uncertainty is good_uncertainty bad_uncertainty = 5 with pytest.raises(TypeError): a.uncertainty = bad_uncertainty
# Licensed under a 3-clause BSD style license - see LICENSE.rst # Tests of NDDataBase from __future__ import (absolute_import, division, print_function, unicode_literals) from ..nddatabase import NDDataBase from ...tests.helper import pytest class MinimalSubclass(NDDataBase): def __init__(self): super(MinimalSubclass, self).__init__() @property def data(self): return None @property def mask(self): super(MinimalSubclass, self).mask @property def unit(self): super(MinimalSubclass, self).unit @property def wcs(self): super(MinimalSubclass, self).wcs @property def meta(self): super(MinimalSubclass, self).meta class MinimalUncertainty(object): """ Define the minimum attributes acceptable as an uncertainty object. """ def __init__(self, value): self._uncertainty = value @property def uncertainty_type(self): return "totally and completely fake" def test_nddatabase_subclass(): a = MinimalSubclass() assert a.meta is None assert a.data is None assert a.mask is None assert a.unit is None assert a.wcs is None good_uncertainty = MinimalUncertainty(5) a.uncertainty = good_uncertainty assert a.uncertainty is good_uncertainty bad_uncertainty = 5 with pytest.raises(TypeError): a.uncertainty = bad_uncertainty Add returns to test class properties# Licensed under a 3-clause BSD style license - see LICENSE.rst # Tests of NDDataBase from __future__ import (absolute_import, division, print_function, unicode_literals) from ..nddatabase import NDDataBase from ...tests.helper import pytest class MinimalSubclass(NDDataBase): def __init__(self): super(MinimalSubclass, self).__init__() @property def data(self): return None @property def mask(self): return super(MinimalSubclass, self).mask @property def unit(self): return super(MinimalSubclass, self).unit @property def wcs(self): return super(MinimalSubclass, self).wcs @property def meta(self): return super(MinimalSubclass, self).meta class MinimalUncertainty(object): """ Define the minimum attributes acceptable as an uncertainty object. """ def __init__(self, value): self._uncertainty = value @property def uncertainty_type(self): return "totally and completely fake" def test_nddatabase_subclass(): a = MinimalSubclass() assert a.meta is None assert a.data is None assert a.mask is None assert a.unit is None assert a.wcs is None good_uncertainty = MinimalUncertainty(5) a.uncertainty = good_uncertainty assert a.uncertainty is good_uncertainty bad_uncertainty = 5 with pytest.raises(TypeError): a.uncertainty = bad_uncertainty
<commit_before># Licensed under a 3-clause BSD style license - see LICENSE.rst # Tests of NDDataBase from __future__ import (absolute_import, division, print_function, unicode_literals) from ..nddatabase import NDDataBase from ...tests.helper import pytest class MinimalSubclass(NDDataBase): def __init__(self): super(MinimalSubclass, self).__init__() @property def data(self): return None @property def mask(self): super(MinimalSubclass, self).mask @property def unit(self): super(MinimalSubclass, self).unit @property def wcs(self): super(MinimalSubclass, self).wcs @property def meta(self): super(MinimalSubclass, self).meta class MinimalUncertainty(object): """ Define the minimum attributes acceptable as an uncertainty object. """ def __init__(self, value): self._uncertainty = value @property def uncertainty_type(self): return "totally and completely fake" def test_nddatabase_subclass(): a = MinimalSubclass() assert a.meta is None assert a.data is None assert a.mask is None assert a.unit is None assert a.wcs is None good_uncertainty = MinimalUncertainty(5) a.uncertainty = good_uncertainty assert a.uncertainty is good_uncertainty bad_uncertainty = 5 with pytest.raises(TypeError): a.uncertainty = bad_uncertainty <commit_msg>Add returns to test class properties<commit_after># Licensed under a 3-clause BSD style license - see LICENSE.rst # Tests of NDDataBase from __future__ import (absolute_import, division, print_function, unicode_literals) from ..nddatabase import NDDataBase from ...tests.helper import pytest class MinimalSubclass(NDDataBase): def __init__(self): super(MinimalSubclass, self).__init__() @property def data(self): return None @property def mask(self): return super(MinimalSubclass, self).mask @property def unit(self): return super(MinimalSubclass, self).unit @property def wcs(self): return super(MinimalSubclass, self).wcs @property def meta(self): return super(MinimalSubclass, self).meta class MinimalUncertainty(object): """ Define the minimum attributes acceptable as an uncertainty object. """ def __init__(self, value): self._uncertainty = value @property def uncertainty_type(self): return "totally and completely fake" def test_nddatabase_subclass(): a = MinimalSubclass() assert a.meta is None assert a.data is None assert a.mask is None assert a.unit is None assert a.wcs is None good_uncertainty = MinimalUncertainty(5) a.uncertainty = good_uncertainty assert a.uncertainty is good_uncertainty bad_uncertainty = 5 with pytest.raises(TypeError): a.uncertainty = bad_uncertainty
1e63d21d5751da12ad4104b6d2a0c170cc3898ff
problem_3/solution.py
problem_3/solution.py
def largest_prime_factor(n, h): for i in xrange(2, n+1): d, m = divmod(n, i) if m == 0: largest_prime_factor(d, i) break if n == 1: print h largest_prime_factor(600851475143, 0)
import time def largest_prime_factor(n, h): for i in xrange(2, n+1): d, m = divmod(n, i) if m == 0: largest_prime_factor(d, i) break if n == 1: return h t1 = time.time() largest_prime_factor(600851475143, 0) t2 = time.time() print "=> largest_prime_factor(600851475143, 0): %fs" % (t2 - t1)
Add timing for problem 3's python implementation
Add timing for problem 3's python implementation
Python
mit
mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler
def largest_prime_factor(n, h): for i in xrange(2, n+1): d, m = divmod(n, i) if m == 0: largest_prime_factor(d, i) break if n == 1: print h largest_prime_factor(600851475143, 0) Add timing for problem 3's python implementation
import time def largest_prime_factor(n, h): for i in xrange(2, n+1): d, m = divmod(n, i) if m == 0: largest_prime_factor(d, i) break if n == 1: return h t1 = time.time() largest_prime_factor(600851475143, 0) t2 = time.time() print "=> largest_prime_factor(600851475143, 0): %fs" % (t2 - t1)
<commit_before>def largest_prime_factor(n, h): for i in xrange(2, n+1): d, m = divmod(n, i) if m == 0: largest_prime_factor(d, i) break if n == 1: print h largest_prime_factor(600851475143, 0) <commit_msg>Add timing for problem 3's python implementation<commit_after>
import time def largest_prime_factor(n, h): for i in xrange(2, n+1): d, m = divmod(n, i) if m == 0: largest_prime_factor(d, i) break if n == 1: return h t1 = time.time() largest_prime_factor(600851475143, 0) t2 = time.time() print "=> largest_prime_factor(600851475143, 0): %fs" % (t2 - t1)
def largest_prime_factor(n, h): for i in xrange(2, n+1): d, m = divmod(n, i) if m == 0: largest_prime_factor(d, i) break if n == 1: print h largest_prime_factor(600851475143, 0) Add timing for problem 3's python implementationimport time def largest_prime_factor(n, h): for i in xrange(2, n+1): d, m = divmod(n, i) if m == 0: largest_prime_factor(d, i) break if n == 1: return h t1 = time.time() largest_prime_factor(600851475143, 0) t2 = time.time() print "=> largest_prime_factor(600851475143, 0): %fs" % (t2 - t1)
<commit_before>def largest_prime_factor(n, h): for i in xrange(2, n+1): d, m = divmod(n, i) if m == 0: largest_prime_factor(d, i) break if n == 1: print h largest_prime_factor(600851475143, 0) <commit_msg>Add timing for problem 3's python implementation<commit_after>import time def largest_prime_factor(n, h): for i in xrange(2, n+1): d, m = divmod(n, i) if m == 0: largest_prime_factor(d, i) break if n == 1: return h t1 = time.time() largest_prime_factor(600851475143, 0) t2 = time.time() print "=> largest_prime_factor(600851475143, 0): %fs" % (t2 - t1)
16a85be6597388092e497e642cdad8650fdfea95
app/tasks/twitter/listener.py
app/tasks/twitter/listener.py
# -*- coding: utf-8 -*- import time import json import sys import pika from tweepy.streaming import StreamListener class Listener(StreamListener): def __init__(self): #setup rabbitMQ Connection connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost')) self.channel = connection.channel() #set max queue size args = {"x-max-length": 2000} self.channel.queue_declare(queue='social_data', arguments=args) def on_data(self, data): try: data = json.loads(data) if data["text"]: self.verify(data) time.sleep(5) return True except BaseException, e: print("failed in ondata, ", str(e)) time.sleep(5) pass def on_error(self, status): print(status) def verify(self, data): print "Incoming tweet from " + data["user"]["screen_name"] tweet = data["text"] # enqueue the tweet self.channel.basic_publish(exchange='', routing_key='social_data', body=data["text"])
# -*- coding: utf-8 -*- import time import json import sys import pika import os from tweepy.streaming import StreamListener class Listener(StreamListener): def __init__(self): #setup rabbitMQ Connection host = os.environ['CLOUDAMQP_URL'] connection = pika.BlockingConnection(pika.ConnectionParameters(host=host)) self.channel = connection.channel() #set max queue size args = {"x-max-length": 2000} self.channel.queue_declare(queue='social_data', arguments=args) def on_data(self, data): try: data = json.loads(data) if data["text"]: self.verify(data) time.sleep(5) return True except BaseException, e: print("failed in ondata, ", str(e)) time.sleep(5) pass def on_error(self, status): print(status) def verify(self, data): print "Incoming tweet from " + data["user"]["screen_name"] tweet = data["text"] # enqueue the tweet self.channel.basic_publish(exchange='', routing_key='social_data', body=data["text"])
Set up environment specific connection to rabbitmq
Set up environment specific connection to rabbitmq
Python
mit
robot-overlord/syriarightnow
# -*- coding: utf-8 -*- import time import json import sys import pika from tweepy.streaming import StreamListener class Listener(StreamListener): def __init__(self): #setup rabbitMQ Connection connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost')) self.channel = connection.channel() #set max queue size args = {"x-max-length": 2000} self.channel.queue_declare(queue='social_data', arguments=args) def on_data(self, data): try: data = json.loads(data) if data["text"]: self.verify(data) time.sleep(5) return True except BaseException, e: print("failed in ondata, ", str(e)) time.sleep(5) pass def on_error(self, status): print(status) def verify(self, data): print "Incoming tweet from " + data["user"]["screen_name"] tweet = data["text"] # enqueue the tweet self.channel.basic_publish(exchange='', routing_key='social_data', body=data["text"]) Set up environment specific connection to rabbitmq
# -*- coding: utf-8 -*- import time import json import sys import pika import os from tweepy.streaming import StreamListener class Listener(StreamListener): def __init__(self): #setup rabbitMQ Connection host = os.environ['CLOUDAMQP_URL'] connection = pika.BlockingConnection(pika.ConnectionParameters(host=host)) self.channel = connection.channel() #set max queue size args = {"x-max-length": 2000} self.channel.queue_declare(queue='social_data', arguments=args) def on_data(self, data): try: data = json.loads(data) if data["text"]: self.verify(data) time.sleep(5) return True except BaseException, e: print("failed in ondata, ", str(e)) time.sleep(5) pass def on_error(self, status): print(status) def verify(self, data): print "Incoming tweet from " + data["user"]["screen_name"] tweet = data["text"] # enqueue the tweet self.channel.basic_publish(exchange='', routing_key='social_data', body=data["text"])
<commit_before># -*- coding: utf-8 -*- import time import json import sys import pika from tweepy.streaming import StreamListener class Listener(StreamListener): def __init__(self): #setup rabbitMQ Connection connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost')) self.channel = connection.channel() #set max queue size args = {"x-max-length": 2000} self.channel.queue_declare(queue='social_data', arguments=args) def on_data(self, data): try: data = json.loads(data) if data["text"]: self.verify(data) time.sleep(5) return True except BaseException, e: print("failed in ondata, ", str(e)) time.sleep(5) pass def on_error(self, status): print(status) def verify(self, data): print "Incoming tweet from " + data["user"]["screen_name"] tweet = data["text"] # enqueue the tweet self.channel.basic_publish(exchange='', routing_key='social_data', body=data["text"]) <commit_msg>Set up environment specific connection to rabbitmq<commit_after>
# -*- coding: utf-8 -*- import time import json import sys import pika import os from tweepy.streaming import StreamListener class Listener(StreamListener): def __init__(self): #setup rabbitMQ Connection host = os.environ['CLOUDAMQP_URL'] connection = pika.BlockingConnection(pika.ConnectionParameters(host=host)) self.channel = connection.channel() #set max queue size args = {"x-max-length": 2000} self.channel.queue_declare(queue='social_data', arguments=args) def on_data(self, data): try: data = json.loads(data) if data["text"]: self.verify(data) time.sleep(5) return True except BaseException, e: print("failed in ondata, ", str(e)) time.sleep(5) pass def on_error(self, status): print(status) def verify(self, data): print "Incoming tweet from " + data["user"]["screen_name"] tweet = data["text"] # enqueue the tweet self.channel.basic_publish(exchange='', routing_key='social_data', body=data["text"])
# -*- coding: utf-8 -*- import time import json import sys import pika from tweepy.streaming import StreamListener class Listener(StreamListener): def __init__(self): #setup rabbitMQ Connection connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost')) self.channel = connection.channel() #set max queue size args = {"x-max-length": 2000} self.channel.queue_declare(queue='social_data', arguments=args) def on_data(self, data): try: data = json.loads(data) if data["text"]: self.verify(data) time.sleep(5) return True except BaseException, e: print("failed in ondata, ", str(e)) time.sleep(5) pass def on_error(self, status): print(status) def verify(self, data): print "Incoming tweet from " + data["user"]["screen_name"] tweet = data["text"] # enqueue the tweet self.channel.basic_publish(exchange='', routing_key='social_data', body=data["text"]) Set up environment specific connection to rabbitmq# -*- coding: utf-8 -*- import time import json import sys import pika import os from tweepy.streaming import StreamListener class Listener(StreamListener): def __init__(self): #setup rabbitMQ Connection host = os.environ['CLOUDAMQP_URL'] connection = pika.BlockingConnection(pika.ConnectionParameters(host=host)) self.channel = connection.channel() #set max queue size args = {"x-max-length": 2000} self.channel.queue_declare(queue='social_data', arguments=args) def on_data(self, data): try: data = json.loads(data) if data["text"]: self.verify(data) time.sleep(5) return True except BaseException, e: print("failed in ondata, ", str(e)) time.sleep(5) pass def on_error(self, status): print(status) def verify(self, data): print "Incoming tweet from " + data["user"]["screen_name"] tweet = data["text"] # enqueue the tweet self.channel.basic_publish(exchange='', routing_key='social_data', body=data["text"])
<commit_before># -*- coding: utf-8 -*- import time import json import sys import pika from tweepy.streaming import StreamListener class Listener(StreamListener): def __init__(self): #setup rabbitMQ Connection connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost')) self.channel = connection.channel() #set max queue size args = {"x-max-length": 2000} self.channel.queue_declare(queue='social_data', arguments=args) def on_data(self, data): try: data = json.loads(data) if data["text"]: self.verify(data) time.sleep(5) return True except BaseException, e: print("failed in ondata, ", str(e)) time.sleep(5) pass def on_error(self, status): print(status) def verify(self, data): print "Incoming tweet from " + data["user"]["screen_name"] tweet = data["text"] # enqueue the tweet self.channel.basic_publish(exchange='', routing_key='social_data', body=data["text"]) <commit_msg>Set up environment specific connection to rabbitmq<commit_after># -*- coding: utf-8 -*- import time import json import sys import pika import os from tweepy.streaming import StreamListener class Listener(StreamListener): def __init__(self): #setup rabbitMQ Connection host = os.environ['CLOUDAMQP_URL'] connection = pika.BlockingConnection(pika.ConnectionParameters(host=host)) self.channel = connection.channel() #set max queue size args = {"x-max-length": 2000} self.channel.queue_declare(queue='social_data', arguments=args) def on_data(self, data): try: data = json.loads(data) if data["text"]: self.verify(data) time.sleep(5) return True except BaseException, e: print("failed in ondata, ", str(e)) time.sleep(5) pass def on_error(self, status): print(status) def verify(self, data): print "Incoming tweet from " + data["user"]["screen_name"] tweet = data["text"] # enqueue the tweet self.channel.basic_publish(exchange='', routing_key='social_data', body=data["text"])
0a136631d78ee518aec96a1a6ec24ed3e7d4c613
taOonja/game/models.py
taOonja/game/models.py
import os from django.db import models def get_image_path(filename): return os.path.join('photos',filename) class Location(models.Model): name = models.CharField(max_length=250) local_name = models.CharField(max_length=250) visited = models.BooleanField(default=False) class Detail(models.Model): coordinates = models.CharField(max_length=250) detail = models.CharField(max_length=500) img = ImageField(upload_to=get_image_path, blank=True, null=True) location = models.OneToOneField(Location, on_delete=models.CASCADE, primary_key=True)
import os from django.db import models #def get_image_path(filename): # return os.path.join('media') class Location(models.Model): name = models.CharField(max_length=250) local_name = models.CharField(max_length=250) visited = models.BooleanField(default=False) def __str__(self): return self.name class Detail(models.Model): coordinates = models.CharField(max_length=250) detail = models.CharField(max_length=500) img = models.ImageField(upload_to = "media/", blank=True, null=True) location = models.OneToOneField(Location, on_delete=models.CASCADE, primary_key=True) def __str__(self): return self.detail
Change model File to Show Better and Correct Image Field
Change model File to Show Better and Correct Image Field
Python
mit
Javid-Izadfar/TaOonja,Javid-Izadfar/TaOonja,Javid-Izadfar/TaOonja
import os from django.db import models def get_image_path(filename): return os.path.join('photos',filename) class Location(models.Model): name = models.CharField(max_length=250) local_name = models.CharField(max_length=250) visited = models.BooleanField(default=False) class Detail(models.Model): coordinates = models.CharField(max_length=250) detail = models.CharField(max_length=500) img = ImageField(upload_to=get_image_path, blank=True, null=True) location = models.OneToOneField(Location, on_delete=models.CASCADE, primary_key=True) Change model File to Show Better and Correct Image Field
import os from django.db import models #def get_image_path(filename): # return os.path.join('media') class Location(models.Model): name = models.CharField(max_length=250) local_name = models.CharField(max_length=250) visited = models.BooleanField(default=False) def __str__(self): return self.name class Detail(models.Model): coordinates = models.CharField(max_length=250) detail = models.CharField(max_length=500) img = models.ImageField(upload_to = "media/", blank=True, null=True) location = models.OneToOneField(Location, on_delete=models.CASCADE, primary_key=True) def __str__(self): return self.detail
<commit_before>import os from django.db import models def get_image_path(filename): return os.path.join('photos',filename) class Location(models.Model): name = models.CharField(max_length=250) local_name = models.CharField(max_length=250) visited = models.BooleanField(default=False) class Detail(models.Model): coordinates = models.CharField(max_length=250) detail = models.CharField(max_length=500) img = ImageField(upload_to=get_image_path, blank=True, null=True) location = models.OneToOneField(Location, on_delete=models.CASCADE, primary_key=True) <commit_msg>Change model File to Show Better and Correct Image Field<commit_after>
import os from django.db import models #def get_image_path(filename): # return os.path.join('media') class Location(models.Model): name = models.CharField(max_length=250) local_name = models.CharField(max_length=250) visited = models.BooleanField(default=False) def __str__(self): return self.name class Detail(models.Model): coordinates = models.CharField(max_length=250) detail = models.CharField(max_length=500) img = models.ImageField(upload_to = "media/", blank=True, null=True) location = models.OneToOneField(Location, on_delete=models.CASCADE, primary_key=True) def __str__(self): return self.detail
import os from django.db import models def get_image_path(filename): return os.path.join('photos',filename) class Location(models.Model): name = models.CharField(max_length=250) local_name = models.CharField(max_length=250) visited = models.BooleanField(default=False) class Detail(models.Model): coordinates = models.CharField(max_length=250) detail = models.CharField(max_length=500) img = ImageField(upload_to=get_image_path, blank=True, null=True) location = models.OneToOneField(Location, on_delete=models.CASCADE, primary_key=True) Change model File to Show Better and Correct Image Fieldimport os from django.db import models #def get_image_path(filename): # return os.path.join('media') class Location(models.Model): name = models.CharField(max_length=250) local_name = models.CharField(max_length=250) visited = models.BooleanField(default=False) def __str__(self): return self.name class Detail(models.Model): coordinates = models.CharField(max_length=250) detail = models.CharField(max_length=500) img = models.ImageField(upload_to = "media/", blank=True, null=True) location = models.OneToOneField(Location, on_delete=models.CASCADE, primary_key=True) def __str__(self): return self.detail
<commit_before>import os from django.db import models def get_image_path(filename): return os.path.join('photos',filename) class Location(models.Model): name = models.CharField(max_length=250) local_name = models.CharField(max_length=250) visited = models.BooleanField(default=False) class Detail(models.Model): coordinates = models.CharField(max_length=250) detail = models.CharField(max_length=500) img = ImageField(upload_to=get_image_path, blank=True, null=True) location = models.OneToOneField(Location, on_delete=models.CASCADE, primary_key=True) <commit_msg>Change model File to Show Better and Correct Image Field<commit_after>import os from django.db import models #def get_image_path(filename): # return os.path.join('media') class Location(models.Model): name = models.CharField(max_length=250) local_name = models.CharField(max_length=250) visited = models.BooleanField(default=False) def __str__(self): return self.name class Detail(models.Model): coordinates = models.CharField(max_length=250) detail = models.CharField(max_length=500) img = models.ImageField(upload_to = "media/", blank=True, null=True) location = models.OneToOneField(Location, on_delete=models.CASCADE, primary_key=True) def __str__(self): return self.detail
ed12fe8cde425c75d02dbb9beb98abd8a814292a
alg_selection_sort.py
alg_selection_sort.py
from __future__ import absolute_import from __future__ import print_function from __future__ import division def selection_sort(ls): """Selection Sort algortihm. Time complexity: O(n^2). Space complexity: O(1). """ # Start from the last elemenet reversely: len(ls) - 1, ..., 0. for i_max in reversed(range(len(ls))): # Select the next max, and interchange it with corresponding element. s = 0 for i in range(1, i_max + 1): if ls[i] > ls[s]: s = i ls[s], ls[i_max] = ls[i_max], ls[s] def main(): ls = [54, 26, 93, 17, 77, 31, 44, 55, 20] print('List: {}'.format(ls)) print('By selection sort: ') selection_sort(ls) print(ls) if __name__ == '__main__': main()
from __future__ import absolute_import from __future__ import print_function from __future__ import division def selection_sort(ls): """Selection Sort algortihm. Time complexity: O(n^2). Space complexity: O(1). """ # Start from the last position reversely: len(ls) - 1, ..., 0. for i in reversed(range(len(ls))): # Select next max element, and swap it and element at position i. s = 0 for j in range(1, i + 1): if ls[j] > ls[s]: s = j ls[s], ls[i] = ls[i], ls[s] def main(): ls = [54, 26, 93, 17, 77, 31, 44, 55, 20] print('List: {}'.format(ls)) print('By selection sort: ') selection_sort(ls) print(ls) if __name__ == '__main__': main()
Refactor selection sort w/ comments
Refactor selection sort w/ comments
Python
bsd-2-clause
bowen0701/algorithms_data_structures
from __future__ import absolute_import from __future__ import print_function from __future__ import division def selection_sort(ls): """Selection Sort algortihm. Time complexity: O(n^2). Space complexity: O(1). """ # Start from the last elemenet reversely: len(ls) - 1, ..., 0. for i_max in reversed(range(len(ls))): # Select the next max, and interchange it with corresponding element. s = 0 for i in range(1, i_max + 1): if ls[i] > ls[s]: s = i ls[s], ls[i_max] = ls[i_max], ls[s] def main(): ls = [54, 26, 93, 17, 77, 31, 44, 55, 20] print('List: {}'.format(ls)) print('By selection sort: ') selection_sort(ls) print(ls) if __name__ == '__main__': main() Refactor selection sort w/ comments
from __future__ import absolute_import from __future__ import print_function from __future__ import division def selection_sort(ls): """Selection Sort algortihm. Time complexity: O(n^2). Space complexity: O(1). """ # Start from the last position reversely: len(ls) - 1, ..., 0. for i in reversed(range(len(ls))): # Select next max element, and swap it and element at position i. s = 0 for j in range(1, i + 1): if ls[j] > ls[s]: s = j ls[s], ls[i] = ls[i], ls[s] def main(): ls = [54, 26, 93, 17, 77, 31, 44, 55, 20] print('List: {}'.format(ls)) print('By selection sort: ') selection_sort(ls) print(ls) if __name__ == '__main__': main()
<commit_before>from __future__ import absolute_import from __future__ import print_function from __future__ import division def selection_sort(ls): """Selection Sort algortihm. Time complexity: O(n^2). Space complexity: O(1). """ # Start from the last elemenet reversely: len(ls) - 1, ..., 0. for i_max in reversed(range(len(ls))): # Select the next max, and interchange it with corresponding element. s = 0 for i in range(1, i_max + 1): if ls[i] > ls[s]: s = i ls[s], ls[i_max] = ls[i_max], ls[s] def main(): ls = [54, 26, 93, 17, 77, 31, 44, 55, 20] print('List: {}'.format(ls)) print('By selection sort: ') selection_sort(ls) print(ls) if __name__ == '__main__': main() <commit_msg>Refactor selection sort w/ comments<commit_after>
from __future__ import absolute_import from __future__ import print_function from __future__ import division def selection_sort(ls): """Selection Sort algortihm. Time complexity: O(n^2). Space complexity: O(1). """ # Start from the last position reversely: len(ls) - 1, ..., 0. for i in reversed(range(len(ls))): # Select next max element, and swap it and element at position i. s = 0 for j in range(1, i + 1): if ls[j] > ls[s]: s = j ls[s], ls[i] = ls[i], ls[s] def main(): ls = [54, 26, 93, 17, 77, 31, 44, 55, 20] print('List: {}'.format(ls)) print('By selection sort: ') selection_sort(ls) print(ls) if __name__ == '__main__': main()
from __future__ import absolute_import from __future__ import print_function from __future__ import division def selection_sort(ls): """Selection Sort algortihm. Time complexity: O(n^2). Space complexity: O(1). """ # Start from the last elemenet reversely: len(ls) - 1, ..., 0. for i_max in reversed(range(len(ls))): # Select the next max, and interchange it with corresponding element. s = 0 for i in range(1, i_max + 1): if ls[i] > ls[s]: s = i ls[s], ls[i_max] = ls[i_max], ls[s] def main(): ls = [54, 26, 93, 17, 77, 31, 44, 55, 20] print('List: {}'.format(ls)) print('By selection sort: ') selection_sort(ls) print(ls) if __name__ == '__main__': main() Refactor selection sort w/ commentsfrom __future__ import absolute_import from __future__ import print_function from __future__ import division def selection_sort(ls): """Selection Sort algortihm. Time complexity: O(n^2). Space complexity: O(1). """ # Start from the last position reversely: len(ls) - 1, ..., 0. for i in reversed(range(len(ls))): # Select next max element, and swap it and element at position i. s = 0 for j in range(1, i + 1): if ls[j] > ls[s]: s = j ls[s], ls[i] = ls[i], ls[s] def main(): ls = [54, 26, 93, 17, 77, 31, 44, 55, 20] print('List: {}'.format(ls)) print('By selection sort: ') selection_sort(ls) print(ls) if __name__ == '__main__': main()
<commit_before>from __future__ import absolute_import from __future__ import print_function from __future__ import division def selection_sort(ls): """Selection Sort algortihm. Time complexity: O(n^2). Space complexity: O(1). """ # Start from the last elemenet reversely: len(ls) - 1, ..., 0. for i_max in reversed(range(len(ls))): # Select the next max, and interchange it with corresponding element. s = 0 for i in range(1, i_max + 1): if ls[i] > ls[s]: s = i ls[s], ls[i_max] = ls[i_max], ls[s] def main(): ls = [54, 26, 93, 17, 77, 31, 44, 55, 20] print('List: {}'.format(ls)) print('By selection sort: ') selection_sort(ls) print(ls) if __name__ == '__main__': main() <commit_msg>Refactor selection sort w/ comments<commit_after>from __future__ import absolute_import from __future__ import print_function from __future__ import division def selection_sort(ls): """Selection Sort algortihm. Time complexity: O(n^2). Space complexity: O(1). """ # Start from the last position reversely: len(ls) - 1, ..., 0. for i in reversed(range(len(ls))): # Select next max element, and swap it and element at position i. s = 0 for j in range(1, i + 1): if ls[j] > ls[s]: s = j ls[s], ls[i] = ls[i], ls[s] def main(): ls = [54, 26, 93, 17, 77, 31, 44, 55, 20] print('List: {}'.format(ls)) print('By selection sort: ') selection_sort(ls) print(ls) if __name__ == '__main__': main()
63a4a2dfa733fab15bb7e0d632c8efe6528b82cb
escpos/impl/__init__.py
escpos/impl/__init__.py
# -*- coding: utf-8 -*- # # escpos/impl/__init__.py # # Copyright 2015 Base4 Sistemas Ltda ME # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import epson import daruma
# -*- coding: utf-8 -*- # # escpos/impl/__init__.py # # Copyright 2015 Base4 Sistemas Ltda ME # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from . import epson from . import daruma
Fix import to support Python3
Fix import to support Python3
Python
apache-2.0
base4sistemas/pyescpos
# -*- coding: utf-8 -*- # # escpos/impl/__init__.py # # Copyright 2015 Base4 Sistemas Ltda ME # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import epson import darumaFix import to support Python3
# -*- coding: utf-8 -*- # # escpos/impl/__init__.py # # Copyright 2015 Base4 Sistemas Ltda ME # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from . import epson from . import daruma
<commit_before># -*- coding: utf-8 -*- # # escpos/impl/__init__.py # # Copyright 2015 Base4 Sistemas Ltda ME # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import epson import daruma<commit_msg>Fix import to support Python3<commit_after>
# -*- coding: utf-8 -*- # # escpos/impl/__init__.py # # Copyright 2015 Base4 Sistemas Ltda ME # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from . import epson from . import daruma
# -*- coding: utf-8 -*- # # escpos/impl/__init__.py # # Copyright 2015 Base4 Sistemas Ltda ME # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import epson import darumaFix import to support Python3# -*- coding: utf-8 -*- # # escpos/impl/__init__.py # # Copyright 2015 Base4 Sistemas Ltda ME # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from . import epson from . import daruma
<commit_before># -*- coding: utf-8 -*- # # escpos/impl/__init__.py # # Copyright 2015 Base4 Sistemas Ltda ME # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import epson import daruma<commit_msg>Fix import to support Python3<commit_after># -*- coding: utf-8 -*- # # escpos/impl/__init__.py # # Copyright 2015 Base4 Sistemas Ltda ME # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from . import epson from . import daruma
a492b0395ff56f150d2fde506b6536f0324f31f6
teerace/local_tests.py
teerace/local_tests.py
from django.test.simple import run_tests as default_run_tests from django.conf import settings def run_tests(test_labels, *args, **kwargs): del test_labels return default_run_tests(settings.OUR_APPS, *args, **kwargs)
from django.test.simple import DjangoTestSuiteRunner from django.conf import settings class LocalTestSuiteRunner(DjangoTestSuiteRunner): def run_tests(self, test_labels, extra_tests=None, **kwargs): del test_labels super(LocalTestSuiteRunner, self).run_tests(settings.OUR_APPS, extra_tests, **kwargs)
Test runner is now class-based.
Test runner is now class-based.
Python
bsd-3-clause
SushiTee/teerace,SushiTee/teerace,SushiTee/teerace
from django.test.simple import run_tests as default_run_tests from django.conf import settings def run_tests(test_labels, *args, **kwargs): del test_labels return default_run_tests(settings.OUR_APPS, *args, **kwargs) Test runner is now class-based.
from django.test.simple import DjangoTestSuiteRunner from django.conf import settings class LocalTestSuiteRunner(DjangoTestSuiteRunner): def run_tests(self, test_labels, extra_tests=None, **kwargs): del test_labels super(LocalTestSuiteRunner, self).run_tests(settings.OUR_APPS, extra_tests, **kwargs)
<commit_before>from django.test.simple import run_tests as default_run_tests from django.conf import settings def run_tests(test_labels, *args, **kwargs): del test_labels return default_run_tests(settings.OUR_APPS, *args, **kwargs) <commit_msg>Test runner is now class-based.<commit_after>
from django.test.simple import DjangoTestSuiteRunner from django.conf import settings class LocalTestSuiteRunner(DjangoTestSuiteRunner): def run_tests(self, test_labels, extra_tests=None, **kwargs): del test_labels super(LocalTestSuiteRunner, self).run_tests(settings.OUR_APPS, extra_tests, **kwargs)
from django.test.simple import run_tests as default_run_tests from django.conf import settings def run_tests(test_labels, *args, **kwargs): del test_labels return default_run_tests(settings.OUR_APPS, *args, **kwargs) Test runner is now class-based.from django.test.simple import DjangoTestSuiteRunner from django.conf import settings class LocalTestSuiteRunner(DjangoTestSuiteRunner): def run_tests(self, test_labels, extra_tests=None, **kwargs): del test_labels super(LocalTestSuiteRunner, self).run_tests(settings.OUR_APPS, extra_tests, **kwargs)
<commit_before>from django.test.simple import run_tests as default_run_tests from django.conf import settings def run_tests(test_labels, *args, **kwargs): del test_labels return default_run_tests(settings.OUR_APPS, *args, **kwargs) <commit_msg>Test runner is now class-based.<commit_after>from django.test.simple import DjangoTestSuiteRunner from django.conf import settings class LocalTestSuiteRunner(DjangoTestSuiteRunner): def run_tests(self, test_labels, extra_tests=None, **kwargs): del test_labels super(LocalTestSuiteRunner, self).run_tests(settings.OUR_APPS, extra_tests, **kwargs)
dbc932d7776b22835ff15f086c41e1bff02e9daf
apps/private/views.py
apps/private/views.py
from django.contrib.auth.decorators import user_passes_test from django.http import Http404 from django.shortcuts import redirect, render from accounts.utils import send_activation_email from .forms import InviteForm owner_required = user_passes_test( lambda u: u.is_authenticated() and u.is_owner ) @owner_required def member_list(request): if not request.user.is_owner: raise Http404 organization = request.organization qs = organization.members.all() return render(request, 'private/ornigazation_members.html', { 'object_list': qs }) @owner_required def invite_member(request): form = InviteForm(request.POST or None) if form.is_valid(): user = form.save(commit=False) user.set_unusable_password() user.organization = request.organization user.save() activation = user.make_activation() send_activation_email(request, activation) return redirect('private_member_list') return render(request, 'private/invite_member.html', { 'form': form })
from django.contrib.auth.decorators import user_passes_test from django.http import Http404 from django.shortcuts import redirect, render from accounts.utils import send_activation_email from accounts.forms import InviteForm owner_required = user_passes_test( lambda u: u.is_authenticated() and u.is_owner ) @owner_required def member_list(request): if not request.user.is_owner: raise Http404 organization = request.organization qs = organization.members.all() return render(request, 'private/ornigazation_members.html', { 'object_list': qs }) @owner_required def invite_member(request): form = InviteForm(request.POST or None) if form.is_valid(): user = form.save(commit=False) user.set_unusable_password() user.organization = request.organization user.save() activation = user.make_activation() send_activation_email(request, activation) return redirect('private_member_list') return render(request, 'private/invite_member.html', { 'form': form })
Change import InviteForm from private.forms to accounts.forms
Change import InviteForm from private.forms to accounts.forms
Python
mit
xobb1t/ddash2013,xobb1t/ddash2013
from django.contrib.auth.decorators import user_passes_test from django.http import Http404 from django.shortcuts import redirect, render from accounts.utils import send_activation_email from .forms import InviteForm owner_required = user_passes_test( lambda u: u.is_authenticated() and u.is_owner ) @owner_required def member_list(request): if not request.user.is_owner: raise Http404 organization = request.organization qs = organization.members.all() return render(request, 'private/ornigazation_members.html', { 'object_list': qs }) @owner_required def invite_member(request): form = InviteForm(request.POST or None) if form.is_valid(): user = form.save(commit=False) user.set_unusable_password() user.organization = request.organization user.save() activation = user.make_activation() send_activation_email(request, activation) return redirect('private_member_list') return render(request, 'private/invite_member.html', { 'form': form }) Change import InviteForm from private.forms to accounts.forms
from django.contrib.auth.decorators import user_passes_test from django.http import Http404 from django.shortcuts import redirect, render from accounts.utils import send_activation_email from accounts.forms import InviteForm owner_required = user_passes_test( lambda u: u.is_authenticated() and u.is_owner ) @owner_required def member_list(request): if not request.user.is_owner: raise Http404 organization = request.organization qs = organization.members.all() return render(request, 'private/ornigazation_members.html', { 'object_list': qs }) @owner_required def invite_member(request): form = InviteForm(request.POST or None) if form.is_valid(): user = form.save(commit=False) user.set_unusable_password() user.organization = request.organization user.save() activation = user.make_activation() send_activation_email(request, activation) return redirect('private_member_list') return render(request, 'private/invite_member.html', { 'form': form })
<commit_before>from django.contrib.auth.decorators import user_passes_test from django.http import Http404 from django.shortcuts import redirect, render from accounts.utils import send_activation_email from .forms import InviteForm owner_required = user_passes_test( lambda u: u.is_authenticated() and u.is_owner ) @owner_required def member_list(request): if not request.user.is_owner: raise Http404 organization = request.organization qs = organization.members.all() return render(request, 'private/ornigazation_members.html', { 'object_list': qs }) @owner_required def invite_member(request): form = InviteForm(request.POST or None) if form.is_valid(): user = form.save(commit=False) user.set_unusable_password() user.organization = request.organization user.save() activation = user.make_activation() send_activation_email(request, activation) return redirect('private_member_list') return render(request, 'private/invite_member.html', { 'form': form }) <commit_msg>Change import InviteForm from private.forms to accounts.forms<commit_after>
from django.contrib.auth.decorators import user_passes_test from django.http import Http404 from django.shortcuts import redirect, render from accounts.utils import send_activation_email from accounts.forms import InviteForm owner_required = user_passes_test( lambda u: u.is_authenticated() and u.is_owner ) @owner_required def member_list(request): if not request.user.is_owner: raise Http404 organization = request.organization qs = organization.members.all() return render(request, 'private/ornigazation_members.html', { 'object_list': qs }) @owner_required def invite_member(request): form = InviteForm(request.POST or None) if form.is_valid(): user = form.save(commit=False) user.set_unusable_password() user.organization = request.organization user.save() activation = user.make_activation() send_activation_email(request, activation) return redirect('private_member_list') return render(request, 'private/invite_member.html', { 'form': form })
from django.contrib.auth.decorators import user_passes_test from django.http import Http404 from django.shortcuts import redirect, render from accounts.utils import send_activation_email from .forms import InviteForm owner_required = user_passes_test( lambda u: u.is_authenticated() and u.is_owner ) @owner_required def member_list(request): if not request.user.is_owner: raise Http404 organization = request.organization qs = organization.members.all() return render(request, 'private/ornigazation_members.html', { 'object_list': qs }) @owner_required def invite_member(request): form = InviteForm(request.POST or None) if form.is_valid(): user = form.save(commit=False) user.set_unusable_password() user.organization = request.organization user.save() activation = user.make_activation() send_activation_email(request, activation) return redirect('private_member_list') return render(request, 'private/invite_member.html', { 'form': form }) Change import InviteForm from private.forms to accounts.formsfrom django.contrib.auth.decorators import user_passes_test from django.http import Http404 from django.shortcuts import redirect, render from accounts.utils import send_activation_email from accounts.forms import InviteForm owner_required = user_passes_test( lambda u: u.is_authenticated() and u.is_owner ) @owner_required def member_list(request): if not request.user.is_owner: raise Http404 organization = request.organization qs = organization.members.all() return render(request, 'private/ornigazation_members.html', { 'object_list': qs }) @owner_required def invite_member(request): form = InviteForm(request.POST or None) if form.is_valid(): user = form.save(commit=False) user.set_unusable_password() user.organization = request.organization user.save() activation = user.make_activation() send_activation_email(request, activation) return redirect('private_member_list') return render(request, 'private/invite_member.html', { 'form': form })
<commit_before>from django.contrib.auth.decorators import user_passes_test from django.http import Http404 from django.shortcuts import redirect, render from accounts.utils import send_activation_email from .forms import InviteForm owner_required = user_passes_test( lambda u: u.is_authenticated() and u.is_owner ) @owner_required def member_list(request): if not request.user.is_owner: raise Http404 organization = request.organization qs = organization.members.all() return render(request, 'private/ornigazation_members.html', { 'object_list': qs }) @owner_required def invite_member(request): form = InviteForm(request.POST or None) if form.is_valid(): user = form.save(commit=False) user.set_unusable_password() user.organization = request.organization user.save() activation = user.make_activation() send_activation_email(request, activation) return redirect('private_member_list') return render(request, 'private/invite_member.html', { 'form': form }) <commit_msg>Change import InviteForm from private.forms to accounts.forms<commit_after>from django.contrib.auth.decorators import user_passes_test from django.http import Http404 from django.shortcuts import redirect, render from accounts.utils import send_activation_email from accounts.forms import InviteForm owner_required = user_passes_test( lambda u: u.is_authenticated() and u.is_owner ) @owner_required def member_list(request): if not request.user.is_owner: raise Http404 organization = request.organization qs = organization.members.all() return render(request, 'private/ornigazation_members.html', { 'object_list': qs }) @owner_required def invite_member(request): form = InviteForm(request.POST or None) if form.is_valid(): user = form.save(commit=False) user.set_unusable_password() user.organization = request.organization user.save() activation = user.make_activation() send_activation_email(request, activation) return redirect('private_member_list') return render(request, 'private/invite_member.html', { 'form': form })
252bc8df092f59ecd092ea5904fcc845dc22bee8
dbaas/util/update_instances_with_offering.py
dbaas/util/update_instances_with_offering.py
# coding: utf-8 class UpdateInstances(object): @staticmethod def do(): from dbaas_cloudstack.models import DatabaseInfraOffering from dbaas_cloudstack.models import PlanAttr infra_offerings = DatabaseInfraOffering.objects.all() for infra_offering in infra_offerings: plan_attr = PlanAttr.objects.get(plan=infra_offering.databaseinfra.plan) strong_offering = infra_offering.offering weaker_offering = plan_attr.get_weaker_offering() for instance in infra_offering.databaseinfra.instances.all(): if instance.is_database: instance.offering = strong_offering else: instance.oferring = weaker_offering instance.save()
# coding: utf-8 class UpdateInstances(object): @staticmethod def do(): from dbaas_cloudstack.models import DatabaseInfraOffering from dbaas_cloudstack.models import PlanAttr infra_offerings = DatabaseInfraOffering.objects.all() for infra_offering in infra_offerings: plan_attr = PlanAttr.objects.get(plan=infra_offering.databaseinfra.plan) strong_offering = infra_offering.offering weaker_offering = plan_attr.get_weaker_offering() for host in infra_offering.databaseinfra.hosts: host.offering = strong_offering if host.database_instance() else weaker_offering host.save()
Change script to update offering on Host instead Instance
Change script to update offering on Host instead Instance
Python
bsd-3-clause
globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service
# coding: utf-8 class UpdateInstances(object): @staticmethod def do(): from dbaas_cloudstack.models import DatabaseInfraOffering from dbaas_cloudstack.models import PlanAttr infra_offerings = DatabaseInfraOffering.objects.all() for infra_offering in infra_offerings: plan_attr = PlanAttr.objects.get(plan=infra_offering.databaseinfra.plan) strong_offering = infra_offering.offering weaker_offering = plan_attr.get_weaker_offering() for instance in infra_offering.databaseinfra.instances.all(): if instance.is_database: instance.offering = strong_offering else: instance.oferring = weaker_offering instance.save() Change script to update offering on Host instead Instance
# coding: utf-8 class UpdateInstances(object): @staticmethod def do(): from dbaas_cloudstack.models import DatabaseInfraOffering from dbaas_cloudstack.models import PlanAttr infra_offerings = DatabaseInfraOffering.objects.all() for infra_offering in infra_offerings: plan_attr = PlanAttr.objects.get(plan=infra_offering.databaseinfra.plan) strong_offering = infra_offering.offering weaker_offering = plan_attr.get_weaker_offering() for host in infra_offering.databaseinfra.hosts: host.offering = strong_offering if host.database_instance() else weaker_offering host.save()
<commit_before># coding: utf-8 class UpdateInstances(object): @staticmethod def do(): from dbaas_cloudstack.models import DatabaseInfraOffering from dbaas_cloudstack.models import PlanAttr infra_offerings = DatabaseInfraOffering.objects.all() for infra_offering in infra_offerings: plan_attr = PlanAttr.objects.get(plan=infra_offering.databaseinfra.plan) strong_offering = infra_offering.offering weaker_offering = plan_attr.get_weaker_offering() for instance in infra_offering.databaseinfra.instances.all(): if instance.is_database: instance.offering = strong_offering else: instance.oferring = weaker_offering instance.save() <commit_msg>Change script to update offering on Host instead Instance<commit_after>
# coding: utf-8 class UpdateInstances(object): @staticmethod def do(): from dbaas_cloudstack.models import DatabaseInfraOffering from dbaas_cloudstack.models import PlanAttr infra_offerings = DatabaseInfraOffering.objects.all() for infra_offering in infra_offerings: plan_attr = PlanAttr.objects.get(plan=infra_offering.databaseinfra.plan) strong_offering = infra_offering.offering weaker_offering = plan_attr.get_weaker_offering() for host in infra_offering.databaseinfra.hosts: host.offering = strong_offering if host.database_instance() else weaker_offering host.save()
# coding: utf-8 class UpdateInstances(object): @staticmethod def do(): from dbaas_cloudstack.models import DatabaseInfraOffering from dbaas_cloudstack.models import PlanAttr infra_offerings = DatabaseInfraOffering.objects.all() for infra_offering in infra_offerings: plan_attr = PlanAttr.objects.get(plan=infra_offering.databaseinfra.plan) strong_offering = infra_offering.offering weaker_offering = plan_attr.get_weaker_offering() for instance in infra_offering.databaseinfra.instances.all(): if instance.is_database: instance.offering = strong_offering else: instance.oferring = weaker_offering instance.save() Change script to update offering on Host instead Instance# coding: utf-8 class UpdateInstances(object): @staticmethod def do(): from dbaas_cloudstack.models import DatabaseInfraOffering from dbaas_cloudstack.models import PlanAttr infra_offerings = DatabaseInfraOffering.objects.all() for infra_offering in infra_offerings: plan_attr = PlanAttr.objects.get(plan=infra_offering.databaseinfra.plan) strong_offering = infra_offering.offering weaker_offering = plan_attr.get_weaker_offering() for host in infra_offering.databaseinfra.hosts: host.offering = strong_offering if host.database_instance() else weaker_offering host.save()
<commit_before># coding: utf-8 class UpdateInstances(object): @staticmethod def do(): from dbaas_cloudstack.models import DatabaseInfraOffering from dbaas_cloudstack.models import PlanAttr infra_offerings = DatabaseInfraOffering.objects.all() for infra_offering in infra_offerings: plan_attr = PlanAttr.objects.get(plan=infra_offering.databaseinfra.plan) strong_offering = infra_offering.offering weaker_offering = plan_attr.get_weaker_offering() for instance in infra_offering.databaseinfra.instances.all(): if instance.is_database: instance.offering = strong_offering else: instance.oferring = weaker_offering instance.save() <commit_msg>Change script to update offering on Host instead Instance<commit_after># coding: utf-8 class UpdateInstances(object): @staticmethod def do(): from dbaas_cloudstack.models import DatabaseInfraOffering from dbaas_cloudstack.models import PlanAttr infra_offerings = DatabaseInfraOffering.objects.all() for infra_offering in infra_offerings: plan_attr = PlanAttr.objects.get(plan=infra_offering.databaseinfra.plan) strong_offering = infra_offering.offering weaker_offering = plan_attr.get_weaker_offering() for host in infra_offering.databaseinfra.hosts: host.offering = strong_offering if host.database_instance() else weaker_offering host.save()
d3ca58e098fd872eb32c82e87a76361829d68f37
config/__init__.py
config/__init__.py
""" This module is responsible for handling configuration and files related to it, including calibration parameters. """ import configparser from os import path import syslog """ Default options """ #TODO: more default options... _CONFIG_DEFAULTS = { "general": { "poll_interval": 10, "averaging_time": 9, }, "calibration" : { "sensor_min_value" : 0, "sensor_max_value" : 1024, }, } """ Initialize a configparser dictionary with given or default filename and return it """ def get_config_dict(filename = None): if filename is None: cfg_path = path.dirname(__file__) filename = path.join(cfg_path, "config.ini") cp = configparser.ConfigParser() #_CONFIG_DEFAULTS) # read default values from dict if they are not given in the config file. cp.read_dict(_CONFIG_DEFAULTS) syslog.syslog(syslog.LOG_INFO, "config: Using configuration file " + filename) cp.read(filename) return cp #def __getitem__(self, i): self.configparser. if __name__ == "__main__": import argparse ap = argparse.ArgumentParser() ap.add_argument("-c", "--config", dest = "config_file", help = "use CONFIG_FILE as the configuration file instead of the default") args = ap.parse_args() cfg = get_config_dict(args.config_file) print(str(cfg))
""" This module is responsible for handling configuration and files related to it, including calibration parameters. """ import configparser from os import path import syslog """ Default options """ #TODO: more default options... _CONFIG_DEFAULTS = { "general": { "poll_interval": 10, "averaging_time": 9, }, "calibration" : { "sensor_min_value" : 0, "sensor_max_value" : 1024, }, } """ Initialize a configparser dictionary with given or default filename and return it """ def get_config_dict(filename = None): if filename is None: cfg_path = path.dirname(__file__) filename = path.join(cfg_path, "config.ini") cp = configparser.ConfigParser() #_CONFIG_DEFAULTS) # read default values from dict if they are not given in the config file. cp.read_dict(_CONFIG_DEFAULTS) syslog.syslog(syslog.LOG_INFO, "config: Using configuration file " + filename) cp.read(filename) return cp #def __getitem__(self, i): self.configparser. if __name__ == "__main__": import argparse from pprint import pprint ap = argparse.ArgumentParser() ap.add_argument("-c", "--config", dest = "config_file", help = "use CONFIG_FILE as the configuration file instead of the default") args = ap.parse_args() cfg = get_config_dict(args.config_file) for sec in cfg.sections(): print("{}:".format(sec)) pprint(list(cfg[sec].items())) print("")
Print configuration contents in main.
Print configuration contents in main.
Python
mit
mgunyho/kiltiskahvi
""" This module is responsible for handling configuration and files related to it, including calibration parameters. """ import configparser from os import path import syslog """ Default options """ #TODO: more default options... _CONFIG_DEFAULTS = { "general": { "poll_interval": 10, "averaging_time": 9, }, "calibration" : { "sensor_min_value" : 0, "sensor_max_value" : 1024, }, } """ Initialize a configparser dictionary with given or default filename and return it """ def get_config_dict(filename = None): if filename is None: cfg_path = path.dirname(__file__) filename = path.join(cfg_path, "config.ini") cp = configparser.ConfigParser() #_CONFIG_DEFAULTS) # read default values from dict if they are not given in the config file. cp.read_dict(_CONFIG_DEFAULTS) syslog.syslog(syslog.LOG_INFO, "config: Using configuration file " + filename) cp.read(filename) return cp #def __getitem__(self, i): self.configparser. if __name__ == "__main__": import argparse ap = argparse.ArgumentParser() ap.add_argument("-c", "--config", dest = "config_file", help = "use CONFIG_FILE as the configuration file instead of the default") args = ap.parse_args() cfg = get_config_dict(args.config_file) print(str(cfg)) Print configuration contents in main.
""" This module is responsible for handling configuration and files related to it, including calibration parameters. """ import configparser from os import path import syslog """ Default options """ #TODO: more default options... _CONFIG_DEFAULTS = { "general": { "poll_interval": 10, "averaging_time": 9, }, "calibration" : { "sensor_min_value" : 0, "sensor_max_value" : 1024, }, } """ Initialize a configparser dictionary with given or default filename and return it """ def get_config_dict(filename = None): if filename is None: cfg_path = path.dirname(__file__) filename = path.join(cfg_path, "config.ini") cp = configparser.ConfigParser() #_CONFIG_DEFAULTS) # read default values from dict if they are not given in the config file. cp.read_dict(_CONFIG_DEFAULTS) syslog.syslog(syslog.LOG_INFO, "config: Using configuration file " + filename) cp.read(filename) return cp #def __getitem__(self, i): self.configparser. if __name__ == "__main__": import argparse from pprint import pprint ap = argparse.ArgumentParser() ap.add_argument("-c", "--config", dest = "config_file", help = "use CONFIG_FILE as the configuration file instead of the default") args = ap.parse_args() cfg = get_config_dict(args.config_file) for sec in cfg.sections(): print("{}:".format(sec)) pprint(list(cfg[sec].items())) print("")
<commit_before>""" This module is responsible for handling configuration and files related to it, including calibration parameters. """ import configparser from os import path import syslog """ Default options """ #TODO: more default options... _CONFIG_DEFAULTS = { "general": { "poll_interval": 10, "averaging_time": 9, }, "calibration" : { "sensor_min_value" : 0, "sensor_max_value" : 1024, }, } """ Initialize a configparser dictionary with given or default filename and return it """ def get_config_dict(filename = None): if filename is None: cfg_path = path.dirname(__file__) filename = path.join(cfg_path, "config.ini") cp = configparser.ConfigParser() #_CONFIG_DEFAULTS) # read default values from dict if they are not given in the config file. cp.read_dict(_CONFIG_DEFAULTS) syslog.syslog(syslog.LOG_INFO, "config: Using configuration file " + filename) cp.read(filename) return cp #def __getitem__(self, i): self.configparser. if __name__ == "__main__": import argparse ap = argparse.ArgumentParser() ap.add_argument("-c", "--config", dest = "config_file", help = "use CONFIG_FILE as the configuration file instead of the default") args = ap.parse_args() cfg = get_config_dict(args.config_file) print(str(cfg)) <commit_msg>Print configuration contents in main.<commit_after>
""" This module is responsible for handling configuration and files related to it, including calibration parameters. """ import configparser from os import path import syslog """ Default options """ #TODO: more default options... _CONFIG_DEFAULTS = { "general": { "poll_interval": 10, "averaging_time": 9, }, "calibration" : { "sensor_min_value" : 0, "sensor_max_value" : 1024, }, } """ Initialize a configparser dictionary with given or default filename and return it """ def get_config_dict(filename = None): if filename is None: cfg_path = path.dirname(__file__) filename = path.join(cfg_path, "config.ini") cp = configparser.ConfigParser() #_CONFIG_DEFAULTS) # read default values from dict if they are not given in the config file. cp.read_dict(_CONFIG_DEFAULTS) syslog.syslog(syslog.LOG_INFO, "config: Using configuration file " + filename) cp.read(filename) return cp #def __getitem__(self, i): self.configparser. if __name__ == "__main__": import argparse from pprint import pprint ap = argparse.ArgumentParser() ap.add_argument("-c", "--config", dest = "config_file", help = "use CONFIG_FILE as the configuration file instead of the default") args = ap.parse_args() cfg = get_config_dict(args.config_file) for sec in cfg.sections(): print("{}:".format(sec)) pprint(list(cfg[sec].items())) print("")
""" This module is responsible for handling configuration and files related to it, including calibration parameters. """ import configparser from os import path import syslog """ Default options """ #TODO: more default options... _CONFIG_DEFAULTS = { "general": { "poll_interval": 10, "averaging_time": 9, }, "calibration" : { "sensor_min_value" : 0, "sensor_max_value" : 1024, }, } """ Initialize a configparser dictionary with given or default filename and return it """ def get_config_dict(filename = None): if filename is None: cfg_path = path.dirname(__file__) filename = path.join(cfg_path, "config.ini") cp = configparser.ConfigParser() #_CONFIG_DEFAULTS) # read default values from dict if they are not given in the config file. cp.read_dict(_CONFIG_DEFAULTS) syslog.syslog(syslog.LOG_INFO, "config: Using configuration file " + filename) cp.read(filename) return cp #def __getitem__(self, i): self.configparser. if __name__ == "__main__": import argparse ap = argparse.ArgumentParser() ap.add_argument("-c", "--config", dest = "config_file", help = "use CONFIG_FILE as the configuration file instead of the default") args = ap.parse_args() cfg = get_config_dict(args.config_file) print(str(cfg)) Print configuration contents in main.""" This module is responsible for handling configuration and files related to it, including calibration parameters. """ import configparser from os import path import syslog """ Default options """ #TODO: more default options... _CONFIG_DEFAULTS = { "general": { "poll_interval": 10, "averaging_time": 9, }, "calibration" : { "sensor_min_value" : 0, "sensor_max_value" : 1024, }, } """ Initialize a configparser dictionary with given or default filename and return it """ def get_config_dict(filename = None): if filename is None: cfg_path = path.dirname(__file__) filename = path.join(cfg_path, "config.ini") cp = configparser.ConfigParser() #_CONFIG_DEFAULTS) # read default values from dict if they are not given in the config file. cp.read_dict(_CONFIG_DEFAULTS) syslog.syslog(syslog.LOG_INFO, "config: Using configuration file " + filename) cp.read(filename) return cp #def __getitem__(self, i): self.configparser. if __name__ == "__main__": import argparse from pprint import pprint ap = argparse.ArgumentParser() ap.add_argument("-c", "--config", dest = "config_file", help = "use CONFIG_FILE as the configuration file instead of the default") args = ap.parse_args() cfg = get_config_dict(args.config_file) for sec in cfg.sections(): print("{}:".format(sec)) pprint(list(cfg[sec].items())) print("")
<commit_before>""" This module is responsible for handling configuration and files related to it, including calibration parameters. """ import configparser from os import path import syslog """ Default options """ #TODO: more default options... _CONFIG_DEFAULTS = { "general": { "poll_interval": 10, "averaging_time": 9, }, "calibration" : { "sensor_min_value" : 0, "sensor_max_value" : 1024, }, } """ Initialize a configparser dictionary with given or default filename and return it """ def get_config_dict(filename = None): if filename is None: cfg_path = path.dirname(__file__) filename = path.join(cfg_path, "config.ini") cp = configparser.ConfigParser() #_CONFIG_DEFAULTS) # read default values from dict if they are not given in the config file. cp.read_dict(_CONFIG_DEFAULTS) syslog.syslog(syslog.LOG_INFO, "config: Using configuration file " + filename) cp.read(filename) return cp #def __getitem__(self, i): self.configparser. if __name__ == "__main__": import argparse ap = argparse.ArgumentParser() ap.add_argument("-c", "--config", dest = "config_file", help = "use CONFIG_FILE as the configuration file instead of the default") args = ap.parse_args() cfg = get_config_dict(args.config_file) print(str(cfg)) <commit_msg>Print configuration contents in main.<commit_after>""" This module is responsible for handling configuration and files related to it, including calibration parameters. """ import configparser from os import path import syslog """ Default options """ #TODO: more default options... _CONFIG_DEFAULTS = { "general": { "poll_interval": 10, "averaging_time": 9, }, "calibration" : { "sensor_min_value" : 0, "sensor_max_value" : 1024, }, } """ Initialize a configparser dictionary with given or default filename and return it """ def get_config_dict(filename = None): if filename is None: cfg_path = path.dirname(__file__) filename = path.join(cfg_path, "config.ini") cp = configparser.ConfigParser() #_CONFIG_DEFAULTS) # read default values from dict if they are not given in the config file. cp.read_dict(_CONFIG_DEFAULTS) syslog.syslog(syslog.LOG_INFO, "config: Using configuration file " + filename) cp.read(filename) return cp #def __getitem__(self, i): self.configparser. if __name__ == "__main__": import argparse from pprint import pprint ap = argparse.ArgumentParser() ap.add_argument("-c", "--config", dest = "config_file", help = "use CONFIG_FILE as the configuration file instead of the default") args = ap.parse_args() cfg = get_config_dict(args.config_file) for sec in cfg.sections(): print("{}:".format(sec)) pprint(list(cfg[sec].items())) print("")
579101f714201ba2cc933f64c83ca6cfda8eca8c
test/wheel_velocity.py
test/wheel_velocity.py
#!/usr/bin/python from config import Config from motor import Motor import Rpi.GPIO as GPIO import json import sys import time def _init_motor(self, pin1_s, pin2_s, pinE_s): pin1 = self.config.get("motors", pin1_s) pin2 = self.config.get("motors", pin2_s) pinE = self.config.get("motors", pinE_s) if pin1 == None or pin2 == None or pinE == None: print "Get motor pins failed" return None return Motor(pin1, pin2, pinE) config = Config() if config == None: print "Get config failed" sys.exit(1) GPIO.setmode(GPIO.BCM) right = _init_motor("in1", "in2", "ena") max_power = 40 try: for i in range(20, max_power + 1, 10): print "Updating power to " + i right.update(i, True) count = 0 while count < 5: count++; time.sleep(1) except Exception as e: print e right.stop() right.stop()
#!/usr/bin/python from config import Config from motor import Motor from encoder import Encoder import Rpi.GPIO as GPIO import json import sys import time def _init_motor(config, pin1_s, pin2_s, pinE_s): pin1 = config.get("motors", pin1_s) pin2 = config.get("motors", pin2_s) pinE = config.get("motors", pinE_s) if pin1 == None or pin2 == None or pinE == None: print "Get motor pins failed" return None return Motor(pin1, pin2, pinE) config = Config() if config == None: print "Get config failed" sys.exit(1) GPIO.setmode(GPIO.BCM) right = _init_motor(config, "in1", "in2", "ena") right_enc = Encoder("right") max_power = 40 try: for i in range(20, max_power + 1, 10): print "Updating power to " + i right.update(i, True) count = 0 while count < 5: count++; time.sleep(1) except Exception as e: print e right.stop() right.stop()
Add encoder to wheel velocity test
Add encoder to wheel velocity test
Python
mit
thomasweng15/rover
#!/usr/bin/python from config import Config from motor import Motor import Rpi.GPIO as GPIO import json import sys import time def _init_motor(self, pin1_s, pin2_s, pinE_s): pin1 = self.config.get("motors", pin1_s) pin2 = self.config.get("motors", pin2_s) pinE = self.config.get("motors", pinE_s) if pin1 == None or pin2 == None or pinE == None: print "Get motor pins failed" return None return Motor(pin1, pin2, pinE) config = Config() if config == None: print "Get config failed" sys.exit(1) GPIO.setmode(GPIO.BCM) right = _init_motor("in1", "in2", "ena") max_power = 40 try: for i in range(20, max_power + 1, 10): print "Updating power to " + i right.update(i, True) count = 0 while count < 5: count++; time.sleep(1) except Exception as e: print e right.stop() right.stop()Add encoder to wheel velocity test
#!/usr/bin/python from config import Config from motor import Motor from encoder import Encoder import Rpi.GPIO as GPIO import json import sys import time def _init_motor(config, pin1_s, pin2_s, pinE_s): pin1 = config.get("motors", pin1_s) pin2 = config.get("motors", pin2_s) pinE = config.get("motors", pinE_s) if pin1 == None or pin2 == None or pinE == None: print "Get motor pins failed" return None return Motor(pin1, pin2, pinE) config = Config() if config == None: print "Get config failed" sys.exit(1) GPIO.setmode(GPIO.BCM) right = _init_motor(config, "in1", "in2", "ena") right_enc = Encoder("right") max_power = 40 try: for i in range(20, max_power + 1, 10): print "Updating power to " + i right.update(i, True) count = 0 while count < 5: count++; time.sleep(1) except Exception as e: print e right.stop() right.stop()
<commit_before>#!/usr/bin/python from config import Config from motor import Motor import Rpi.GPIO as GPIO import json import sys import time def _init_motor(self, pin1_s, pin2_s, pinE_s): pin1 = self.config.get("motors", pin1_s) pin2 = self.config.get("motors", pin2_s) pinE = self.config.get("motors", pinE_s) if pin1 == None or pin2 == None or pinE == None: print "Get motor pins failed" return None return Motor(pin1, pin2, pinE) config = Config() if config == None: print "Get config failed" sys.exit(1) GPIO.setmode(GPIO.BCM) right = _init_motor("in1", "in2", "ena") max_power = 40 try: for i in range(20, max_power + 1, 10): print "Updating power to " + i right.update(i, True) count = 0 while count < 5: count++; time.sleep(1) except Exception as e: print e right.stop() right.stop()<commit_msg>Add encoder to wheel velocity test<commit_after>
#!/usr/bin/python from config import Config from motor import Motor from encoder import Encoder import Rpi.GPIO as GPIO import json import sys import time def _init_motor(config, pin1_s, pin2_s, pinE_s): pin1 = config.get("motors", pin1_s) pin2 = config.get("motors", pin2_s) pinE = config.get("motors", pinE_s) if pin1 == None or pin2 == None or pinE == None: print "Get motor pins failed" return None return Motor(pin1, pin2, pinE) config = Config() if config == None: print "Get config failed" sys.exit(1) GPIO.setmode(GPIO.BCM) right = _init_motor(config, "in1", "in2", "ena") right_enc = Encoder("right") max_power = 40 try: for i in range(20, max_power + 1, 10): print "Updating power to " + i right.update(i, True) count = 0 while count < 5: count++; time.sleep(1) except Exception as e: print e right.stop() right.stop()
#!/usr/bin/python from config import Config from motor import Motor import Rpi.GPIO as GPIO import json import sys import time def _init_motor(self, pin1_s, pin2_s, pinE_s): pin1 = self.config.get("motors", pin1_s) pin2 = self.config.get("motors", pin2_s) pinE = self.config.get("motors", pinE_s) if pin1 == None or pin2 == None or pinE == None: print "Get motor pins failed" return None return Motor(pin1, pin2, pinE) config = Config() if config == None: print "Get config failed" sys.exit(1) GPIO.setmode(GPIO.BCM) right = _init_motor("in1", "in2", "ena") max_power = 40 try: for i in range(20, max_power + 1, 10): print "Updating power to " + i right.update(i, True) count = 0 while count < 5: count++; time.sleep(1) except Exception as e: print e right.stop() right.stop()Add encoder to wheel velocity test#!/usr/bin/python from config import Config from motor import Motor from encoder import Encoder import Rpi.GPIO as GPIO import json import sys import time def _init_motor(config, pin1_s, pin2_s, pinE_s): pin1 = config.get("motors", pin1_s) pin2 = config.get("motors", pin2_s) pinE = config.get("motors", pinE_s) if pin1 == None or pin2 == None or pinE == None: print "Get motor pins failed" return None return Motor(pin1, pin2, pinE) config = Config() if config == None: print "Get config failed" sys.exit(1) GPIO.setmode(GPIO.BCM) right = _init_motor(config, "in1", "in2", "ena") right_enc = Encoder("right") max_power = 40 try: for i in range(20, max_power + 1, 10): print "Updating power to " + i right.update(i, True) count = 0 while count < 5: count++; time.sleep(1) except Exception as e: print e right.stop() right.stop()
<commit_before>#!/usr/bin/python from config import Config from motor import Motor import Rpi.GPIO as GPIO import json import sys import time def _init_motor(self, pin1_s, pin2_s, pinE_s): pin1 = self.config.get("motors", pin1_s) pin2 = self.config.get("motors", pin2_s) pinE = self.config.get("motors", pinE_s) if pin1 == None or pin2 == None or pinE == None: print "Get motor pins failed" return None return Motor(pin1, pin2, pinE) config = Config() if config == None: print "Get config failed" sys.exit(1) GPIO.setmode(GPIO.BCM) right = _init_motor("in1", "in2", "ena") max_power = 40 try: for i in range(20, max_power + 1, 10): print "Updating power to " + i right.update(i, True) count = 0 while count < 5: count++; time.sleep(1) except Exception as e: print e right.stop() right.stop()<commit_msg>Add encoder to wheel velocity test<commit_after>#!/usr/bin/python from config import Config from motor import Motor from encoder import Encoder import Rpi.GPIO as GPIO import json import sys import time def _init_motor(config, pin1_s, pin2_s, pinE_s): pin1 = config.get("motors", pin1_s) pin2 = config.get("motors", pin2_s) pinE = config.get("motors", pinE_s) if pin1 == None or pin2 == None or pinE == None: print "Get motor pins failed" return None return Motor(pin1, pin2, pinE) config = Config() if config == None: print "Get config failed" sys.exit(1) GPIO.setmode(GPIO.BCM) right = _init_motor(config, "in1", "in2", "ena") right_enc = Encoder("right") max_power = 40 try: for i in range(20, max_power + 1, 10): print "Updating power to " + i right.update(i, True) count = 0 while count < 5: count++; time.sleep(1) except Exception as e: print e right.stop() right.stop()
0d491c616284933e35bb5d61a94828aed0c8d3f2
setuptools/logging.py
setuptools/logging.py
import sys import logging import distutils.log from . import monkey def _not_warning(record): return record.levelno < logging.WARNING def configure(): """ Configure logging to emit warning and above to stderr and everything else to stdout. This behavior is provided for compatibilty with distutils.log but may change in the future. """ err_handler = logging.StreamHandler() err_handler.setLevel(logging.WARNING) out_handler = logging.StreamHandler(sys.stdout) out_handler.addFilter(_not_warning) handlers = err_handler, out_handler logging.basicConfig( format="{message}", style='{', handlers=handlers, level=logging.DEBUG) monkey.patch_func(set_threshold, distutils.log, 'set_threshold') def set_threshold(level): logging.root.setLevel(level*10) return set_threshold.unpatched(level)
import sys import logging import distutils.log from . import monkey def _not_warning(record): return record.levelno < logging.WARNING def configure(): """ Configure logging to emit warning and above to stderr and everything else to stdout. This behavior is provided for compatibilty with distutils.log but may change in the future. """ err_handler = logging.StreamHandler() err_handler.setLevel(logging.WARNING) out_handler = logging.StreamHandler(sys.stdout) out_handler.addFilter(_not_warning) handlers = err_handler, out_handler logging.basicConfig( format="{message}", style='{', handlers=handlers, level=logging.DEBUG) monkey.patch_func(set_threshold, distutils.log, 'set_threshold') # For some reason `distutils.log` module is getting cached in `distutils.dist` # and then loaded again when we have the opportunity to patch it. # This implies: id(distutils.log) != id(distutils.dist.log). # We need to make sure the same module object is used everywhere: distutils.dist.log = distutils.log def set_threshold(level): logging.root.setLevel(level*10) return set_threshold.unpatched(level)
Fix weird distutils.log reloading/caching situation
Fix weird distutils.log reloading/caching situation For some reason `distutils.log` module is getting cached in `distutils.dist` and then loaded again when we have the opportunity to patch it. This implies: id(distutils.log) != id(distutils.dist.log). We need to make sure the same module object is used everywhere.
Python
mit
pypa/setuptools,pypa/setuptools,pypa/setuptools
import sys import logging import distutils.log from . import monkey def _not_warning(record): return record.levelno < logging.WARNING def configure(): """ Configure logging to emit warning and above to stderr and everything else to stdout. This behavior is provided for compatibilty with distutils.log but may change in the future. """ err_handler = logging.StreamHandler() err_handler.setLevel(logging.WARNING) out_handler = logging.StreamHandler(sys.stdout) out_handler.addFilter(_not_warning) handlers = err_handler, out_handler logging.basicConfig( format="{message}", style='{', handlers=handlers, level=logging.DEBUG) monkey.patch_func(set_threshold, distutils.log, 'set_threshold') def set_threshold(level): logging.root.setLevel(level*10) return set_threshold.unpatched(level) Fix weird distutils.log reloading/caching situation For some reason `distutils.log` module is getting cached in `distutils.dist` and then loaded again when we have the opportunity to patch it. This implies: id(distutils.log) != id(distutils.dist.log). We need to make sure the same module object is used everywhere.
import sys import logging import distutils.log from . import monkey def _not_warning(record): return record.levelno < logging.WARNING def configure(): """ Configure logging to emit warning and above to stderr and everything else to stdout. This behavior is provided for compatibilty with distutils.log but may change in the future. """ err_handler = logging.StreamHandler() err_handler.setLevel(logging.WARNING) out_handler = logging.StreamHandler(sys.stdout) out_handler.addFilter(_not_warning) handlers = err_handler, out_handler logging.basicConfig( format="{message}", style='{', handlers=handlers, level=logging.DEBUG) monkey.patch_func(set_threshold, distutils.log, 'set_threshold') # For some reason `distutils.log` module is getting cached in `distutils.dist` # and then loaded again when we have the opportunity to patch it. # This implies: id(distutils.log) != id(distutils.dist.log). # We need to make sure the same module object is used everywhere: distutils.dist.log = distutils.log def set_threshold(level): logging.root.setLevel(level*10) return set_threshold.unpatched(level)
<commit_before>import sys import logging import distutils.log from . import monkey def _not_warning(record): return record.levelno < logging.WARNING def configure(): """ Configure logging to emit warning and above to stderr and everything else to stdout. This behavior is provided for compatibilty with distutils.log but may change in the future. """ err_handler = logging.StreamHandler() err_handler.setLevel(logging.WARNING) out_handler = logging.StreamHandler(sys.stdout) out_handler.addFilter(_not_warning) handlers = err_handler, out_handler logging.basicConfig( format="{message}", style='{', handlers=handlers, level=logging.DEBUG) monkey.patch_func(set_threshold, distutils.log, 'set_threshold') def set_threshold(level): logging.root.setLevel(level*10) return set_threshold.unpatched(level) <commit_msg>Fix weird distutils.log reloading/caching situation For some reason `distutils.log` module is getting cached in `distutils.dist` and then loaded again when we have the opportunity to patch it. This implies: id(distutils.log) != id(distutils.dist.log). We need to make sure the same module object is used everywhere.<commit_after>
import sys import logging import distutils.log from . import monkey def _not_warning(record): return record.levelno < logging.WARNING def configure(): """ Configure logging to emit warning and above to stderr and everything else to stdout. This behavior is provided for compatibilty with distutils.log but may change in the future. """ err_handler = logging.StreamHandler() err_handler.setLevel(logging.WARNING) out_handler = logging.StreamHandler(sys.stdout) out_handler.addFilter(_not_warning) handlers = err_handler, out_handler logging.basicConfig( format="{message}", style='{', handlers=handlers, level=logging.DEBUG) monkey.patch_func(set_threshold, distutils.log, 'set_threshold') # For some reason `distutils.log` module is getting cached in `distutils.dist` # and then loaded again when we have the opportunity to patch it. # This implies: id(distutils.log) != id(distutils.dist.log). # We need to make sure the same module object is used everywhere: distutils.dist.log = distutils.log def set_threshold(level): logging.root.setLevel(level*10) return set_threshold.unpatched(level)
import sys import logging import distutils.log from . import monkey def _not_warning(record): return record.levelno < logging.WARNING def configure(): """ Configure logging to emit warning and above to stderr and everything else to stdout. This behavior is provided for compatibilty with distutils.log but may change in the future. """ err_handler = logging.StreamHandler() err_handler.setLevel(logging.WARNING) out_handler = logging.StreamHandler(sys.stdout) out_handler.addFilter(_not_warning) handlers = err_handler, out_handler logging.basicConfig( format="{message}", style='{', handlers=handlers, level=logging.DEBUG) monkey.patch_func(set_threshold, distutils.log, 'set_threshold') def set_threshold(level): logging.root.setLevel(level*10) return set_threshold.unpatched(level) Fix weird distutils.log reloading/caching situation For some reason `distutils.log` module is getting cached in `distutils.dist` and then loaded again when we have the opportunity to patch it. This implies: id(distutils.log) != id(distutils.dist.log). We need to make sure the same module object is used everywhere.import sys import logging import distutils.log from . import monkey def _not_warning(record): return record.levelno < logging.WARNING def configure(): """ Configure logging to emit warning and above to stderr and everything else to stdout. This behavior is provided for compatibilty with distutils.log but may change in the future. """ err_handler = logging.StreamHandler() err_handler.setLevel(logging.WARNING) out_handler = logging.StreamHandler(sys.stdout) out_handler.addFilter(_not_warning) handlers = err_handler, out_handler logging.basicConfig( format="{message}", style='{', handlers=handlers, level=logging.DEBUG) monkey.patch_func(set_threshold, distutils.log, 'set_threshold') # For some reason `distutils.log` module is getting cached in `distutils.dist` # and then loaded again when we have the opportunity to patch it. # This implies: id(distutils.log) != id(distutils.dist.log). # We need to make sure the same module object is used everywhere: distutils.dist.log = distutils.log def set_threshold(level): logging.root.setLevel(level*10) return set_threshold.unpatched(level)
<commit_before>import sys import logging import distutils.log from . import monkey def _not_warning(record): return record.levelno < logging.WARNING def configure(): """ Configure logging to emit warning and above to stderr and everything else to stdout. This behavior is provided for compatibilty with distutils.log but may change in the future. """ err_handler = logging.StreamHandler() err_handler.setLevel(logging.WARNING) out_handler = logging.StreamHandler(sys.stdout) out_handler.addFilter(_not_warning) handlers = err_handler, out_handler logging.basicConfig( format="{message}", style='{', handlers=handlers, level=logging.DEBUG) monkey.patch_func(set_threshold, distutils.log, 'set_threshold') def set_threshold(level): logging.root.setLevel(level*10) return set_threshold.unpatched(level) <commit_msg>Fix weird distutils.log reloading/caching situation For some reason `distutils.log` module is getting cached in `distutils.dist` and then loaded again when we have the opportunity to patch it. This implies: id(distutils.log) != id(distutils.dist.log). We need to make sure the same module object is used everywhere.<commit_after>import sys import logging import distutils.log from . import monkey def _not_warning(record): return record.levelno < logging.WARNING def configure(): """ Configure logging to emit warning and above to stderr and everything else to stdout. This behavior is provided for compatibilty with distutils.log but may change in the future. """ err_handler = logging.StreamHandler() err_handler.setLevel(logging.WARNING) out_handler = logging.StreamHandler(sys.stdout) out_handler.addFilter(_not_warning) handlers = err_handler, out_handler logging.basicConfig( format="{message}", style='{', handlers=handlers, level=logging.DEBUG) monkey.patch_func(set_threshold, distutils.log, 'set_threshold') # For some reason `distutils.log` module is getting cached in `distutils.dist` # and then loaded again when we have the opportunity to patch it. # This implies: id(distutils.log) != id(distutils.dist.log). # We need to make sure the same module object is used everywhere: distutils.dist.log = distutils.log def set_threshold(level): logging.root.setLevel(level*10) return set_threshold.unpatched(level)
799d6738bd189fa202f45c10e7b5361f71f14c57
bin/request_domain.py
bin/request_domain.py
#!/usr/bin/python """An example demonstrating the client-side usage of the cretificate request API endpoint. """ import requests, sys, json otp = sys.argv[1] domain_req_url = 'https://spire.cloudfleet.io/api/v1/blimp/domain' domain_txt_path = '/opt/cloudfleet/data/config/domain.txt' print('retrieving domain for blimp: ' + domain_req_url) r = requests.get(domain_req_url, headers={'X-AUTH-OTP': otp}) if r.status_code == 200: print('Success: %s' % r.text) result_dict = r.json() if "domain" in result_dict: with open(domain_txt_path, 'w') as domain_txt_file: domain_txt_file.write(result_dict['domain']) quit(0) else: quit(1) else: print('Error: %s' % r.text) quit(1)
#!/usr/bin/python """An example demonstrating the client-side usage of the cretificate request API endpoint. """ import requests, sys, json otp = sys.argv[1] domain_req_url = 'https://spire.cloudfleet.io/api/v1/blimp/domain' domain_txt_path = '/opt/cloudfleet/data/config/domain.txt' print('retrieving domain for blimp: ' + domain_req_url) r = requests.get(domain_req_url, headers={'X-AUTH-OTP': otp}) if r.status_code == 200: print('Success: %s' % r.text) result_dict = r.json() if "domain" in result_dict: with open(domain_txt_path, 'w') as domain_txt_file: domain_txt_file.write(result_dict['domain']) quit(0) else: quit(1) else: print('Error: %s. Is the OTP correct? Double-check on Spire!' % r.text) quit(1)
Clarify error if otp is wrong
Clarify error if otp is wrong
Python
agpl-3.0
cloudfleet/blimp-engineroom,cloudfleet/blimp-engineroom
#!/usr/bin/python """An example demonstrating the client-side usage of the cretificate request API endpoint. """ import requests, sys, json otp = sys.argv[1] domain_req_url = 'https://spire.cloudfleet.io/api/v1/blimp/domain' domain_txt_path = '/opt/cloudfleet/data/config/domain.txt' print('retrieving domain for blimp: ' + domain_req_url) r = requests.get(domain_req_url, headers={'X-AUTH-OTP': otp}) if r.status_code == 200: print('Success: %s' % r.text) result_dict = r.json() if "domain" in result_dict: with open(domain_txt_path, 'w') as domain_txt_file: domain_txt_file.write(result_dict['domain']) quit(0) else: quit(1) else: print('Error: %s' % r.text) quit(1) Clarify error if otp is wrong
#!/usr/bin/python """An example demonstrating the client-side usage of the cretificate request API endpoint. """ import requests, sys, json otp = sys.argv[1] domain_req_url = 'https://spire.cloudfleet.io/api/v1/blimp/domain' domain_txt_path = '/opt/cloudfleet/data/config/domain.txt' print('retrieving domain for blimp: ' + domain_req_url) r = requests.get(domain_req_url, headers={'X-AUTH-OTP': otp}) if r.status_code == 200: print('Success: %s' % r.text) result_dict = r.json() if "domain" in result_dict: with open(domain_txt_path, 'w') as domain_txt_file: domain_txt_file.write(result_dict['domain']) quit(0) else: quit(1) else: print('Error: %s. Is the OTP correct? Double-check on Spire!' % r.text) quit(1)
<commit_before>#!/usr/bin/python """An example demonstrating the client-side usage of the cretificate request API endpoint. """ import requests, sys, json otp = sys.argv[1] domain_req_url = 'https://spire.cloudfleet.io/api/v1/blimp/domain' domain_txt_path = '/opt/cloudfleet/data/config/domain.txt' print('retrieving domain for blimp: ' + domain_req_url) r = requests.get(domain_req_url, headers={'X-AUTH-OTP': otp}) if r.status_code == 200: print('Success: %s' % r.text) result_dict = r.json() if "domain" in result_dict: with open(domain_txt_path, 'w') as domain_txt_file: domain_txt_file.write(result_dict['domain']) quit(0) else: quit(1) else: print('Error: %s' % r.text) quit(1) <commit_msg>Clarify error if otp is wrong<commit_after>
#!/usr/bin/python """An example demonstrating the client-side usage of the cretificate request API endpoint. """ import requests, sys, json otp = sys.argv[1] domain_req_url = 'https://spire.cloudfleet.io/api/v1/blimp/domain' domain_txt_path = '/opt/cloudfleet/data/config/domain.txt' print('retrieving domain for blimp: ' + domain_req_url) r = requests.get(domain_req_url, headers={'X-AUTH-OTP': otp}) if r.status_code == 200: print('Success: %s' % r.text) result_dict = r.json() if "domain" in result_dict: with open(domain_txt_path, 'w') as domain_txt_file: domain_txt_file.write(result_dict['domain']) quit(0) else: quit(1) else: print('Error: %s. Is the OTP correct? Double-check on Spire!' % r.text) quit(1)
#!/usr/bin/python """An example demonstrating the client-side usage of the cretificate request API endpoint. """ import requests, sys, json otp = sys.argv[1] domain_req_url = 'https://spire.cloudfleet.io/api/v1/blimp/domain' domain_txt_path = '/opt/cloudfleet/data/config/domain.txt' print('retrieving domain for blimp: ' + domain_req_url) r = requests.get(domain_req_url, headers={'X-AUTH-OTP': otp}) if r.status_code == 200: print('Success: %s' % r.text) result_dict = r.json() if "domain" in result_dict: with open(domain_txt_path, 'w') as domain_txt_file: domain_txt_file.write(result_dict['domain']) quit(0) else: quit(1) else: print('Error: %s' % r.text) quit(1) Clarify error if otp is wrong#!/usr/bin/python """An example demonstrating the client-side usage of the cretificate request API endpoint. """ import requests, sys, json otp = sys.argv[1] domain_req_url = 'https://spire.cloudfleet.io/api/v1/blimp/domain' domain_txt_path = '/opt/cloudfleet/data/config/domain.txt' print('retrieving domain for blimp: ' + domain_req_url) r = requests.get(domain_req_url, headers={'X-AUTH-OTP': otp}) if r.status_code == 200: print('Success: %s' % r.text) result_dict = r.json() if "domain" in result_dict: with open(domain_txt_path, 'w') as domain_txt_file: domain_txt_file.write(result_dict['domain']) quit(0) else: quit(1) else: print('Error: %s. Is the OTP correct? Double-check on Spire!' % r.text) quit(1)
<commit_before>#!/usr/bin/python """An example demonstrating the client-side usage of the cretificate request API endpoint. """ import requests, sys, json otp = sys.argv[1] domain_req_url = 'https://spire.cloudfleet.io/api/v1/blimp/domain' domain_txt_path = '/opt/cloudfleet/data/config/domain.txt' print('retrieving domain for blimp: ' + domain_req_url) r = requests.get(domain_req_url, headers={'X-AUTH-OTP': otp}) if r.status_code == 200: print('Success: %s' % r.text) result_dict = r.json() if "domain" in result_dict: with open(domain_txt_path, 'w') as domain_txt_file: domain_txt_file.write(result_dict['domain']) quit(0) else: quit(1) else: print('Error: %s' % r.text) quit(1) <commit_msg>Clarify error if otp is wrong<commit_after>#!/usr/bin/python """An example demonstrating the client-side usage of the cretificate request API endpoint. """ import requests, sys, json otp = sys.argv[1] domain_req_url = 'https://spire.cloudfleet.io/api/v1/blimp/domain' domain_txt_path = '/opt/cloudfleet/data/config/domain.txt' print('retrieving domain for blimp: ' + domain_req_url) r = requests.get(domain_req_url, headers={'X-AUTH-OTP': otp}) if r.status_code == 200: print('Success: %s' % r.text) result_dict = r.json() if "domain" in result_dict: with open(domain_txt_path, 'w') as domain_txt_file: domain_txt_file.write(result_dict['domain']) quit(0) else: quit(1) else: print('Error: %s. Is the OTP correct? Double-check on Spire!' % r.text) quit(1)
600992d9bb3f357bdef8769a61b4829be8952573
blazar/api/context.py
blazar/api/context.py
# Copyright (c) 2013 Mirantis Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. from oslo_serialization import jsonutils import six from blazar import context from blazar import exceptions def ctx_from_headers(headers): try: service_catalog = jsonutils.loads(headers['X-Service-Catalog']) except KeyError: raise exceptions.ServiceCatalogNotFound() except TypeError: raise exceptions.WrongFormat() return context.BlazarContext( user_id=headers['X-User-Id'], project_id=headers['X-Project-Id'], auth_token=headers['X-Auth-Token'], service_catalog=service_catalog, user_name=headers['X-User-Name'], project_name=headers['X-Project-Name'], roles=map(six.text_type.strip, headers['X-Roles'].split(',')), )
# Copyright (c) 2013 Mirantis Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. from oslo_serialization import jsonutils import six from blazar import context from blazar import exceptions def ctx_from_headers(headers): try: service_catalog = jsonutils.loads(headers['X-Service-Catalog']) except KeyError: raise exceptions.ServiceCatalogNotFound() except TypeError: raise exceptions.WrongFormat() return context.BlazarContext( user_id=headers['X-User-Id'], project_id=headers['X-Project-Id'], auth_token=headers['X-Auth-Token'], service_catalog=service_catalog, user_name=headers['X-User-Name'], project_name=headers['X-Project-Name'], roles=list(map(six.text_type.strip, headers['X-Roles'].split(','))), )
Fix map issues with Python3
Fix map issues with Python3 Partially implements: blueprint python-3 Change-Id: Ia7dfc2a28c311a378ca5ada477d18a5b741782b2
Python
apache-2.0
stackforge/blazar,openstack/blazar,ChameleonCloud/blazar,ChameleonCloud/blazar,stackforge/blazar,openstack/blazar
# Copyright (c) 2013 Mirantis Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. from oslo_serialization import jsonutils import six from blazar import context from blazar import exceptions def ctx_from_headers(headers): try: service_catalog = jsonutils.loads(headers['X-Service-Catalog']) except KeyError: raise exceptions.ServiceCatalogNotFound() except TypeError: raise exceptions.WrongFormat() return context.BlazarContext( user_id=headers['X-User-Id'], project_id=headers['X-Project-Id'], auth_token=headers['X-Auth-Token'], service_catalog=service_catalog, user_name=headers['X-User-Name'], project_name=headers['X-Project-Name'], roles=map(six.text_type.strip, headers['X-Roles'].split(',')), ) Fix map issues with Python3 Partially implements: blueprint python-3 Change-Id: Ia7dfc2a28c311a378ca5ada477d18a5b741782b2
# Copyright (c) 2013 Mirantis Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. from oslo_serialization import jsonutils import six from blazar import context from blazar import exceptions def ctx_from_headers(headers): try: service_catalog = jsonutils.loads(headers['X-Service-Catalog']) except KeyError: raise exceptions.ServiceCatalogNotFound() except TypeError: raise exceptions.WrongFormat() return context.BlazarContext( user_id=headers['X-User-Id'], project_id=headers['X-Project-Id'], auth_token=headers['X-Auth-Token'], service_catalog=service_catalog, user_name=headers['X-User-Name'], project_name=headers['X-Project-Name'], roles=list(map(six.text_type.strip, headers['X-Roles'].split(','))), )
<commit_before># Copyright (c) 2013 Mirantis Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. from oslo_serialization import jsonutils import six from blazar import context from blazar import exceptions def ctx_from_headers(headers): try: service_catalog = jsonutils.loads(headers['X-Service-Catalog']) except KeyError: raise exceptions.ServiceCatalogNotFound() except TypeError: raise exceptions.WrongFormat() return context.BlazarContext( user_id=headers['X-User-Id'], project_id=headers['X-Project-Id'], auth_token=headers['X-Auth-Token'], service_catalog=service_catalog, user_name=headers['X-User-Name'], project_name=headers['X-Project-Name'], roles=map(six.text_type.strip, headers['X-Roles'].split(',')), ) <commit_msg>Fix map issues with Python3 Partially implements: blueprint python-3 Change-Id: Ia7dfc2a28c311a378ca5ada477d18a5b741782b2<commit_after>
# Copyright (c) 2013 Mirantis Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. from oslo_serialization import jsonutils import six from blazar import context from blazar import exceptions def ctx_from_headers(headers): try: service_catalog = jsonutils.loads(headers['X-Service-Catalog']) except KeyError: raise exceptions.ServiceCatalogNotFound() except TypeError: raise exceptions.WrongFormat() return context.BlazarContext( user_id=headers['X-User-Id'], project_id=headers['X-Project-Id'], auth_token=headers['X-Auth-Token'], service_catalog=service_catalog, user_name=headers['X-User-Name'], project_name=headers['X-Project-Name'], roles=list(map(six.text_type.strip, headers['X-Roles'].split(','))), )
# Copyright (c) 2013 Mirantis Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. from oslo_serialization import jsonutils import six from blazar import context from blazar import exceptions def ctx_from_headers(headers): try: service_catalog = jsonutils.loads(headers['X-Service-Catalog']) except KeyError: raise exceptions.ServiceCatalogNotFound() except TypeError: raise exceptions.WrongFormat() return context.BlazarContext( user_id=headers['X-User-Id'], project_id=headers['X-Project-Id'], auth_token=headers['X-Auth-Token'], service_catalog=service_catalog, user_name=headers['X-User-Name'], project_name=headers['X-Project-Name'], roles=map(six.text_type.strip, headers['X-Roles'].split(',')), ) Fix map issues with Python3 Partially implements: blueprint python-3 Change-Id: Ia7dfc2a28c311a378ca5ada477d18a5b741782b2# Copyright (c) 2013 Mirantis Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. from oslo_serialization import jsonutils import six from blazar import context from blazar import exceptions def ctx_from_headers(headers): try: service_catalog = jsonutils.loads(headers['X-Service-Catalog']) except KeyError: raise exceptions.ServiceCatalogNotFound() except TypeError: raise exceptions.WrongFormat() return context.BlazarContext( user_id=headers['X-User-Id'], project_id=headers['X-Project-Id'], auth_token=headers['X-Auth-Token'], service_catalog=service_catalog, user_name=headers['X-User-Name'], project_name=headers['X-Project-Name'], roles=list(map(six.text_type.strip, headers['X-Roles'].split(','))), )
<commit_before># Copyright (c) 2013 Mirantis Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. from oslo_serialization import jsonutils import six from blazar import context from blazar import exceptions def ctx_from_headers(headers): try: service_catalog = jsonutils.loads(headers['X-Service-Catalog']) except KeyError: raise exceptions.ServiceCatalogNotFound() except TypeError: raise exceptions.WrongFormat() return context.BlazarContext( user_id=headers['X-User-Id'], project_id=headers['X-Project-Id'], auth_token=headers['X-Auth-Token'], service_catalog=service_catalog, user_name=headers['X-User-Name'], project_name=headers['X-Project-Name'], roles=map(six.text_type.strip, headers['X-Roles'].split(',')), ) <commit_msg>Fix map issues with Python3 Partially implements: blueprint python-3 Change-Id: Ia7dfc2a28c311a378ca5ada477d18a5b741782b2<commit_after># Copyright (c) 2013 Mirantis Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. from oslo_serialization import jsonutils import six from blazar import context from blazar import exceptions def ctx_from_headers(headers): try: service_catalog = jsonutils.loads(headers['X-Service-Catalog']) except KeyError: raise exceptions.ServiceCatalogNotFound() except TypeError: raise exceptions.WrongFormat() return context.BlazarContext( user_id=headers['X-User-Id'], project_id=headers['X-Project-Id'], auth_token=headers['X-Auth-Token'], service_catalog=service_catalog, user_name=headers['X-User-Name'], project_name=headers['X-Project-Name'], roles=list(map(six.text_type.strip, headers['X-Roles'].split(','))), )
4943d9a7d6ed77d10c3185054c9c74846c89a450
bugimporters/items.py
bugimporters/items.py
import scrapy.item class ParsedBug(scrapy.item.Item): # Fields beginning with an underscore are not really part of a # bug, but extra information that can be exported. _project_name = scrapy.item.Field() # These fields correspond to bug data title = scrapy.item.Field() description = scrapy.item.Field() status = scrapy.item.Field() importance = scrapy.item.Field() people_involved = scrapy.item.Field() date_reported = scrapy.item.Field() last_touched = scrapy.item.Field() submitter_username = scrapy.item.Field() submitter_realname = scrapy.item.Field() canonical_bug_link = scrapy.item.Field() looks_closed = scrapy.item.Field() last_polled = scrapy.item.Field() as_appears_in_distribution = scrapy.item.Field() good_for_newcomers = scrapy.item.Field() concerns_just_documentation = scrapy.item.Field() tracker = scrapy.item.Field()
import scrapy.item class ParsedBug(scrapy.item.Item): # Fields beginning with an underscore are not really part of a # bug, but extra information that can be exported. _project_name = scrapy.item.Field() _tracker_name = scrapy.item.Field() # These fields correspond to bug data title = scrapy.item.Field() description = scrapy.item.Field() status = scrapy.item.Field() importance = scrapy.item.Field() people_involved = scrapy.item.Field() date_reported = scrapy.item.Field() last_touched = scrapy.item.Field() submitter_username = scrapy.item.Field() submitter_realname = scrapy.item.Field() canonical_bug_link = scrapy.item.Field() looks_closed = scrapy.item.Field() last_polled = scrapy.item.Field() as_appears_in_distribution = scrapy.item.Field() good_for_newcomers = scrapy.item.Field() concerns_just_documentation = scrapy.item.Field()
Remove tracker field from ParsedBug. Add _tracker_name
Remove tracker field from ParsedBug. Add _tracker_name
Python
agpl-3.0
openhatch/oh-bugimporters,openhatch/oh-bugimporters,openhatch/oh-bugimporters
import scrapy.item class ParsedBug(scrapy.item.Item): # Fields beginning with an underscore are not really part of a # bug, but extra information that can be exported. _project_name = scrapy.item.Field() # These fields correspond to bug data title = scrapy.item.Field() description = scrapy.item.Field() status = scrapy.item.Field() importance = scrapy.item.Field() people_involved = scrapy.item.Field() date_reported = scrapy.item.Field() last_touched = scrapy.item.Field() submitter_username = scrapy.item.Field() submitter_realname = scrapy.item.Field() canonical_bug_link = scrapy.item.Field() looks_closed = scrapy.item.Field() last_polled = scrapy.item.Field() as_appears_in_distribution = scrapy.item.Field() good_for_newcomers = scrapy.item.Field() concerns_just_documentation = scrapy.item.Field() tracker = scrapy.item.Field() Remove tracker field from ParsedBug. Add _tracker_name
import scrapy.item class ParsedBug(scrapy.item.Item): # Fields beginning with an underscore are not really part of a # bug, but extra information that can be exported. _project_name = scrapy.item.Field() _tracker_name = scrapy.item.Field() # These fields correspond to bug data title = scrapy.item.Field() description = scrapy.item.Field() status = scrapy.item.Field() importance = scrapy.item.Field() people_involved = scrapy.item.Field() date_reported = scrapy.item.Field() last_touched = scrapy.item.Field() submitter_username = scrapy.item.Field() submitter_realname = scrapy.item.Field() canonical_bug_link = scrapy.item.Field() looks_closed = scrapy.item.Field() last_polled = scrapy.item.Field() as_appears_in_distribution = scrapy.item.Field() good_for_newcomers = scrapy.item.Field() concerns_just_documentation = scrapy.item.Field()
<commit_before>import scrapy.item class ParsedBug(scrapy.item.Item): # Fields beginning with an underscore are not really part of a # bug, but extra information that can be exported. _project_name = scrapy.item.Field() # These fields correspond to bug data title = scrapy.item.Field() description = scrapy.item.Field() status = scrapy.item.Field() importance = scrapy.item.Field() people_involved = scrapy.item.Field() date_reported = scrapy.item.Field() last_touched = scrapy.item.Field() submitter_username = scrapy.item.Field() submitter_realname = scrapy.item.Field() canonical_bug_link = scrapy.item.Field() looks_closed = scrapy.item.Field() last_polled = scrapy.item.Field() as_appears_in_distribution = scrapy.item.Field() good_for_newcomers = scrapy.item.Field() concerns_just_documentation = scrapy.item.Field() tracker = scrapy.item.Field() <commit_msg>Remove tracker field from ParsedBug. Add _tracker_name<commit_after>
import scrapy.item class ParsedBug(scrapy.item.Item): # Fields beginning with an underscore are not really part of a # bug, but extra information that can be exported. _project_name = scrapy.item.Field() _tracker_name = scrapy.item.Field() # These fields correspond to bug data title = scrapy.item.Field() description = scrapy.item.Field() status = scrapy.item.Field() importance = scrapy.item.Field() people_involved = scrapy.item.Field() date_reported = scrapy.item.Field() last_touched = scrapy.item.Field() submitter_username = scrapy.item.Field() submitter_realname = scrapy.item.Field() canonical_bug_link = scrapy.item.Field() looks_closed = scrapy.item.Field() last_polled = scrapy.item.Field() as_appears_in_distribution = scrapy.item.Field() good_for_newcomers = scrapy.item.Field() concerns_just_documentation = scrapy.item.Field()
import scrapy.item class ParsedBug(scrapy.item.Item): # Fields beginning with an underscore are not really part of a # bug, but extra information that can be exported. _project_name = scrapy.item.Field() # These fields correspond to bug data title = scrapy.item.Field() description = scrapy.item.Field() status = scrapy.item.Field() importance = scrapy.item.Field() people_involved = scrapy.item.Field() date_reported = scrapy.item.Field() last_touched = scrapy.item.Field() submitter_username = scrapy.item.Field() submitter_realname = scrapy.item.Field() canonical_bug_link = scrapy.item.Field() looks_closed = scrapy.item.Field() last_polled = scrapy.item.Field() as_appears_in_distribution = scrapy.item.Field() good_for_newcomers = scrapy.item.Field() concerns_just_documentation = scrapy.item.Field() tracker = scrapy.item.Field() Remove tracker field from ParsedBug. Add _tracker_nameimport scrapy.item class ParsedBug(scrapy.item.Item): # Fields beginning with an underscore are not really part of a # bug, but extra information that can be exported. _project_name = scrapy.item.Field() _tracker_name = scrapy.item.Field() # These fields correspond to bug data title = scrapy.item.Field() description = scrapy.item.Field() status = scrapy.item.Field() importance = scrapy.item.Field() people_involved = scrapy.item.Field() date_reported = scrapy.item.Field() last_touched = scrapy.item.Field() submitter_username = scrapy.item.Field() submitter_realname = scrapy.item.Field() canonical_bug_link = scrapy.item.Field() looks_closed = scrapy.item.Field() last_polled = scrapy.item.Field() as_appears_in_distribution = scrapy.item.Field() good_for_newcomers = scrapy.item.Field() concerns_just_documentation = scrapy.item.Field()
<commit_before>import scrapy.item class ParsedBug(scrapy.item.Item): # Fields beginning with an underscore are not really part of a # bug, but extra information that can be exported. _project_name = scrapy.item.Field() # These fields correspond to bug data title = scrapy.item.Field() description = scrapy.item.Field() status = scrapy.item.Field() importance = scrapy.item.Field() people_involved = scrapy.item.Field() date_reported = scrapy.item.Field() last_touched = scrapy.item.Field() submitter_username = scrapy.item.Field() submitter_realname = scrapy.item.Field() canonical_bug_link = scrapy.item.Field() looks_closed = scrapy.item.Field() last_polled = scrapy.item.Field() as_appears_in_distribution = scrapy.item.Field() good_for_newcomers = scrapy.item.Field() concerns_just_documentation = scrapy.item.Field() tracker = scrapy.item.Field() <commit_msg>Remove tracker field from ParsedBug. Add _tracker_name<commit_after>import scrapy.item class ParsedBug(scrapy.item.Item): # Fields beginning with an underscore are not really part of a # bug, but extra information that can be exported. _project_name = scrapy.item.Field() _tracker_name = scrapy.item.Field() # These fields correspond to bug data title = scrapy.item.Field() description = scrapy.item.Field() status = scrapy.item.Field() importance = scrapy.item.Field() people_involved = scrapy.item.Field() date_reported = scrapy.item.Field() last_touched = scrapy.item.Field() submitter_username = scrapy.item.Field() submitter_realname = scrapy.item.Field() canonical_bug_link = scrapy.item.Field() looks_closed = scrapy.item.Field() last_polled = scrapy.item.Field() as_appears_in_distribution = scrapy.item.Field() good_for_newcomers = scrapy.item.Field() concerns_just_documentation = scrapy.item.Field()
079ab75cc316c994bb3f63d32fa633aeebf08d87
grid/views.py
grid/views.py
from django.core import serializers from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseForbidden from django.shortcuts import get_object_or_404, redirect, render_to_response from django.template import RequestContext from django.template.loader import get_template import json from models import Game, Week def index(request): ben_teams = [] brian_teams = [] wk = Week.objects.latest() for game in wk.game_set.all(): picked = game.picked_team other = game.away_team if game.home_team == picked else game.home_team if game.picker == "BEN": ben_teams.append(picked) brian_teams.append(other) else: brian_teams.append(picked) ben_teams.append(other) interval = 1 * 60 * 1000 return render_to_response('grid/index.html', {'ben_teams': json.dumps(ben_teams), 'brian_teams': json.dumps(brian_teams), 'interval': interval }, context_instance=RequestContext(request)) def scores(request): wk = Week.objects.latest() games = wk.game_set.all() ret = serializers.serialize('json', games) return HttpResponse(ret, "application/javascript")
from django.core import serializers from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseForbidden from django.shortcuts import get_object_or_404, redirect, render_to_response from django.template import RequestContext from django.template.loader import get_template import json from models import Game, Week def index(request): ben_teams = [] brian_teams = [] wk = Week.objects.latest() for game in wk.game_set.all(): picked = game.picked_team other = game.away_team if game.home_team == picked else game.home_team if game.picker == "BEN": ben_teams.append(picked) brian_teams.append(other) else: brian_teams.append(picked) ben_teams.append(other) interval = 1 * 20 * 1000 return render_to_response('grid/index.html', {'ben_teams': json.dumps(ben_teams), 'brian_teams': json.dumps(brian_teams), 'interval': interval }, context_instance=RequestContext(request)) def scores(request): wk = Week.objects.latest() games = wk.game_set.all() ret = serializers.serialize('json', games) return HttpResponse(ret, "application/javascript")
Refresh the grid every 20 seconds.
Refresh the grid every 20 seconds.
Python
mit
bschmeck/gnarl,bschmeck/gnarl,bschmeck/gnarl
from django.core import serializers from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseForbidden from django.shortcuts import get_object_or_404, redirect, render_to_response from django.template import RequestContext from django.template.loader import get_template import json from models import Game, Week def index(request): ben_teams = [] brian_teams = [] wk = Week.objects.latest() for game in wk.game_set.all(): picked = game.picked_team other = game.away_team if game.home_team == picked else game.home_team if game.picker == "BEN": ben_teams.append(picked) brian_teams.append(other) else: brian_teams.append(picked) ben_teams.append(other) interval = 1 * 60 * 1000 return render_to_response('grid/index.html', {'ben_teams': json.dumps(ben_teams), 'brian_teams': json.dumps(brian_teams), 'interval': interval }, context_instance=RequestContext(request)) def scores(request): wk = Week.objects.latest() games = wk.game_set.all() ret = serializers.serialize('json', games) return HttpResponse(ret, "application/javascript") Refresh the grid every 20 seconds.
from django.core import serializers from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseForbidden from django.shortcuts import get_object_or_404, redirect, render_to_response from django.template import RequestContext from django.template.loader import get_template import json from models import Game, Week def index(request): ben_teams = [] brian_teams = [] wk = Week.objects.latest() for game in wk.game_set.all(): picked = game.picked_team other = game.away_team if game.home_team == picked else game.home_team if game.picker == "BEN": ben_teams.append(picked) brian_teams.append(other) else: brian_teams.append(picked) ben_teams.append(other) interval = 1 * 20 * 1000 return render_to_response('grid/index.html', {'ben_teams': json.dumps(ben_teams), 'brian_teams': json.dumps(brian_teams), 'interval': interval }, context_instance=RequestContext(request)) def scores(request): wk = Week.objects.latest() games = wk.game_set.all() ret = serializers.serialize('json', games) return HttpResponse(ret, "application/javascript")
<commit_before>from django.core import serializers from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseForbidden from django.shortcuts import get_object_or_404, redirect, render_to_response from django.template import RequestContext from django.template.loader import get_template import json from models import Game, Week def index(request): ben_teams = [] brian_teams = [] wk = Week.objects.latest() for game in wk.game_set.all(): picked = game.picked_team other = game.away_team if game.home_team == picked else game.home_team if game.picker == "BEN": ben_teams.append(picked) brian_teams.append(other) else: brian_teams.append(picked) ben_teams.append(other) interval = 1 * 60 * 1000 return render_to_response('grid/index.html', {'ben_teams': json.dumps(ben_teams), 'brian_teams': json.dumps(brian_teams), 'interval': interval }, context_instance=RequestContext(request)) def scores(request): wk = Week.objects.latest() games = wk.game_set.all() ret = serializers.serialize('json', games) return HttpResponse(ret, "application/javascript") <commit_msg>Refresh the grid every 20 seconds.<commit_after>
from django.core import serializers from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseForbidden from django.shortcuts import get_object_or_404, redirect, render_to_response from django.template import RequestContext from django.template.loader import get_template import json from models import Game, Week def index(request): ben_teams = [] brian_teams = [] wk = Week.objects.latest() for game in wk.game_set.all(): picked = game.picked_team other = game.away_team if game.home_team == picked else game.home_team if game.picker == "BEN": ben_teams.append(picked) brian_teams.append(other) else: brian_teams.append(picked) ben_teams.append(other) interval = 1 * 20 * 1000 return render_to_response('grid/index.html', {'ben_teams': json.dumps(ben_teams), 'brian_teams': json.dumps(brian_teams), 'interval': interval }, context_instance=RequestContext(request)) def scores(request): wk = Week.objects.latest() games = wk.game_set.all() ret = serializers.serialize('json', games) return HttpResponse(ret, "application/javascript")
from django.core import serializers from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseForbidden from django.shortcuts import get_object_or_404, redirect, render_to_response from django.template import RequestContext from django.template.loader import get_template import json from models import Game, Week def index(request): ben_teams = [] brian_teams = [] wk = Week.objects.latest() for game in wk.game_set.all(): picked = game.picked_team other = game.away_team if game.home_team == picked else game.home_team if game.picker == "BEN": ben_teams.append(picked) brian_teams.append(other) else: brian_teams.append(picked) ben_teams.append(other) interval = 1 * 60 * 1000 return render_to_response('grid/index.html', {'ben_teams': json.dumps(ben_teams), 'brian_teams': json.dumps(brian_teams), 'interval': interval }, context_instance=RequestContext(request)) def scores(request): wk = Week.objects.latest() games = wk.game_set.all() ret = serializers.serialize('json', games) return HttpResponse(ret, "application/javascript") Refresh the grid every 20 seconds.from django.core import serializers from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseForbidden from django.shortcuts import get_object_or_404, redirect, render_to_response from django.template import RequestContext from django.template.loader import get_template import json from models import Game, Week def index(request): ben_teams = [] brian_teams = [] wk = Week.objects.latest() for game in wk.game_set.all(): picked = game.picked_team other = game.away_team if game.home_team == picked else game.home_team if game.picker == "BEN": ben_teams.append(picked) brian_teams.append(other) else: brian_teams.append(picked) ben_teams.append(other) interval = 1 * 20 * 1000 return render_to_response('grid/index.html', {'ben_teams': json.dumps(ben_teams), 'brian_teams': json.dumps(brian_teams), 'interval': interval }, context_instance=RequestContext(request)) def scores(request): wk = Week.objects.latest() games = wk.game_set.all() ret = serializers.serialize('json', games) return HttpResponse(ret, "application/javascript")
<commit_before>from django.core import serializers from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseForbidden from django.shortcuts import get_object_or_404, redirect, render_to_response from django.template import RequestContext from django.template.loader import get_template import json from models import Game, Week def index(request): ben_teams = [] brian_teams = [] wk = Week.objects.latest() for game in wk.game_set.all(): picked = game.picked_team other = game.away_team if game.home_team == picked else game.home_team if game.picker == "BEN": ben_teams.append(picked) brian_teams.append(other) else: brian_teams.append(picked) ben_teams.append(other) interval = 1 * 60 * 1000 return render_to_response('grid/index.html', {'ben_teams': json.dumps(ben_teams), 'brian_teams': json.dumps(brian_teams), 'interval': interval }, context_instance=RequestContext(request)) def scores(request): wk = Week.objects.latest() games = wk.game_set.all() ret = serializers.serialize('json', games) return HttpResponse(ret, "application/javascript") <commit_msg>Refresh the grid every 20 seconds.<commit_after>from django.core import serializers from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseForbidden from django.shortcuts import get_object_or_404, redirect, render_to_response from django.template import RequestContext from django.template.loader import get_template import json from models import Game, Week def index(request): ben_teams = [] brian_teams = [] wk = Week.objects.latest() for game in wk.game_set.all(): picked = game.picked_team other = game.away_team if game.home_team == picked else game.home_team if game.picker == "BEN": ben_teams.append(picked) brian_teams.append(other) else: brian_teams.append(picked) ben_teams.append(other) interval = 1 * 20 * 1000 return render_to_response('grid/index.html', {'ben_teams': json.dumps(ben_teams), 'brian_teams': json.dumps(brian_teams), 'interval': interval }, context_instance=RequestContext(request)) def scores(request): wk = Week.objects.latest() games = wk.game_set.all() ret = serializers.serialize('json', games) return HttpResponse(ret, "application/javascript")
970eb92f6db8b2fd22594d662a7142a976d60559
airflow/contrib/hooks/__init__.py
airflow/contrib/hooks/__init__.py
# Imports the hooks dynamically while keeping the package API clean, # abstracting the underlying modules from airflow.utils import import_module_attrs as _import_module_attrs _hooks = { 'ftp_hook': ['FTPHook'], 'vertica_hook': ['VerticaHook'], 'ssh_hook': ['SSHHook'], 'bigquery_hook': ['BigQueryHook'], 'qubole_hook': ['QuboleHook'] } _import_module_attrs(globals(), _hooks)
# Imports the hooks dynamically while keeping the package API clean, # abstracting the underlying modules from airflow.utils import import_module_attrs as _import_module_attrs _hooks = { 'ftp_hook': ['FTPHook'], 'ftps_hook': ['FTPSHook'], 'vertica_hook': ['VerticaHook'], 'ssh_hook': ['SSHHook'], 'bigquery_hook': ['BigQueryHook'], 'qubole_hook': ['QuboleHook'] } _import_module_attrs(globals(), _hooks)
Add FTPSHook in _hooks register.
Add FTPSHook in _hooks register.
Python
apache-2.0
cjqian/incubator-airflow,KL-WLCR/incubator-airflow,dmitry-r/incubator-airflow,yiqingj/airflow,rishibarve/incubator-airflow,vineet-rh/incubator-airflow,ty707/airflow,preete-dixit-ck/incubator-airflow,saguziel/incubator-airflow,sdiazb/airflow,NielsZeilemaker/incubator-airflow,subodhchhabra/airflow,yiqingj/airflow,preete-dixit-ck/incubator-airflow,adamhaney/airflow,aminghadersohi/airflow,mtagle/airflow,adrpar/incubator-airflow,jhsenjaliya/incubator-airflow,cfei18/incubator-airflow,criccomini/airflow,subodhchhabra/airflow,caseyching/incubator-airflow,juvoinc/airflow,airbnb/airflow,dmitry-r/incubator-airflow,hamedhsn/incubator-airflow,apache/airflow,fenglu-g/incubator-airflow,Fokko/incubator-airflow,KL-WLCR/incubator-airflow,andrewmchen/incubator-airflow,forevernull/incubator-airflow,cademarkegard/airflow,jwi078/incubator-airflow,jiwang576/incubator-airflow,btallman/incubator-airflow,zack3241/incubator-airflow,DinoCow/airflow,biln/airflow,caseyching/incubator-airflow,Fokko/incubator-airflow,DEVELByte/incubator-airflow,airbnb/airflow,alexvanboxel/airflow,apache/incubator-airflow,vijaysbhat/incubator-airflow,gritlogic/incubator-airflow,gtoonstra/airflow,forevernull/incubator-airflow,btallman/incubator-airflow,zodiac/incubator-airflow,malmiron/incubator-airflow,ty707/airflow,cademarkegard/airflow,preete-dixit-ck/incubator-airflow,sergiohgz/incubator-airflow,cademarkegard/airflow,wndhydrnt/airflow,mtdewulf/incubator-airflow,yiqingj/airflow,opensignal/airflow,vijaysbhat/incubator-airflow,MetrodataTeam/incubator-airflow,apache/airflow,mattuuh7/incubator-airflow,holygits/incubator-airflow,edgarRd/incubator-airflow,lxneng/incubator-airflow,plypaul/airflow,sid88in/incubator-airflow,yati-sagade/incubator-airflow,adrpar/incubator-airflow,cjqian/incubator-airflow,hamedhsn/incubator-airflow,skudriashev/incubator-airflow,artwr/airflow,jwi078/incubator-airflow,stverhae/incubator-airflow,owlabs/incubator-airflow,ronfung/incubator-airflow,lyft/incubator-airflow,zack3241/incubator-airflow,hgrif/incubator-airflow,RealImpactAnalytics/airflow,dgies/incubator-airflow,ty707/airflow,ProstoMaxim/incubator-airflow,aminghadersohi/airflow,jbhsieh/incubator-airflow,rishibarve/incubator-airflow,jbhsieh/incubator-airflow,r39132/airflow,jgao54/airflow,forevernull/incubator-airflow,jlowin/airflow,jlowin/airflow,holygits/incubator-airflow,DEVELByte/incubator-airflow,mtdewulf/incubator-airflow,biln/airflow,fenglu-g/incubator-airflow,mylons/incubator-airflow,ledsusop/airflow,zoyahav/incubator-airflow,CloverHealth/airflow,dud225/incubator-airflow,jfantom/incubator-airflow,dgies/incubator-airflow,sekikn/incubator-airflow,lyft/incubator-airflow,saguziel/incubator-airflow,mattuuh7/incubator-airflow,gtoonstra/airflow,vineet-rh/incubator-airflow,yk5/incubator-airflow,aminghadersohi/airflow,wileeam/airflow,jfantom/incubator-airflow,mistercrunch/airflow,easytaxibr/airflow,Twistbioscience/incubator-airflow,zodiac/incubator-airflow,hgrif/incubator-airflow,lxneng/incubator-airflow,Acehaidrey/incubator-airflow,mattuuh7/incubator-airflow,wxiang7/airflow,gilt/incubator-airflow,mrkm4ntr/incubator-airflow,zack3241/incubator-airflow,Acehaidrey/incubator-airflow,owlabs/incubator-airflow,yati-sagade/incubator-airflow,kerzhner/airflow,mrkm4ntr/incubator-airflow,andyxhadji/incubator-airflow,sergiohgz/incubator-airflow,DinoCow/airflow,edgarRd/incubator-airflow,skudriashev/incubator-airflow,jhsenjaliya/incubator-airflow,dhuang/incubator-airflow,dgies/incubator-airflow,adrpar/incubator-airflow,AllisonWang/incubator-airflow,NielsZeilemaker/incubator-airflow,danielvdende/incubator-airflow,rishibarve/incubator-airflow,wxiang7/airflow,jiwang576/incubator-airflow,sdiazb/airflow,brandsoulmates/incubator-airflow,mrares/incubator-airflow,jhsenjaliya/incubator-airflow,jesusfcr/airflow,criccomini/airflow,wooga/airflow,OpringaoDoTurno/airflow,yati-sagade/incubator-airflow,ty707/airflow,OpringaoDoTurno/airflow,apache/incubator-airflow,ProstoMaxim/incubator-airflow,sid88in/incubator-airflow,nathanielvarona/airflow,janczak10/incubator-airflow,yati-sagade/incubator-airflow,ledsusop/airflow,plypaul/airflow,jhsenjaliya/incubator-airflow,brandsoulmates/incubator-airflow,RealImpactAnalytics/airflow,wileeam/airflow,gilt/incubator-airflow,wileeam/airflow,wolfier/incubator-airflow,wooga/airflow,Tagar/incubator-airflow,RealImpactAnalytics/airflow,owlabs/incubator-airflow,AllisonWang/incubator-airflow,jwi078/incubator-airflow,nathanielvarona/airflow,KL-WLCR/incubator-airflow,MetrodataTeam/incubator-airflow,r39132/airflow,dgies/incubator-airflow,danielvdende/incubator-airflow,jesusfcr/airflow,forevernull/incubator-airflow,nathanielvarona/airflow,MortalViews/incubator-airflow,plypaul/airflow,easytaxibr/airflow,gilt/incubator-airflow,edgarRd/incubator-airflow,OpringaoDoTurno/airflow,mrares/incubator-airflow,modsy/incubator-airflow,akosel/incubator-airflow,adamhaney/airflow,holygits/incubator-airflow,RealImpactAnalytics/airflow,mistercrunch/airflow,gritlogic/incubator-airflow,gritlogic/incubator-airflow,mtagle/airflow,jgao54/airflow,skudriashev/incubator-airflow,janczak10/incubator-airflow,danielvdende/incubator-airflow,cfei18/incubator-airflow,kerzhner/airflow,Acehaidrey/incubator-airflow,mtagle/airflow,Tagar/incubator-airflow,juvoinc/airflow,hgrif/incubator-airflow,yk5/incubator-airflow,jwi078/incubator-airflow,opensignal/airflow,DinoCow/airflow,fenglu-g/incubator-airflow,AllisonWang/incubator-airflow,wndhydrnt/airflow,d-lee/airflow,malmiron/incubator-airflow,jiwang576/incubator-airflow,mattuuh7/incubator-airflow,dud225/incubator-airflow,mistercrunch/airflow,cjqian/incubator-airflow,subodhchhabra/airflow,DinoCow/airflow,mylons/incubator-airflow,adamhaney/airflow,cfei18/incubator-airflow,opensignal/airflow,andyxhadji/incubator-airflow,ronfung/incubator-airflow,stverhae/incubator-airflow,ProstoMaxim/incubator-airflow,sdiazb/airflow,gtoonstra/airflow,jesusfcr/airflow,MortalViews/incubator-airflow,DEVELByte/incubator-airflow,kerzhner/airflow,lxneng/incubator-airflow,AllisonWang/incubator-airflow,fenglu-g/incubator-airflow,jesusfcr/airflow,biln/airflow,nathanielvarona/airflow,opensignal/airflow,jgao54/airflow,wxiang7/airflow,btallman/incubator-airflow,vineet-rh/incubator-airflow,jgao54/airflow,andyxhadji/incubator-airflow,alexvanboxel/airflow,malmiron/incubator-airflow,ronfung/incubator-airflow,janczak10/incubator-airflow,zodiac/incubator-airflow,akosel/incubator-airflow,juvoinc/airflow,danielvdende/incubator-airflow,wndhydrnt/airflow,edgarRd/incubator-airflow,Twistbioscience/incubator-airflow,gilt/incubator-airflow,cjqian/incubator-airflow,juvoinc/airflow,vijaysbhat/incubator-airflow,apache/incubator-airflow,KL-WLCR/incubator-airflow,Fokko/incubator-airflow,subodhchhabra/airflow,artwr/airflow,dhuang/incubator-airflow,aminghadersohi/airflow,nathanielvarona/airflow,OpringaoDoTurno/airflow,zoyahav/incubator-airflow,sid88in/incubator-airflow,wolfier/incubator-airflow,cfei18/incubator-airflow,jiwang576/incubator-airflow,wooga/airflow,dhuang/incubator-airflow,CloverHealth/airflow,N3da/incubator-airflow,dhuang/incubator-airflow,jlowin/airflow,DEVELByte/incubator-airflow,MetrodataTeam/incubator-airflow,wolfier/incubator-airflow,zodiac/incubator-airflow,sekikn/incubator-airflow,mrares/incubator-airflow,d-lee/airflow,spektom/incubator-airflow,lyft/incubator-airflow,andrewmchen/incubator-airflow,apache/airflow,lxneng/incubator-airflow,bolkedebruin/airflow,biln/airflow,r39132/airflow,saguziel/incubator-airflow,mtdewulf/incubator-airflow,bolkedebruin/airflow,wileeam/airflow,mrares/incubator-airflow,ledsusop/airflow,spektom/incubator-airflow,alexvanboxel/airflow,Acehaidrey/incubator-airflow,dud225/incubator-airflow,asnir/airflow,skudriashev/incubator-airflow,janczak10/incubator-airflow,gritlogic/incubator-airflow,Tagar/incubator-airflow,modsy/incubator-airflow,nathanielvarona/airflow,ronfung/incubator-airflow,caseyching/incubator-airflow,brandsoulmates/incubator-airflow,Acehaidrey/incubator-airflow,criccomini/airflow,easytaxibr/airflow,caseyching/incubator-airflow,criccomini/airflow,cfei18/incubator-airflow,N3da/incubator-airflow,lyft/incubator-airflow,hgrif/incubator-airflow,adrpar/incubator-airflow,akosel/incubator-airflow,jfantom/incubator-airflow,spektom/incubator-airflow,sergiohgz/incubator-airflow,owlabs/incubator-airflow,MetrodataTeam/incubator-airflow,sekikn/incubator-airflow,mrkm4ntr/incubator-airflow,d-lee/airflow,andyxhadji/incubator-airflow,mtagle/airflow,vijaysbhat/incubator-airflow,adamhaney/airflow,r39132/airflow,dud225/incubator-airflow,Twistbioscience/incubator-airflow,zack3241/incubator-airflow,modsy/incubator-airflow,Twistbioscience/incubator-airflow,NielsZeilemaker/incubator-airflow,Tagar/incubator-airflow,jfantom/incubator-airflow,sid88in/incubator-airflow,mistercrunch/airflow,wolfier/incubator-airflow,apache/airflow,mylons/incubator-airflow,spektom/incubator-airflow,MortalViews/incubator-airflow,CloverHealth/airflow,yk5/incubator-airflow,hamedhsn/incubator-airflow,andrewmchen/incubator-airflow,mrkm4ntr/incubator-airflow,wndhydrnt/airflow,asnir/airflow,danielvdende/incubator-airflow,dmitry-r/incubator-airflow,mylons/incubator-airflow,kerzhner/airflow,apache/incubator-airflow,cademarkegard/airflow,artwr/airflow,jlowin/airflow,CloverHealth/airflow,zoyahav/incubator-airflow,preete-dixit-ck/incubator-airflow,easytaxibr/airflow,malmiron/incubator-airflow,N3da/incubator-airflow,bolkedebruin/airflow,modsy/incubator-airflow,gtoonstra/airflow,dmitry-r/incubator-airflow,alexvanboxel/airflow,saguziel/incubator-airflow,jbhsieh/incubator-airflow,akosel/incubator-airflow,apache/airflow,brandsoulmates/incubator-airflow,N3da/incubator-airflow,wxiang7/airflow,Fokko/incubator-airflow,yk5/incubator-airflow,hamedhsn/incubator-airflow,rishibarve/incubator-airflow,bolkedebruin/airflow,d-lee/airflow,airbnb/airflow,vineet-rh/incubator-airflow,apache/airflow,plypaul/airflow,bolkedebruin/airflow,andrewmchen/incubator-airflow,mtdewulf/incubator-airflow,sdiazb/airflow,MortalViews/incubator-airflow,Acehaidrey/incubator-airflow,sekikn/incubator-airflow,NielsZeilemaker/incubator-airflow,asnir/airflow,wooga/airflow,ledsusop/airflow,artwr/airflow,danielvdende/incubator-airflow,btallman/incubator-airflow,asnir/airflow,airbnb/airflow,stverhae/incubator-airflow,cfei18/incubator-airflow,holygits/incubator-airflow,sergiohgz/incubator-airflow,zoyahav/incubator-airflow,jbhsieh/incubator-airflow,stverhae/incubator-airflow,yiqingj/airflow,ProstoMaxim/incubator-airflow
# Imports the hooks dynamically while keeping the package API clean, # abstracting the underlying modules from airflow.utils import import_module_attrs as _import_module_attrs _hooks = { 'ftp_hook': ['FTPHook'], 'vertica_hook': ['VerticaHook'], 'ssh_hook': ['SSHHook'], 'bigquery_hook': ['BigQueryHook'], 'qubole_hook': ['QuboleHook'] } _import_module_attrs(globals(), _hooks) Add FTPSHook in _hooks register.
# Imports the hooks dynamically while keeping the package API clean, # abstracting the underlying modules from airflow.utils import import_module_attrs as _import_module_attrs _hooks = { 'ftp_hook': ['FTPHook'], 'ftps_hook': ['FTPSHook'], 'vertica_hook': ['VerticaHook'], 'ssh_hook': ['SSHHook'], 'bigquery_hook': ['BigQueryHook'], 'qubole_hook': ['QuboleHook'] } _import_module_attrs(globals(), _hooks)
<commit_before># Imports the hooks dynamically while keeping the package API clean, # abstracting the underlying modules from airflow.utils import import_module_attrs as _import_module_attrs _hooks = { 'ftp_hook': ['FTPHook'], 'vertica_hook': ['VerticaHook'], 'ssh_hook': ['SSHHook'], 'bigquery_hook': ['BigQueryHook'], 'qubole_hook': ['QuboleHook'] } _import_module_attrs(globals(), _hooks) <commit_msg>Add FTPSHook in _hooks register.<commit_after>
# Imports the hooks dynamically while keeping the package API clean, # abstracting the underlying modules from airflow.utils import import_module_attrs as _import_module_attrs _hooks = { 'ftp_hook': ['FTPHook'], 'ftps_hook': ['FTPSHook'], 'vertica_hook': ['VerticaHook'], 'ssh_hook': ['SSHHook'], 'bigquery_hook': ['BigQueryHook'], 'qubole_hook': ['QuboleHook'] } _import_module_attrs(globals(), _hooks)
# Imports the hooks dynamically while keeping the package API clean, # abstracting the underlying modules from airflow.utils import import_module_attrs as _import_module_attrs _hooks = { 'ftp_hook': ['FTPHook'], 'vertica_hook': ['VerticaHook'], 'ssh_hook': ['SSHHook'], 'bigquery_hook': ['BigQueryHook'], 'qubole_hook': ['QuboleHook'] } _import_module_attrs(globals(), _hooks) Add FTPSHook in _hooks register.# Imports the hooks dynamically while keeping the package API clean, # abstracting the underlying modules from airflow.utils import import_module_attrs as _import_module_attrs _hooks = { 'ftp_hook': ['FTPHook'], 'ftps_hook': ['FTPSHook'], 'vertica_hook': ['VerticaHook'], 'ssh_hook': ['SSHHook'], 'bigquery_hook': ['BigQueryHook'], 'qubole_hook': ['QuboleHook'] } _import_module_attrs(globals(), _hooks)
<commit_before># Imports the hooks dynamically while keeping the package API clean, # abstracting the underlying modules from airflow.utils import import_module_attrs as _import_module_attrs _hooks = { 'ftp_hook': ['FTPHook'], 'vertica_hook': ['VerticaHook'], 'ssh_hook': ['SSHHook'], 'bigquery_hook': ['BigQueryHook'], 'qubole_hook': ['QuboleHook'] } _import_module_attrs(globals(), _hooks) <commit_msg>Add FTPSHook in _hooks register.<commit_after># Imports the hooks dynamically while keeping the package API clean, # abstracting the underlying modules from airflow.utils import import_module_attrs as _import_module_attrs _hooks = { 'ftp_hook': ['FTPHook'], 'ftps_hook': ['FTPSHook'], 'vertica_hook': ['VerticaHook'], 'ssh_hook': ['SSHHook'], 'bigquery_hook': ['BigQueryHook'], 'qubole_hook': ['QuboleHook'] } _import_module_attrs(globals(), _hooks)
7db3a14636402a5c66179a9c60df33398190bd3e
app/modules/frest/api/__init__.py
app/modules/frest/api/__init__.py
# -*- coding: utf-8 -*- from functools import wraps, partial from flask import request from flask_api import status from flask.wrappers import Response from app.config import API_ACCEPT_HEADER def API(method=None): if method is None: return partial(API) @wraps(method) def decorated(*args, **kwargs): _return = method(*args, **kwargs) if isinstance(_return, Response): return _return if request.headers['Accept'] == API_ACCEPT_HEADER: ret, code = _return else: ret, code = ("Please check request accept again.", status.HTTP_406_NOT_ACCEPTABLE) return serialize(ret, code) def serialize(ret, code): _return = {'code': code} if not status.is_success(code): _return['status'] = 'fail' if ret is not None: if isinstance(ret, dict): _return.update(ret) else: _return['message'] = ret else: _return['status'] = 'success' if ret is not None: if isinstance(ret, dict): _return.update(ret) else: _return['data'] = ret return _return, code return decorated
# -*- coding: utf-8 -*- from functools import wraps, partial from flask import request from flask_api import status from flask.wrappers import Response from app.config import API_ACCEPT_HEADER, API_VERSION def API(method=None): if method is None: return partial(API) @wraps(method) def decorated(*args, **kwargs): _return = method(*args, **kwargs) if isinstance(_return, Response): return _return if request.url.find('v' + str(API_VERSION)) > 0: if request.headers['Accept'] == API_ACCEPT_HEADER: ret, code = _return else: ret, code = ("Please check request accept again.", status.HTTP_406_NOT_ACCEPTABLE) else: ret, code = ("API has been updated. The latest version is v" + str(API_VERSION), status.HTTP_301_MOVED_PERMANENTLY) return serialize(ret, code) def serialize(ret, code): _return = {'code': code} if not status.is_success(code): _return['status'] = 'fail' if ret is not None: if isinstance(ret, dict): _return.update(ret) else: _return['message'] = ret else: _return['status'] = 'success' if ret is not None: if isinstance(ret, dict): _return.update(ret) else: _return['data'] = ret return _return, code return decorated
Return http status code 301 when api version is wrong
Return http status code 301 when api version is wrong
Python
mit
h4wldev/Frest
# -*- coding: utf-8 -*- from functools import wraps, partial from flask import request from flask_api import status from flask.wrappers import Response from app.config import API_ACCEPT_HEADER def API(method=None): if method is None: return partial(API) @wraps(method) def decorated(*args, **kwargs): _return = method(*args, **kwargs) if isinstance(_return, Response): return _return if request.headers['Accept'] == API_ACCEPT_HEADER: ret, code = _return else: ret, code = ("Please check request accept again.", status.HTTP_406_NOT_ACCEPTABLE) return serialize(ret, code) def serialize(ret, code): _return = {'code': code} if not status.is_success(code): _return['status'] = 'fail' if ret is not None: if isinstance(ret, dict): _return.update(ret) else: _return['message'] = ret else: _return['status'] = 'success' if ret is not None: if isinstance(ret, dict): _return.update(ret) else: _return['data'] = ret return _return, code return decorated Return http status code 301 when api version is wrong
# -*- coding: utf-8 -*- from functools import wraps, partial from flask import request from flask_api import status from flask.wrappers import Response from app.config import API_ACCEPT_HEADER, API_VERSION def API(method=None): if method is None: return partial(API) @wraps(method) def decorated(*args, **kwargs): _return = method(*args, **kwargs) if isinstance(_return, Response): return _return if request.url.find('v' + str(API_VERSION)) > 0: if request.headers['Accept'] == API_ACCEPT_HEADER: ret, code = _return else: ret, code = ("Please check request accept again.", status.HTTP_406_NOT_ACCEPTABLE) else: ret, code = ("API has been updated. The latest version is v" + str(API_VERSION), status.HTTP_301_MOVED_PERMANENTLY) return serialize(ret, code) def serialize(ret, code): _return = {'code': code} if not status.is_success(code): _return['status'] = 'fail' if ret is not None: if isinstance(ret, dict): _return.update(ret) else: _return['message'] = ret else: _return['status'] = 'success' if ret is not None: if isinstance(ret, dict): _return.update(ret) else: _return['data'] = ret return _return, code return decorated
<commit_before># -*- coding: utf-8 -*- from functools import wraps, partial from flask import request from flask_api import status from flask.wrappers import Response from app.config import API_ACCEPT_HEADER def API(method=None): if method is None: return partial(API) @wraps(method) def decorated(*args, **kwargs): _return = method(*args, **kwargs) if isinstance(_return, Response): return _return if request.headers['Accept'] == API_ACCEPT_HEADER: ret, code = _return else: ret, code = ("Please check request accept again.", status.HTTP_406_NOT_ACCEPTABLE) return serialize(ret, code) def serialize(ret, code): _return = {'code': code} if not status.is_success(code): _return['status'] = 'fail' if ret is not None: if isinstance(ret, dict): _return.update(ret) else: _return['message'] = ret else: _return['status'] = 'success' if ret is not None: if isinstance(ret, dict): _return.update(ret) else: _return['data'] = ret return _return, code return decorated <commit_msg>Return http status code 301 when api version is wrong<commit_after>
# -*- coding: utf-8 -*- from functools import wraps, partial from flask import request from flask_api import status from flask.wrappers import Response from app.config import API_ACCEPT_HEADER, API_VERSION def API(method=None): if method is None: return partial(API) @wraps(method) def decorated(*args, **kwargs): _return = method(*args, **kwargs) if isinstance(_return, Response): return _return if request.url.find('v' + str(API_VERSION)) > 0: if request.headers['Accept'] == API_ACCEPT_HEADER: ret, code = _return else: ret, code = ("Please check request accept again.", status.HTTP_406_NOT_ACCEPTABLE) else: ret, code = ("API has been updated. The latest version is v" + str(API_VERSION), status.HTTP_301_MOVED_PERMANENTLY) return serialize(ret, code) def serialize(ret, code): _return = {'code': code} if not status.is_success(code): _return['status'] = 'fail' if ret is not None: if isinstance(ret, dict): _return.update(ret) else: _return['message'] = ret else: _return['status'] = 'success' if ret is not None: if isinstance(ret, dict): _return.update(ret) else: _return['data'] = ret return _return, code return decorated
# -*- coding: utf-8 -*- from functools import wraps, partial from flask import request from flask_api import status from flask.wrappers import Response from app.config import API_ACCEPT_HEADER def API(method=None): if method is None: return partial(API) @wraps(method) def decorated(*args, **kwargs): _return = method(*args, **kwargs) if isinstance(_return, Response): return _return if request.headers['Accept'] == API_ACCEPT_HEADER: ret, code = _return else: ret, code = ("Please check request accept again.", status.HTTP_406_NOT_ACCEPTABLE) return serialize(ret, code) def serialize(ret, code): _return = {'code': code} if not status.is_success(code): _return['status'] = 'fail' if ret is not None: if isinstance(ret, dict): _return.update(ret) else: _return['message'] = ret else: _return['status'] = 'success' if ret is not None: if isinstance(ret, dict): _return.update(ret) else: _return['data'] = ret return _return, code return decorated Return http status code 301 when api version is wrong# -*- coding: utf-8 -*- from functools import wraps, partial from flask import request from flask_api import status from flask.wrappers import Response from app.config import API_ACCEPT_HEADER, API_VERSION def API(method=None): if method is None: return partial(API) @wraps(method) def decorated(*args, **kwargs): _return = method(*args, **kwargs) if isinstance(_return, Response): return _return if request.url.find('v' + str(API_VERSION)) > 0: if request.headers['Accept'] == API_ACCEPT_HEADER: ret, code = _return else: ret, code = ("Please check request accept again.", status.HTTP_406_NOT_ACCEPTABLE) else: ret, code = ("API has been updated. The latest version is v" + str(API_VERSION), status.HTTP_301_MOVED_PERMANENTLY) return serialize(ret, code) def serialize(ret, code): _return = {'code': code} if not status.is_success(code): _return['status'] = 'fail' if ret is not None: if isinstance(ret, dict): _return.update(ret) else: _return['message'] = ret else: _return['status'] = 'success' if ret is not None: if isinstance(ret, dict): _return.update(ret) else: _return['data'] = ret return _return, code return decorated
<commit_before># -*- coding: utf-8 -*- from functools import wraps, partial from flask import request from flask_api import status from flask.wrappers import Response from app.config import API_ACCEPT_HEADER def API(method=None): if method is None: return partial(API) @wraps(method) def decorated(*args, **kwargs): _return = method(*args, **kwargs) if isinstance(_return, Response): return _return if request.headers['Accept'] == API_ACCEPT_HEADER: ret, code = _return else: ret, code = ("Please check request accept again.", status.HTTP_406_NOT_ACCEPTABLE) return serialize(ret, code) def serialize(ret, code): _return = {'code': code} if not status.is_success(code): _return['status'] = 'fail' if ret is not None: if isinstance(ret, dict): _return.update(ret) else: _return['message'] = ret else: _return['status'] = 'success' if ret is not None: if isinstance(ret, dict): _return.update(ret) else: _return['data'] = ret return _return, code return decorated <commit_msg>Return http status code 301 when api version is wrong<commit_after># -*- coding: utf-8 -*- from functools import wraps, partial from flask import request from flask_api import status from flask.wrappers import Response from app.config import API_ACCEPT_HEADER, API_VERSION def API(method=None): if method is None: return partial(API) @wraps(method) def decorated(*args, **kwargs): _return = method(*args, **kwargs) if isinstance(_return, Response): return _return if request.url.find('v' + str(API_VERSION)) > 0: if request.headers['Accept'] == API_ACCEPT_HEADER: ret, code = _return else: ret, code = ("Please check request accept again.", status.HTTP_406_NOT_ACCEPTABLE) else: ret, code = ("API has been updated. The latest version is v" + str(API_VERSION), status.HTTP_301_MOVED_PERMANENTLY) return serialize(ret, code) def serialize(ret, code): _return = {'code': code} if not status.is_success(code): _return['status'] = 'fail' if ret is not None: if isinstance(ret, dict): _return.update(ret) else: _return['message'] = ret else: _return['status'] = 'success' if ret is not None: if isinstance(ret, dict): _return.update(ret) else: _return['data'] = ret return _return, code return decorated
a46c152adb78996538128b63e441b00bea2790ea
django_su/forms.py
django_su/forms.py
# -*- coding: utf-8 -*- from django import forms from django.conf import settings from django.utils.translation import ugettext_lazy as _ from . import get_user_model class UserSuForm(forms.Form): user = forms.ModelChoiceField( label=_('Users'), queryset=get_user_model()._default_manager.order_by( 'username'), required=True) # pylint: disable=W0212 use_ajax_select = False def __init__(self, *args, **kwargs): super(UserSuForm, self).__init__(*args, **kwargs) if 'ajax_select' in settings.INSTALLED_APPS and getattr( settings, 'AJAX_LOOKUP_CHANNELS', None): from ajax_select.fields import AutoCompleteSelectField lookup = settings.AJAX_LOOKUP_CHANNELS.get('django_su', None) if lookup is not None: old_field = self.fields['user'] self.fields['user'] = AutoCompleteSelectField( 'django_su', required=old_field.required, label=old_field.label, ) self.use_ajax_select = True def get_user(self): return self.cleaned_data.get('user', None) def __str__(self): if 'formadmin' in settings.INSTALLED_APPS: try: from formadmin.forms import as_django_admin return as_django_admin(self) except ImportError: pass return super(UserSuForm, self).__str__()
# -*- coding: utf-8 -*- from django import forms from django.conf import settings from django.utils.translation import ugettext_lazy as _ from . import get_user_model class UserSuForm(forms.Form): username_field = get_user_model().USERNAME_FIELD user = forms.ModelChoiceField( label=_('Users'), queryset=get_user_model()._default_manager.order_by( username_field), required=True) # pylint: disable=W0212 use_ajax_select = False def __init__(self, *args, **kwargs): super(UserSuForm, self).__init__(*args, **kwargs) if 'ajax_select' in settings.INSTALLED_APPS and getattr( settings, 'AJAX_LOOKUP_CHANNELS', None): from ajax_select.fields import AutoCompleteSelectField lookup = settings.AJAX_LOOKUP_CHANNELS.get('django_su', None) if lookup is not None: old_field = self.fields['user'] self.fields['user'] = AutoCompleteSelectField( 'django_su', required=old_field.required, label=old_field.label, ) self.use_ajax_select = True def get_user(self): return self.cleaned_data.get('user', None) def __str__(self): if 'formadmin' in settings.INSTALLED_APPS: try: from formadmin.forms import as_django_admin return as_django_admin(self) except ImportError: pass return super(UserSuForm, self).__str__()
Update UserSuForm to enhance compatibility with custom user models.
Update UserSuForm to enhance compatibility with custom user models. In custom user models, we cannot rely on there being a 'username' field. Instead, we should use whichever field has been specified as the username field.
Python
mit
adamcharnock/django-su,PetrDlouhy/django-su,PetrDlouhy/django-su,adamcharnock/django-su
# -*- coding: utf-8 -*- from django import forms from django.conf import settings from django.utils.translation import ugettext_lazy as _ from . import get_user_model class UserSuForm(forms.Form): user = forms.ModelChoiceField( label=_('Users'), queryset=get_user_model()._default_manager.order_by( 'username'), required=True) # pylint: disable=W0212 use_ajax_select = False def __init__(self, *args, **kwargs): super(UserSuForm, self).__init__(*args, **kwargs) if 'ajax_select' in settings.INSTALLED_APPS and getattr( settings, 'AJAX_LOOKUP_CHANNELS', None): from ajax_select.fields import AutoCompleteSelectField lookup = settings.AJAX_LOOKUP_CHANNELS.get('django_su', None) if lookup is not None: old_field = self.fields['user'] self.fields['user'] = AutoCompleteSelectField( 'django_su', required=old_field.required, label=old_field.label, ) self.use_ajax_select = True def get_user(self): return self.cleaned_data.get('user', None) def __str__(self): if 'formadmin' in settings.INSTALLED_APPS: try: from formadmin.forms import as_django_admin return as_django_admin(self) except ImportError: pass return super(UserSuForm, self).__str__() Update UserSuForm to enhance compatibility with custom user models. In custom user models, we cannot rely on there being a 'username' field. Instead, we should use whichever field has been specified as the username field.
# -*- coding: utf-8 -*- from django import forms from django.conf import settings from django.utils.translation import ugettext_lazy as _ from . import get_user_model class UserSuForm(forms.Form): username_field = get_user_model().USERNAME_FIELD user = forms.ModelChoiceField( label=_('Users'), queryset=get_user_model()._default_manager.order_by( username_field), required=True) # pylint: disable=W0212 use_ajax_select = False def __init__(self, *args, **kwargs): super(UserSuForm, self).__init__(*args, **kwargs) if 'ajax_select' in settings.INSTALLED_APPS and getattr( settings, 'AJAX_LOOKUP_CHANNELS', None): from ajax_select.fields import AutoCompleteSelectField lookup = settings.AJAX_LOOKUP_CHANNELS.get('django_su', None) if lookup is not None: old_field = self.fields['user'] self.fields['user'] = AutoCompleteSelectField( 'django_su', required=old_field.required, label=old_field.label, ) self.use_ajax_select = True def get_user(self): return self.cleaned_data.get('user', None) def __str__(self): if 'formadmin' in settings.INSTALLED_APPS: try: from formadmin.forms import as_django_admin return as_django_admin(self) except ImportError: pass return super(UserSuForm, self).__str__()
<commit_before># -*- coding: utf-8 -*- from django import forms from django.conf import settings from django.utils.translation import ugettext_lazy as _ from . import get_user_model class UserSuForm(forms.Form): user = forms.ModelChoiceField( label=_('Users'), queryset=get_user_model()._default_manager.order_by( 'username'), required=True) # pylint: disable=W0212 use_ajax_select = False def __init__(self, *args, **kwargs): super(UserSuForm, self).__init__(*args, **kwargs) if 'ajax_select' in settings.INSTALLED_APPS and getattr( settings, 'AJAX_LOOKUP_CHANNELS', None): from ajax_select.fields import AutoCompleteSelectField lookup = settings.AJAX_LOOKUP_CHANNELS.get('django_su', None) if lookup is not None: old_field = self.fields['user'] self.fields['user'] = AutoCompleteSelectField( 'django_su', required=old_field.required, label=old_field.label, ) self.use_ajax_select = True def get_user(self): return self.cleaned_data.get('user', None) def __str__(self): if 'formadmin' in settings.INSTALLED_APPS: try: from formadmin.forms import as_django_admin return as_django_admin(self) except ImportError: pass return super(UserSuForm, self).__str__() <commit_msg>Update UserSuForm to enhance compatibility with custom user models. In custom user models, we cannot rely on there being a 'username' field. Instead, we should use whichever field has been specified as the username field.<commit_after>
# -*- coding: utf-8 -*- from django import forms from django.conf import settings from django.utils.translation import ugettext_lazy as _ from . import get_user_model class UserSuForm(forms.Form): username_field = get_user_model().USERNAME_FIELD user = forms.ModelChoiceField( label=_('Users'), queryset=get_user_model()._default_manager.order_by( username_field), required=True) # pylint: disable=W0212 use_ajax_select = False def __init__(self, *args, **kwargs): super(UserSuForm, self).__init__(*args, **kwargs) if 'ajax_select' in settings.INSTALLED_APPS and getattr( settings, 'AJAX_LOOKUP_CHANNELS', None): from ajax_select.fields import AutoCompleteSelectField lookup = settings.AJAX_LOOKUP_CHANNELS.get('django_su', None) if lookup is not None: old_field = self.fields['user'] self.fields['user'] = AutoCompleteSelectField( 'django_su', required=old_field.required, label=old_field.label, ) self.use_ajax_select = True def get_user(self): return self.cleaned_data.get('user', None) def __str__(self): if 'formadmin' in settings.INSTALLED_APPS: try: from formadmin.forms import as_django_admin return as_django_admin(self) except ImportError: pass return super(UserSuForm, self).__str__()
# -*- coding: utf-8 -*- from django import forms from django.conf import settings from django.utils.translation import ugettext_lazy as _ from . import get_user_model class UserSuForm(forms.Form): user = forms.ModelChoiceField( label=_('Users'), queryset=get_user_model()._default_manager.order_by( 'username'), required=True) # pylint: disable=W0212 use_ajax_select = False def __init__(self, *args, **kwargs): super(UserSuForm, self).__init__(*args, **kwargs) if 'ajax_select' in settings.INSTALLED_APPS and getattr( settings, 'AJAX_LOOKUP_CHANNELS', None): from ajax_select.fields import AutoCompleteSelectField lookup = settings.AJAX_LOOKUP_CHANNELS.get('django_su', None) if lookup is not None: old_field = self.fields['user'] self.fields['user'] = AutoCompleteSelectField( 'django_su', required=old_field.required, label=old_field.label, ) self.use_ajax_select = True def get_user(self): return self.cleaned_data.get('user', None) def __str__(self): if 'formadmin' in settings.INSTALLED_APPS: try: from formadmin.forms import as_django_admin return as_django_admin(self) except ImportError: pass return super(UserSuForm, self).__str__() Update UserSuForm to enhance compatibility with custom user models. In custom user models, we cannot rely on there being a 'username' field. Instead, we should use whichever field has been specified as the username field.# -*- coding: utf-8 -*- from django import forms from django.conf import settings from django.utils.translation import ugettext_lazy as _ from . import get_user_model class UserSuForm(forms.Form): username_field = get_user_model().USERNAME_FIELD user = forms.ModelChoiceField( label=_('Users'), queryset=get_user_model()._default_manager.order_by( username_field), required=True) # pylint: disable=W0212 use_ajax_select = False def __init__(self, *args, **kwargs): super(UserSuForm, self).__init__(*args, **kwargs) if 'ajax_select' in settings.INSTALLED_APPS and getattr( settings, 'AJAX_LOOKUP_CHANNELS', None): from ajax_select.fields import AutoCompleteSelectField lookup = settings.AJAX_LOOKUP_CHANNELS.get('django_su', None) if lookup is not None: old_field = self.fields['user'] self.fields['user'] = AutoCompleteSelectField( 'django_su', required=old_field.required, label=old_field.label, ) self.use_ajax_select = True def get_user(self): return self.cleaned_data.get('user', None) def __str__(self): if 'formadmin' in settings.INSTALLED_APPS: try: from formadmin.forms import as_django_admin return as_django_admin(self) except ImportError: pass return super(UserSuForm, self).__str__()
<commit_before># -*- coding: utf-8 -*- from django import forms from django.conf import settings from django.utils.translation import ugettext_lazy as _ from . import get_user_model class UserSuForm(forms.Form): user = forms.ModelChoiceField( label=_('Users'), queryset=get_user_model()._default_manager.order_by( 'username'), required=True) # pylint: disable=W0212 use_ajax_select = False def __init__(self, *args, **kwargs): super(UserSuForm, self).__init__(*args, **kwargs) if 'ajax_select' in settings.INSTALLED_APPS and getattr( settings, 'AJAX_LOOKUP_CHANNELS', None): from ajax_select.fields import AutoCompleteSelectField lookup = settings.AJAX_LOOKUP_CHANNELS.get('django_su', None) if lookup is not None: old_field = self.fields['user'] self.fields['user'] = AutoCompleteSelectField( 'django_su', required=old_field.required, label=old_field.label, ) self.use_ajax_select = True def get_user(self): return self.cleaned_data.get('user', None) def __str__(self): if 'formadmin' in settings.INSTALLED_APPS: try: from formadmin.forms import as_django_admin return as_django_admin(self) except ImportError: pass return super(UserSuForm, self).__str__() <commit_msg>Update UserSuForm to enhance compatibility with custom user models. In custom user models, we cannot rely on there being a 'username' field. Instead, we should use whichever field has been specified as the username field.<commit_after># -*- coding: utf-8 -*- from django import forms from django.conf import settings from django.utils.translation import ugettext_lazy as _ from . import get_user_model class UserSuForm(forms.Form): username_field = get_user_model().USERNAME_FIELD user = forms.ModelChoiceField( label=_('Users'), queryset=get_user_model()._default_manager.order_by( username_field), required=True) # pylint: disable=W0212 use_ajax_select = False def __init__(self, *args, **kwargs): super(UserSuForm, self).__init__(*args, **kwargs) if 'ajax_select' in settings.INSTALLED_APPS and getattr( settings, 'AJAX_LOOKUP_CHANNELS', None): from ajax_select.fields import AutoCompleteSelectField lookup = settings.AJAX_LOOKUP_CHANNELS.get('django_su', None) if lookup is not None: old_field = self.fields['user'] self.fields['user'] = AutoCompleteSelectField( 'django_su', required=old_field.required, label=old_field.label, ) self.use_ajax_select = True def get_user(self): return self.cleaned_data.get('user', None) def __str__(self): if 'formadmin' in settings.INSTALLED_APPS: try: from formadmin.forms import as_django_admin return as_django_admin(self) except ImportError: pass return super(UserSuForm, self).__str__()
f3cf8b8e36dc7d2ed5096e17dcfa1f9456a7a996
Project-AENEAS/issues/models.py
Project-AENEAS/issues/models.py
from django.db import models # Create your models here.
"""Mini Issue Tracker program. Originally taken from Paul Bissex's blog post: http://news.e-scribe.com/230 and snippet: http://djangosnippets.org/snippets/28/ """ from django.db import models from django.contrib.auth.models import User from django.conf import settings from django.utils.translation import ugettext_lazy as _ STATUS_CODES = ( (1, _('Open')), (2, _('Working')), (3, _('Closed')), ) PRIORITY_CODES = ( (1, _('Now')), (2, _('Soon')), (3, _('Someday')), ) apps = [app for app in settings.INSTALLED_APPS if not app.startswith('django.')] class Ticket(models.Model): """Trouble tickets""" title = models.CharField(_('title'), max_length=100) project = models.CharField(_('project'), blank=True, max_length=100, choices=list(enumerate(apps))) submitted_date = models.DateField(_('date submitted'), auto_now_add=True) modified_date = models.DateField(_('date modified'), auto_now=True) submitter = models.ForeignKey(User, verbose_name=_('submitter'), related_name="submitter") assigned_to = models.ForeignKey(User, verbose_name=_('assigned to')) description = models.TextField(_('description'), blank=True) status = models.IntegerField(_('status'), default=1, choices=STATUS_CODES) priority = models.IntegerField(_('priority'), default=1, choices=PRIORITY_CODES) class Meta: verbose_name = _('ticket') verbose_name_plural = _('tickets') ordering = ('status', 'priority', 'submitted_date', 'title') def __unicode__(self): return self.title
Add an initial model for an issue
Add an initial model for an issue
Python
bsd-3-clause
zooming-tan/Project-AENEAS,zooming-tan/Project-AENEAS,zooming-tan/Project-AENEAS,zooming-tan/Project-AENEAS
from django.db import models # Create your models here. Add an initial model for an issue
"""Mini Issue Tracker program. Originally taken from Paul Bissex's blog post: http://news.e-scribe.com/230 and snippet: http://djangosnippets.org/snippets/28/ """ from django.db import models from django.contrib.auth.models import User from django.conf import settings from django.utils.translation import ugettext_lazy as _ STATUS_CODES = ( (1, _('Open')), (2, _('Working')), (3, _('Closed')), ) PRIORITY_CODES = ( (1, _('Now')), (2, _('Soon')), (3, _('Someday')), ) apps = [app for app in settings.INSTALLED_APPS if not app.startswith('django.')] class Ticket(models.Model): """Trouble tickets""" title = models.CharField(_('title'), max_length=100) project = models.CharField(_('project'), blank=True, max_length=100, choices=list(enumerate(apps))) submitted_date = models.DateField(_('date submitted'), auto_now_add=True) modified_date = models.DateField(_('date modified'), auto_now=True) submitter = models.ForeignKey(User, verbose_name=_('submitter'), related_name="submitter") assigned_to = models.ForeignKey(User, verbose_name=_('assigned to')) description = models.TextField(_('description'), blank=True) status = models.IntegerField(_('status'), default=1, choices=STATUS_CODES) priority = models.IntegerField(_('priority'), default=1, choices=PRIORITY_CODES) class Meta: verbose_name = _('ticket') verbose_name_plural = _('tickets') ordering = ('status', 'priority', 'submitted_date', 'title') def __unicode__(self): return self.title
<commit_before>from django.db import models # Create your models here. <commit_msg>Add an initial model for an issue<commit_after>
"""Mini Issue Tracker program. Originally taken from Paul Bissex's blog post: http://news.e-scribe.com/230 and snippet: http://djangosnippets.org/snippets/28/ """ from django.db import models from django.contrib.auth.models import User from django.conf import settings from django.utils.translation import ugettext_lazy as _ STATUS_CODES = ( (1, _('Open')), (2, _('Working')), (3, _('Closed')), ) PRIORITY_CODES = ( (1, _('Now')), (2, _('Soon')), (3, _('Someday')), ) apps = [app for app in settings.INSTALLED_APPS if not app.startswith('django.')] class Ticket(models.Model): """Trouble tickets""" title = models.CharField(_('title'), max_length=100) project = models.CharField(_('project'), blank=True, max_length=100, choices=list(enumerate(apps))) submitted_date = models.DateField(_('date submitted'), auto_now_add=True) modified_date = models.DateField(_('date modified'), auto_now=True) submitter = models.ForeignKey(User, verbose_name=_('submitter'), related_name="submitter") assigned_to = models.ForeignKey(User, verbose_name=_('assigned to')) description = models.TextField(_('description'), blank=True) status = models.IntegerField(_('status'), default=1, choices=STATUS_CODES) priority = models.IntegerField(_('priority'), default=1, choices=PRIORITY_CODES) class Meta: verbose_name = _('ticket') verbose_name_plural = _('tickets') ordering = ('status', 'priority', 'submitted_date', 'title') def __unicode__(self): return self.title
from django.db import models # Create your models here. Add an initial model for an issue"""Mini Issue Tracker program. Originally taken from Paul Bissex's blog post: http://news.e-scribe.com/230 and snippet: http://djangosnippets.org/snippets/28/ """ from django.db import models from django.contrib.auth.models import User from django.conf import settings from django.utils.translation import ugettext_lazy as _ STATUS_CODES = ( (1, _('Open')), (2, _('Working')), (3, _('Closed')), ) PRIORITY_CODES = ( (1, _('Now')), (2, _('Soon')), (3, _('Someday')), ) apps = [app for app in settings.INSTALLED_APPS if not app.startswith('django.')] class Ticket(models.Model): """Trouble tickets""" title = models.CharField(_('title'), max_length=100) project = models.CharField(_('project'), blank=True, max_length=100, choices=list(enumerate(apps))) submitted_date = models.DateField(_('date submitted'), auto_now_add=True) modified_date = models.DateField(_('date modified'), auto_now=True) submitter = models.ForeignKey(User, verbose_name=_('submitter'), related_name="submitter") assigned_to = models.ForeignKey(User, verbose_name=_('assigned to')) description = models.TextField(_('description'), blank=True) status = models.IntegerField(_('status'), default=1, choices=STATUS_CODES) priority = models.IntegerField(_('priority'), default=1, choices=PRIORITY_CODES) class Meta: verbose_name = _('ticket') verbose_name_plural = _('tickets') ordering = ('status', 'priority', 'submitted_date', 'title') def __unicode__(self): return self.title
<commit_before>from django.db import models # Create your models here. <commit_msg>Add an initial model for an issue<commit_after>"""Mini Issue Tracker program. Originally taken from Paul Bissex's blog post: http://news.e-scribe.com/230 and snippet: http://djangosnippets.org/snippets/28/ """ from django.db import models from django.contrib.auth.models import User from django.conf import settings from django.utils.translation import ugettext_lazy as _ STATUS_CODES = ( (1, _('Open')), (2, _('Working')), (3, _('Closed')), ) PRIORITY_CODES = ( (1, _('Now')), (2, _('Soon')), (3, _('Someday')), ) apps = [app for app in settings.INSTALLED_APPS if not app.startswith('django.')] class Ticket(models.Model): """Trouble tickets""" title = models.CharField(_('title'), max_length=100) project = models.CharField(_('project'), blank=True, max_length=100, choices=list(enumerate(apps))) submitted_date = models.DateField(_('date submitted'), auto_now_add=True) modified_date = models.DateField(_('date modified'), auto_now=True) submitter = models.ForeignKey(User, verbose_name=_('submitter'), related_name="submitter") assigned_to = models.ForeignKey(User, verbose_name=_('assigned to')) description = models.TextField(_('description'), blank=True) status = models.IntegerField(_('status'), default=1, choices=STATUS_CODES) priority = models.IntegerField(_('priority'), default=1, choices=PRIORITY_CODES) class Meta: verbose_name = _('ticket') verbose_name_plural = _('tickets') ordering = ('status', 'priority', 'submitted_date', 'title') def __unicode__(self): return self.title
cd5d291fc1ccf3e2171ccfc0444e4748de450d3c
99_misc/control_flow.py
99_misc/control_flow.py
#!/usr/bin/env python # function def sum(op1, op2): return op1 + op2 my_sum = sum print my_sum(1, 2) print my_sum("I am ", "zzz"); # Default value in a fuction init = 12 def accumulate(val = init): val += val return val my_accu = accumulate init = 11 print my_accu() # is 12 + 12 rather than 11 + 11 # Default value in a function 2 def my_func(op1, op2 = '2', op3 = '3'): # non-default argument first return op1 + op2 + op3 print my_func('3') print my_func('1', op2 = 'zzz') print my_func('1', op3 = 'xxx') # pass print "press ctrl + c to continue" while True: pass
#!/usr/bin/env python # function def sum(op1, op2): return op1 + op2 my_sum = sum print my_sum(1, 2) print my_sum("I am ", "zzz"); # Default value in a fuction init = 12 def accumulate(val = init): val += val return val my_accu = accumulate init = 11 print my_accu() # is 12 + 12 rather than 11 + 11 # Default value in a function 2 def my_func(op1, op2 = '2', op3 = '3'): # non-default argument first return op1 + op2 + op3 print my_func('3') print my_func('1', op2 = 'zzz') print my_func('1', op3 = 'xxx') # variable argument def var_arg(*args): print args var_arg(1, 2, 3, 4 ,5) var_arg("I am ", "zzz") var_arg(range(3,7)) # pass print "press ctrl + c to continue" while True: pass
Test variable argument in a function
Test variable argument in a function
Python
bsd-2-clause
zzz0072/Python_Exercises,zzz0072/Python_Exercises
#!/usr/bin/env python # function def sum(op1, op2): return op1 + op2 my_sum = sum print my_sum(1, 2) print my_sum("I am ", "zzz"); # Default value in a fuction init = 12 def accumulate(val = init): val += val return val my_accu = accumulate init = 11 print my_accu() # is 12 + 12 rather than 11 + 11 # Default value in a function 2 def my_func(op1, op2 = '2', op3 = '3'): # non-default argument first return op1 + op2 + op3 print my_func('3') print my_func('1', op2 = 'zzz') print my_func('1', op3 = 'xxx') # pass print "press ctrl + c to continue" while True: pass Test variable argument in a function
#!/usr/bin/env python # function def sum(op1, op2): return op1 + op2 my_sum = sum print my_sum(1, 2) print my_sum("I am ", "zzz"); # Default value in a fuction init = 12 def accumulate(val = init): val += val return val my_accu = accumulate init = 11 print my_accu() # is 12 + 12 rather than 11 + 11 # Default value in a function 2 def my_func(op1, op2 = '2', op3 = '3'): # non-default argument first return op1 + op2 + op3 print my_func('3') print my_func('1', op2 = 'zzz') print my_func('1', op3 = 'xxx') # variable argument def var_arg(*args): print args var_arg(1, 2, 3, 4 ,5) var_arg("I am ", "zzz") var_arg(range(3,7)) # pass print "press ctrl + c to continue" while True: pass
<commit_before>#!/usr/bin/env python # function def sum(op1, op2): return op1 + op2 my_sum = sum print my_sum(1, 2) print my_sum("I am ", "zzz"); # Default value in a fuction init = 12 def accumulate(val = init): val += val return val my_accu = accumulate init = 11 print my_accu() # is 12 + 12 rather than 11 + 11 # Default value in a function 2 def my_func(op1, op2 = '2', op3 = '3'): # non-default argument first return op1 + op2 + op3 print my_func('3') print my_func('1', op2 = 'zzz') print my_func('1', op3 = 'xxx') # pass print "press ctrl + c to continue" while True: pass <commit_msg>Test variable argument in a function<commit_after>
#!/usr/bin/env python # function def sum(op1, op2): return op1 + op2 my_sum = sum print my_sum(1, 2) print my_sum("I am ", "zzz"); # Default value in a fuction init = 12 def accumulate(val = init): val += val return val my_accu = accumulate init = 11 print my_accu() # is 12 + 12 rather than 11 + 11 # Default value in a function 2 def my_func(op1, op2 = '2', op3 = '3'): # non-default argument first return op1 + op2 + op3 print my_func('3') print my_func('1', op2 = 'zzz') print my_func('1', op3 = 'xxx') # variable argument def var_arg(*args): print args var_arg(1, 2, 3, 4 ,5) var_arg("I am ", "zzz") var_arg(range(3,7)) # pass print "press ctrl + c to continue" while True: pass
#!/usr/bin/env python # function def sum(op1, op2): return op1 + op2 my_sum = sum print my_sum(1, 2) print my_sum("I am ", "zzz"); # Default value in a fuction init = 12 def accumulate(val = init): val += val return val my_accu = accumulate init = 11 print my_accu() # is 12 + 12 rather than 11 + 11 # Default value in a function 2 def my_func(op1, op2 = '2', op3 = '3'): # non-default argument first return op1 + op2 + op3 print my_func('3') print my_func('1', op2 = 'zzz') print my_func('1', op3 = 'xxx') # pass print "press ctrl + c to continue" while True: pass Test variable argument in a function#!/usr/bin/env python # function def sum(op1, op2): return op1 + op2 my_sum = sum print my_sum(1, 2) print my_sum("I am ", "zzz"); # Default value in a fuction init = 12 def accumulate(val = init): val += val return val my_accu = accumulate init = 11 print my_accu() # is 12 + 12 rather than 11 + 11 # Default value in a function 2 def my_func(op1, op2 = '2', op3 = '3'): # non-default argument first return op1 + op2 + op3 print my_func('3') print my_func('1', op2 = 'zzz') print my_func('1', op3 = 'xxx') # variable argument def var_arg(*args): print args var_arg(1, 2, 3, 4 ,5) var_arg("I am ", "zzz") var_arg(range(3,7)) # pass print "press ctrl + c to continue" while True: pass
<commit_before>#!/usr/bin/env python # function def sum(op1, op2): return op1 + op2 my_sum = sum print my_sum(1, 2) print my_sum("I am ", "zzz"); # Default value in a fuction init = 12 def accumulate(val = init): val += val return val my_accu = accumulate init = 11 print my_accu() # is 12 + 12 rather than 11 + 11 # Default value in a function 2 def my_func(op1, op2 = '2', op3 = '3'): # non-default argument first return op1 + op2 + op3 print my_func('3') print my_func('1', op2 = 'zzz') print my_func('1', op3 = 'xxx') # pass print "press ctrl + c to continue" while True: pass <commit_msg>Test variable argument in a function<commit_after>#!/usr/bin/env python # function def sum(op1, op2): return op1 + op2 my_sum = sum print my_sum(1, 2) print my_sum("I am ", "zzz"); # Default value in a fuction init = 12 def accumulate(val = init): val += val return val my_accu = accumulate init = 11 print my_accu() # is 12 + 12 rather than 11 + 11 # Default value in a function 2 def my_func(op1, op2 = '2', op3 = '3'): # non-default argument first return op1 + op2 + op3 print my_func('3') print my_func('1', op2 = 'zzz') print my_func('1', op3 = 'xxx') # variable argument def var_arg(*args): print args var_arg(1, 2, 3, 4 ,5) var_arg("I am ", "zzz") var_arg(range(3,7)) # pass print "press ctrl + c to continue" while True: pass
f9aeede7af207a672a867c4f310d7d357a4d47c9
icekit/utils/fluent_contents.py
icekit/utils/fluent_contents.py
from django.contrib.contenttypes.models import ContentType # USEFUL FUNCTIONS FOR FLUENT CONTENTS ############################################################# # Fluent Contents Helper Functions ################################################################# def create_content_instance(content_plugin_class, test_page, placeholder_name='main', **kwargs): """ Creates a content instance from a content plugin class. :param content_plugin_class: The class of the content plugin. :param test_page: The fluent_page instance to create the content instance one. :param placeholder_name: The placeholder name defined in the template. [DEFAULT: main] :param kwargs: Additional keyword arguments to be used in the content instance creation. :return: The content instance created. """ # Get the placeholders that are currently available for the slot. placeholders = test_page.get_placeholder_by_slot(placeholder_name) # If a placeholder exists for the placeholder_name use the first one provided otherwise create # a new placeholder instance. if placeholders.exists(): placeholder = placeholders[0] else: placeholder = test_page.create_placeholder(placeholder_name) # Obtain the content type for the page instance class. ct = ContentType.objects.get_for_model(type(test_page)) # Create the actual plugin instance. content_instance = content_plugin_class.objects.create( parent_type=ct, parent_id=test_page.id, placeholder=placeholder, **kwargs ) return content_instance # END Fluent Contents Helper Functions #############################################################
from django.contrib.contenttypes.models import ContentType # USEFUL FUNCTIONS FOR FLUENT CONTENTS ############################################################# # Fluent Contents Helper Functions ################################################################# def create_content_instance(content_plugin_class, test_page, placeholder_name='main', **kwargs): """ Creates a content instance from a content plugin class. :param content_plugin_class: The class of the content plugin. :param test_page: The fluent_page instance to create the content instance one. :param placeholder_name: The placeholder name defined in the template. [DEFAULT: main] :param kwargs: Additional keyword arguments to be used in the content instance creation. :return: The content instance created. """ # Get the placeholders that are currently available for the slot. placeholders = test_page.get_placeholder_by_slot(placeholder_name) # If a placeholder exists for the placeholder_name use the first one provided otherwise create # a new placeholder instance. if placeholders.exists(): placeholder = placeholders[0] else: placeholder = test_page.create_placeholder(placeholder_name) # Obtain the content type for the page instance class. ct = ContentType.objects.get_for_model(type(test_page)) # Create the actual plugin instance. try: content_instance = content_plugin_class.objects.create( parent_type=ct, parent_id=test_page.id, placeholder=placeholder, **kwargs ) except TypeError: raise Exception( 'Could not create content item instance, ensure you ' 'have all required field values for the Model.' ) return content_instance # END Fluent Contents Helper Functions #############################################################
Improve error reporting for content item testing utils
Improve error reporting for content item testing utils
Python
mit
ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit
from django.contrib.contenttypes.models import ContentType # USEFUL FUNCTIONS FOR FLUENT CONTENTS ############################################################# # Fluent Contents Helper Functions ################################################################# def create_content_instance(content_plugin_class, test_page, placeholder_name='main', **kwargs): """ Creates a content instance from a content plugin class. :param content_plugin_class: The class of the content plugin. :param test_page: The fluent_page instance to create the content instance one. :param placeholder_name: The placeholder name defined in the template. [DEFAULT: main] :param kwargs: Additional keyword arguments to be used in the content instance creation. :return: The content instance created. """ # Get the placeholders that are currently available for the slot. placeholders = test_page.get_placeholder_by_slot(placeholder_name) # If a placeholder exists for the placeholder_name use the first one provided otherwise create # a new placeholder instance. if placeholders.exists(): placeholder = placeholders[0] else: placeholder = test_page.create_placeholder(placeholder_name) # Obtain the content type for the page instance class. ct = ContentType.objects.get_for_model(type(test_page)) # Create the actual plugin instance. content_instance = content_plugin_class.objects.create( parent_type=ct, parent_id=test_page.id, placeholder=placeholder, **kwargs ) return content_instance # END Fluent Contents Helper Functions ############################################################# Improve error reporting for content item testing utils
from django.contrib.contenttypes.models import ContentType # USEFUL FUNCTIONS FOR FLUENT CONTENTS ############################################################# # Fluent Contents Helper Functions ################################################################# def create_content_instance(content_plugin_class, test_page, placeholder_name='main', **kwargs): """ Creates a content instance from a content plugin class. :param content_plugin_class: The class of the content plugin. :param test_page: The fluent_page instance to create the content instance one. :param placeholder_name: The placeholder name defined in the template. [DEFAULT: main] :param kwargs: Additional keyword arguments to be used in the content instance creation. :return: The content instance created. """ # Get the placeholders that are currently available for the slot. placeholders = test_page.get_placeholder_by_slot(placeholder_name) # If a placeholder exists for the placeholder_name use the first one provided otherwise create # a new placeholder instance. if placeholders.exists(): placeholder = placeholders[0] else: placeholder = test_page.create_placeholder(placeholder_name) # Obtain the content type for the page instance class. ct = ContentType.objects.get_for_model(type(test_page)) # Create the actual plugin instance. try: content_instance = content_plugin_class.objects.create( parent_type=ct, parent_id=test_page.id, placeholder=placeholder, **kwargs ) except TypeError: raise Exception( 'Could not create content item instance, ensure you ' 'have all required field values for the Model.' ) return content_instance # END Fluent Contents Helper Functions #############################################################
<commit_before>from django.contrib.contenttypes.models import ContentType # USEFUL FUNCTIONS FOR FLUENT CONTENTS ############################################################# # Fluent Contents Helper Functions ################################################################# def create_content_instance(content_plugin_class, test_page, placeholder_name='main', **kwargs): """ Creates a content instance from a content plugin class. :param content_plugin_class: The class of the content plugin. :param test_page: The fluent_page instance to create the content instance one. :param placeholder_name: The placeholder name defined in the template. [DEFAULT: main] :param kwargs: Additional keyword arguments to be used in the content instance creation. :return: The content instance created. """ # Get the placeholders that are currently available for the slot. placeholders = test_page.get_placeholder_by_slot(placeholder_name) # If a placeholder exists for the placeholder_name use the first one provided otherwise create # a new placeholder instance. if placeholders.exists(): placeholder = placeholders[0] else: placeholder = test_page.create_placeholder(placeholder_name) # Obtain the content type for the page instance class. ct = ContentType.objects.get_for_model(type(test_page)) # Create the actual plugin instance. content_instance = content_plugin_class.objects.create( parent_type=ct, parent_id=test_page.id, placeholder=placeholder, **kwargs ) return content_instance # END Fluent Contents Helper Functions ############################################################# <commit_msg>Improve error reporting for content item testing utils<commit_after>
from django.contrib.contenttypes.models import ContentType # USEFUL FUNCTIONS FOR FLUENT CONTENTS ############################################################# # Fluent Contents Helper Functions ################################################################# def create_content_instance(content_plugin_class, test_page, placeholder_name='main', **kwargs): """ Creates a content instance from a content plugin class. :param content_plugin_class: The class of the content plugin. :param test_page: The fluent_page instance to create the content instance one. :param placeholder_name: The placeholder name defined in the template. [DEFAULT: main] :param kwargs: Additional keyword arguments to be used in the content instance creation. :return: The content instance created. """ # Get the placeholders that are currently available for the slot. placeholders = test_page.get_placeholder_by_slot(placeholder_name) # If a placeholder exists for the placeholder_name use the first one provided otherwise create # a new placeholder instance. if placeholders.exists(): placeholder = placeholders[0] else: placeholder = test_page.create_placeholder(placeholder_name) # Obtain the content type for the page instance class. ct = ContentType.objects.get_for_model(type(test_page)) # Create the actual plugin instance. try: content_instance = content_plugin_class.objects.create( parent_type=ct, parent_id=test_page.id, placeholder=placeholder, **kwargs ) except TypeError: raise Exception( 'Could not create content item instance, ensure you ' 'have all required field values for the Model.' ) return content_instance # END Fluent Contents Helper Functions #############################################################
from django.contrib.contenttypes.models import ContentType # USEFUL FUNCTIONS FOR FLUENT CONTENTS ############################################################# # Fluent Contents Helper Functions ################################################################# def create_content_instance(content_plugin_class, test_page, placeholder_name='main', **kwargs): """ Creates a content instance from a content plugin class. :param content_plugin_class: The class of the content plugin. :param test_page: The fluent_page instance to create the content instance one. :param placeholder_name: The placeholder name defined in the template. [DEFAULT: main] :param kwargs: Additional keyword arguments to be used in the content instance creation. :return: The content instance created. """ # Get the placeholders that are currently available for the slot. placeholders = test_page.get_placeholder_by_slot(placeholder_name) # If a placeholder exists for the placeholder_name use the first one provided otherwise create # a new placeholder instance. if placeholders.exists(): placeholder = placeholders[0] else: placeholder = test_page.create_placeholder(placeholder_name) # Obtain the content type for the page instance class. ct = ContentType.objects.get_for_model(type(test_page)) # Create the actual plugin instance. content_instance = content_plugin_class.objects.create( parent_type=ct, parent_id=test_page.id, placeholder=placeholder, **kwargs ) return content_instance # END Fluent Contents Helper Functions ############################################################# Improve error reporting for content item testing utilsfrom django.contrib.contenttypes.models import ContentType # USEFUL FUNCTIONS FOR FLUENT CONTENTS ############################################################# # Fluent Contents Helper Functions ################################################################# def create_content_instance(content_plugin_class, test_page, placeholder_name='main', **kwargs): """ Creates a content instance from a content plugin class. :param content_plugin_class: The class of the content plugin. :param test_page: The fluent_page instance to create the content instance one. :param placeholder_name: The placeholder name defined in the template. [DEFAULT: main] :param kwargs: Additional keyword arguments to be used in the content instance creation. :return: The content instance created. """ # Get the placeholders that are currently available for the slot. placeholders = test_page.get_placeholder_by_slot(placeholder_name) # If a placeholder exists for the placeholder_name use the first one provided otherwise create # a new placeholder instance. if placeholders.exists(): placeholder = placeholders[0] else: placeholder = test_page.create_placeholder(placeholder_name) # Obtain the content type for the page instance class. ct = ContentType.objects.get_for_model(type(test_page)) # Create the actual plugin instance. try: content_instance = content_plugin_class.objects.create( parent_type=ct, parent_id=test_page.id, placeholder=placeholder, **kwargs ) except TypeError: raise Exception( 'Could not create content item instance, ensure you ' 'have all required field values for the Model.' ) return content_instance # END Fluent Contents Helper Functions #############################################################
<commit_before>from django.contrib.contenttypes.models import ContentType # USEFUL FUNCTIONS FOR FLUENT CONTENTS ############################################################# # Fluent Contents Helper Functions ################################################################# def create_content_instance(content_plugin_class, test_page, placeholder_name='main', **kwargs): """ Creates a content instance from a content plugin class. :param content_plugin_class: The class of the content plugin. :param test_page: The fluent_page instance to create the content instance one. :param placeholder_name: The placeholder name defined in the template. [DEFAULT: main] :param kwargs: Additional keyword arguments to be used in the content instance creation. :return: The content instance created. """ # Get the placeholders that are currently available for the slot. placeholders = test_page.get_placeholder_by_slot(placeholder_name) # If a placeholder exists for the placeholder_name use the first one provided otherwise create # a new placeholder instance. if placeholders.exists(): placeholder = placeholders[0] else: placeholder = test_page.create_placeholder(placeholder_name) # Obtain the content type for the page instance class. ct = ContentType.objects.get_for_model(type(test_page)) # Create the actual plugin instance. content_instance = content_plugin_class.objects.create( parent_type=ct, parent_id=test_page.id, placeholder=placeholder, **kwargs ) return content_instance # END Fluent Contents Helper Functions ############################################################# <commit_msg>Improve error reporting for content item testing utils<commit_after>from django.contrib.contenttypes.models import ContentType # USEFUL FUNCTIONS FOR FLUENT CONTENTS ############################################################# # Fluent Contents Helper Functions ################################################################# def create_content_instance(content_plugin_class, test_page, placeholder_name='main', **kwargs): """ Creates a content instance from a content plugin class. :param content_plugin_class: The class of the content plugin. :param test_page: The fluent_page instance to create the content instance one. :param placeholder_name: The placeholder name defined in the template. [DEFAULT: main] :param kwargs: Additional keyword arguments to be used in the content instance creation. :return: The content instance created. """ # Get the placeholders that are currently available for the slot. placeholders = test_page.get_placeholder_by_slot(placeholder_name) # If a placeholder exists for the placeholder_name use the first one provided otherwise create # a new placeholder instance. if placeholders.exists(): placeholder = placeholders[0] else: placeholder = test_page.create_placeholder(placeholder_name) # Obtain the content type for the page instance class. ct = ContentType.objects.get_for_model(type(test_page)) # Create the actual plugin instance. try: content_instance = content_plugin_class.objects.create( parent_type=ct, parent_id=test_page.id, placeholder=placeholder, **kwargs ) except TypeError: raise Exception( 'Could not create content item instance, ensure you ' 'have all required field values for the Model.' ) return content_instance # END Fluent Contents Helper Functions #############################################################
e9efe7ff408fe5dd3be596ce9ded3bce312cb9e6
shell/src/hook.py
shell/src/hook.py
import threading import contextlib the_current_shell = threading.local() the_current_shell.value = None @contextlib.contextmanager def set_current_shell(shell): outer = the_current_shell.value the_current_shell.value = shell try: yield finally: the_current_shell.value = outer def current_shell(): assert the_current_shell.value is not None, 'No current shell!' return the_current_shell.value def bayesdb_shell_cmd(name, autorehook=False): def wrapper(func): # because the cmd loop doesn't handle errors and just kicks people out def excepection_handling_func(*args, **kwargs): try: return func(*args, **kwargs) except Exception as err: print err current_shell()._hook(name, excepection_handling_func, autorehook=autorehook) return wrapper
import threading import contextlib the_current_shell = threading.local() the_current_shell.value = None @contextlib.contextmanager def set_current_shell(shell): outer = the_current_shell.value the_current_shell.value = shell try: yield finally: the_current_shell.value = outer def current_shell(): assert the_current_shell.value is not None, 'No current shell!' return the_current_shell.value # make sure that the function that is hooked by the shell has the same # __doc__ class bayesdb_shellhookexp(object): def __init__(self, func): self.func = func self.__doc__ = func.__doc__ def __call__(self, *args): try: return self.func(*args) except Exception as err: print err def bayesdb_shell_cmd(name, autorehook=False): def wrapper(func): # because the cmd loop doesn't handle errors and just kicks people out current_shell()._hook(name, bayesdb_shellhookexp(func), autorehook=autorehook) return wrapper
Make sure that the wrapped function inherits doctring
Make sure that the wrapped function inherits doctring
Python
apache-2.0
probcomp/bayeslite,probcomp/bayeslite
import threading import contextlib the_current_shell = threading.local() the_current_shell.value = None @contextlib.contextmanager def set_current_shell(shell): outer = the_current_shell.value the_current_shell.value = shell try: yield finally: the_current_shell.value = outer def current_shell(): assert the_current_shell.value is not None, 'No current shell!' return the_current_shell.value def bayesdb_shell_cmd(name, autorehook=False): def wrapper(func): # because the cmd loop doesn't handle errors and just kicks people out def excepection_handling_func(*args, **kwargs): try: return func(*args, **kwargs) except Exception as err: print err current_shell()._hook(name, excepection_handling_func, autorehook=autorehook) return wrapper Make sure that the wrapped function inherits doctring
import threading import contextlib the_current_shell = threading.local() the_current_shell.value = None @contextlib.contextmanager def set_current_shell(shell): outer = the_current_shell.value the_current_shell.value = shell try: yield finally: the_current_shell.value = outer def current_shell(): assert the_current_shell.value is not None, 'No current shell!' return the_current_shell.value # make sure that the function that is hooked by the shell has the same # __doc__ class bayesdb_shellhookexp(object): def __init__(self, func): self.func = func self.__doc__ = func.__doc__ def __call__(self, *args): try: return self.func(*args) except Exception as err: print err def bayesdb_shell_cmd(name, autorehook=False): def wrapper(func): # because the cmd loop doesn't handle errors and just kicks people out current_shell()._hook(name, bayesdb_shellhookexp(func), autorehook=autorehook) return wrapper
<commit_before>import threading import contextlib the_current_shell = threading.local() the_current_shell.value = None @contextlib.contextmanager def set_current_shell(shell): outer = the_current_shell.value the_current_shell.value = shell try: yield finally: the_current_shell.value = outer def current_shell(): assert the_current_shell.value is not None, 'No current shell!' return the_current_shell.value def bayesdb_shell_cmd(name, autorehook=False): def wrapper(func): # because the cmd loop doesn't handle errors and just kicks people out def excepection_handling_func(*args, **kwargs): try: return func(*args, **kwargs) except Exception as err: print err current_shell()._hook(name, excepection_handling_func, autorehook=autorehook) return wrapper <commit_msg>Make sure that the wrapped function inherits doctring<commit_after>
import threading import contextlib the_current_shell = threading.local() the_current_shell.value = None @contextlib.contextmanager def set_current_shell(shell): outer = the_current_shell.value the_current_shell.value = shell try: yield finally: the_current_shell.value = outer def current_shell(): assert the_current_shell.value is not None, 'No current shell!' return the_current_shell.value # make sure that the function that is hooked by the shell has the same # __doc__ class bayesdb_shellhookexp(object): def __init__(self, func): self.func = func self.__doc__ = func.__doc__ def __call__(self, *args): try: return self.func(*args) except Exception as err: print err def bayesdb_shell_cmd(name, autorehook=False): def wrapper(func): # because the cmd loop doesn't handle errors and just kicks people out current_shell()._hook(name, bayesdb_shellhookexp(func), autorehook=autorehook) return wrapper
import threading import contextlib the_current_shell = threading.local() the_current_shell.value = None @contextlib.contextmanager def set_current_shell(shell): outer = the_current_shell.value the_current_shell.value = shell try: yield finally: the_current_shell.value = outer def current_shell(): assert the_current_shell.value is not None, 'No current shell!' return the_current_shell.value def bayesdb_shell_cmd(name, autorehook=False): def wrapper(func): # because the cmd loop doesn't handle errors and just kicks people out def excepection_handling_func(*args, **kwargs): try: return func(*args, **kwargs) except Exception as err: print err current_shell()._hook(name, excepection_handling_func, autorehook=autorehook) return wrapper Make sure that the wrapped function inherits doctringimport threading import contextlib the_current_shell = threading.local() the_current_shell.value = None @contextlib.contextmanager def set_current_shell(shell): outer = the_current_shell.value the_current_shell.value = shell try: yield finally: the_current_shell.value = outer def current_shell(): assert the_current_shell.value is not None, 'No current shell!' return the_current_shell.value # make sure that the function that is hooked by the shell has the same # __doc__ class bayesdb_shellhookexp(object): def __init__(self, func): self.func = func self.__doc__ = func.__doc__ def __call__(self, *args): try: return self.func(*args) except Exception as err: print err def bayesdb_shell_cmd(name, autorehook=False): def wrapper(func): # because the cmd loop doesn't handle errors and just kicks people out current_shell()._hook(name, bayesdb_shellhookexp(func), autorehook=autorehook) return wrapper
<commit_before>import threading import contextlib the_current_shell = threading.local() the_current_shell.value = None @contextlib.contextmanager def set_current_shell(shell): outer = the_current_shell.value the_current_shell.value = shell try: yield finally: the_current_shell.value = outer def current_shell(): assert the_current_shell.value is not None, 'No current shell!' return the_current_shell.value def bayesdb_shell_cmd(name, autorehook=False): def wrapper(func): # because the cmd loop doesn't handle errors and just kicks people out def excepection_handling_func(*args, **kwargs): try: return func(*args, **kwargs) except Exception as err: print err current_shell()._hook(name, excepection_handling_func, autorehook=autorehook) return wrapper <commit_msg>Make sure that the wrapped function inherits doctring<commit_after>import threading import contextlib the_current_shell = threading.local() the_current_shell.value = None @contextlib.contextmanager def set_current_shell(shell): outer = the_current_shell.value the_current_shell.value = shell try: yield finally: the_current_shell.value = outer def current_shell(): assert the_current_shell.value is not None, 'No current shell!' return the_current_shell.value # make sure that the function that is hooked by the shell has the same # __doc__ class bayesdb_shellhookexp(object): def __init__(self, func): self.func = func self.__doc__ = func.__doc__ def __call__(self, *args): try: return self.func(*args) except Exception as err: print err def bayesdb_shell_cmd(name, autorehook=False): def wrapper(func): # because the cmd loop doesn't handle errors and just kicks people out current_shell()._hook(name, bayesdb_shellhookexp(func), autorehook=autorehook) return wrapper
331ce5fde1a653997900f3e247f9d34a2c47fb54
projects/models.py
projects/models.py
# -*- coding: utf-8 from django.conf import settings from django.db import models class InlistItem(models.Model): text = models.CharField(max_length=255, default='') user = models.ForeignKey(settings.AUTH_USER_MODEL) def __str__(self): return self.text class Meta: unique_together = ('text', 'user')
# -*- coding: utf-8 from django.conf import settings from django.db import models class InlistItem(models.Model): text = models.CharField(max_length=255, default='') user = models.ForeignKey(settings.AUTH_USER_MODEL) def __str__(self): return self.text class Meta: unique_together = ('text', 'user') ordering = ('pk',)
Add explicit ordering to inlist items
Add explicit ordering to inlist items
Python
mit
XeryusTC/projman,XeryusTC/projman,XeryusTC/projman
# -*- coding: utf-8 from django.conf import settings from django.db import models class InlistItem(models.Model): text = models.CharField(max_length=255, default='') user = models.ForeignKey(settings.AUTH_USER_MODEL) def __str__(self): return self.text class Meta: unique_together = ('text', 'user') Add explicit ordering to inlist items
# -*- coding: utf-8 from django.conf import settings from django.db import models class InlistItem(models.Model): text = models.CharField(max_length=255, default='') user = models.ForeignKey(settings.AUTH_USER_MODEL) def __str__(self): return self.text class Meta: unique_together = ('text', 'user') ordering = ('pk',)
<commit_before># -*- coding: utf-8 from django.conf import settings from django.db import models class InlistItem(models.Model): text = models.CharField(max_length=255, default='') user = models.ForeignKey(settings.AUTH_USER_MODEL) def __str__(self): return self.text class Meta: unique_together = ('text', 'user') <commit_msg>Add explicit ordering to inlist items<commit_after>
# -*- coding: utf-8 from django.conf import settings from django.db import models class InlistItem(models.Model): text = models.CharField(max_length=255, default='') user = models.ForeignKey(settings.AUTH_USER_MODEL) def __str__(self): return self.text class Meta: unique_together = ('text', 'user') ordering = ('pk',)
# -*- coding: utf-8 from django.conf import settings from django.db import models class InlistItem(models.Model): text = models.CharField(max_length=255, default='') user = models.ForeignKey(settings.AUTH_USER_MODEL) def __str__(self): return self.text class Meta: unique_together = ('text', 'user') Add explicit ordering to inlist items# -*- coding: utf-8 from django.conf import settings from django.db import models class InlistItem(models.Model): text = models.CharField(max_length=255, default='') user = models.ForeignKey(settings.AUTH_USER_MODEL) def __str__(self): return self.text class Meta: unique_together = ('text', 'user') ordering = ('pk',)
<commit_before># -*- coding: utf-8 from django.conf import settings from django.db import models class InlistItem(models.Model): text = models.CharField(max_length=255, default='') user = models.ForeignKey(settings.AUTH_USER_MODEL) def __str__(self): return self.text class Meta: unique_together = ('text', 'user') <commit_msg>Add explicit ordering to inlist items<commit_after># -*- coding: utf-8 from django.conf import settings from django.db import models class InlistItem(models.Model): text = models.CharField(max_length=255, default='') user = models.ForeignKey(settings.AUTH_USER_MODEL) def __str__(self): return self.text class Meta: unique_together = ('text', 'user') ordering = ('pk',)
c23e697ccc64340027d3b07728032247bb5b21a4
kerze.py
kerze.py
from turtle import * GROESSE = 0.5 FARBE = "red" FAERBEN = True SHAPE = "turtle" fillcolor(FARBE) shape(SHAPE) def zeichneKerze(brennt): pd() begin_fill() forward(GROESSE*100) left(90) forward(GROESSE*400) left(90) forward(GROESSE*100) right(90) forward(GROESSE*30) back(GROESSE*30) left(90) forward(GROESSE*100) left(90) forward(GROESSE*400) left(90) forward(GROESSE*100) end_fill() pu() if brennt: zeichneFlamme() def zeichneFlamme(): left(90) fd(GROESSE*430) pd() color("yellow") dot(GROESSE*60) color("black") back(GROESSE*30) pu() home() if __name__=="__main__": zeichneKerze(True) hideturtle()
import turtle as t GROESSE = 0.5 FARBE = "red" FAERBEN = True SHAPE = "turtle" t.fillcolor(FARBE) t.shape(SHAPE) def zeichneKerze(brennt): t.pd() t.begin_fill() t.forward(GROESSE*100) t.left(90) t.forward(GROESSE*400) t.left(90) t.forward(GROESSE*100) t.right(90) t.forward(GROESSE*30) t.back(GROESSE*30) t.left(90) t.forward(GROESSE*100) t.left(90) t.forward(GROESSE*400) t.left(90) t.forward(GROESSE*100) t.end_fill() t.pu() if brennt: zeichneFlamme() def zeichneFlamme(): t.left(90) t.fd(GROESSE*430) t.pd() t.color("yellow") t.dot(GROESSE*60) t.color("black") t.back(GROESSE*30) t.pu() t.home() if __name__=="__main__": zeichneKerze(True) t.hideturtle()
Make imports compliant to PEP 8 suggestion
Make imports compliant to PEP 8 suggestion
Python
mit
luforst/adventskranz
from turtle import * GROESSE = 0.5 FARBE = "red" FAERBEN = True SHAPE = "turtle" fillcolor(FARBE) shape(SHAPE) def zeichneKerze(brennt): pd() begin_fill() forward(GROESSE*100) left(90) forward(GROESSE*400) left(90) forward(GROESSE*100) right(90) forward(GROESSE*30) back(GROESSE*30) left(90) forward(GROESSE*100) left(90) forward(GROESSE*400) left(90) forward(GROESSE*100) end_fill() pu() if brennt: zeichneFlamme() def zeichneFlamme(): left(90) fd(GROESSE*430) pd() color("yellow") dot(GROESSE*60) color("black") back(GROESSE*30) pu() home() if __name__=="__main__": zeichneKerze(True) hideturtle() Make imports compliant to PEP 8 suggestion
import turtle as t GROESSE = 0.5 FARBE = "red" FAERBEN = True SHAPE = "turtle" t.fillcolor(FARBE) t.shape(SHAPE) def zeichneKerze(brennt): t.pd() t.begin_fill() t.forward(GROESSE*100) t.left(90) t.forward(GROESSE*400) t.left(90) t.forward(GROESSE*100) t.right(90) t.forward(GROESSE*30) t.back(GROESSE*30) t.left(90) t.forward(GROESSE*100) t.left(90) t.forward(GROESSE*400) t.left(90) t.forward(GROESSE*100) t.end_fill() t.pu() if brennt: zeichneFlamme() def zeichneFlamme(): t.left(90) t.fd(GROESSE*430) t.pd() t.color("yellow") t.dot(GROESSE*60) t.color("black") t.back(GROESSE*30) t.pu() t.home() if __name__=="__main__": zeichneKerze(True) t.hideturtle()
<commit_before>from turtle import * GROESSE = 0.5 FARBE = "red" FAERBEN = True SHAPE = "turtle" fillcolor(FARBE) shape(SHAPE) def zeichneKerze(brennt): pd() begin_fill() forward(GROESSE*100) left(90) forward(GROESSE*400) left(90) forward(GROESSE*100) right(90) forward(GROESSE*30) back(GROESSE*30) left(90) forward(GROESSE*100) left(90) forward(GROESSE*400) left(90) forward(GROESSE*100) end_fill() pu() if brennt: zeichneFlamme() def zeichneFlamme(): left(90) fd(GROESSE*430) pd() color("yellow") dot(GROESSE*60) color("black") back(GROESSE*30) pu() home() if __name__=="__main__": zeichneKerze(True) hideturtle() <commit_msg>Make imports compliant to PEP 8 suggestion<commit_after>
import turtle as t GROESSE = 0.5 FARBE = "red" FAERBEN = True SHAPE = "turtle" t.fillcolor(FARBE) t.shape(SHAPE) def zeichneKerze(brennt): t.pd() t.begin_fill() t.forward(GROESSE*100) t.left(90) t.forward(GROESSE*400) t.left(90) t.forward(GROESSE*100) t.right(90) t.forward(GROESSE*30) t.back(GROESSE*30) t.left(90) t.forward(GROESSE*100) t.left(90) t.forward(GROESSE*400) t.left(90) t.forward(GROESSE*100) t.end_fill() t.pu() if brennt: zeichneFlamme() def zeichneFlamme(): t.left(90) t.fd(GROESSE*430) t.pd() t.color("yellow") t.dot(GROESSE*60) t.color("black") t.back(GROESSE*30) t.pu() t.home() if __name__=="__main__": zeichneKerze(True) t.hideturtle()
from turtle import * GROESSE = 0.5 FARBE = "red" FAERBEN = True SHAPE = "turtle" fillcolor(FARBE) shape(SHAPE) def zeichneKerze(brennt): pd() begin_fill() forward(GROESSE*100) left(90) forward(GROESSE*400) left(90) forward(GROESSE*100) right(90) forward(GROESSE*30) back(GROESSE*30) left(90) forward(GROESSE*100) left(90) forward(GROESSE*400) left(90) forward(GROESSE*100) end_fill() pu() if brennt: zeichneFlamme() def zeichneFlamme(): left(90) fd(GROESSE*430) pd() color("yellow") dot(GROESSE*60) color("black") back(GROESSE*30) pu() home() if __name__=="__main__": zeichneKerze(True) hideturtle() Make imports compliant to PEP 8 suggestionimport turtle as t GROESSE = 0.5 FARBE = "red" FAERBEN = True SHAPE = "turtle" t.fillcolor(FARBE) t.shape(SHAPE) def zeichneKerze(brennt): t.pd() t.begin_fill() t.forward(GROESSE*100) t.left(90) t.forward(GROESSE*400) t.left(90) t.forward(GROESSE*100) t.right(90) t.forward(GROESSE*30) t.back(GROESSE*30) t.left(90) t.forward(GROESSE*100) t.left(90) t.forward(GROESSE*400) t.left(90) t.forward(GROESSE*100) t.end_fill() t.pu() if brennt: zeichneFlamme() def zeichneFlamme(): t.left(90) t.fd(GROESSE*430) t.pd() t.color("yellow") t.dot(GROESSE*60) t.color("black") t.back(GROESSE*30) t.pu() t.home() if __name__=="__main__": zeichneKerze(True) t.hideturtle()
<commit_before>from turtle import * GROESSE = 0.5 FARBE = "red" FAERBEN = True SHAPE = "turtle" fillcolor(FARBE) shape(SHAPE) def zeichneKerze(brennt): pd() begin_fill() forward(GROESSE*100) left(90) forward(GROESSE*400) left(90) forward(GROESSE*100) right(90) forward(GROESSE*30) back(GROESSE*30) left(90) forward(GROESSE*100) left(90) forward(GROESSE*400) left(90) forward(GROESSE*100) end_fill() pu() if brennt: zeichneFlamme() def zeichneFlamme(): left(90) fd(GROESSE*430) pd() color("yellow") dot(GROESSE*60) color("black") back(GROESSE*30) pu() home() if __name__=="__main__": zeichneKerze(True) hideturtle() <commit_msg>Make imports compliant to PEP 8 suggestion<commit_after>import turtle as t GROESSE = 0.5 FARBE = "red" FAERBEN = True SHAPE = "turtle" t.fillcolor(FARBE) t.shape(SHAPE) def zeichneKerze(brennt): t.pd() t.begin_fill() t.forward(GROESSE*100) t.left(90) t.forward(GROESSE*400) t.left(90) t.forward(GROESSE*100) t.right(90) t.forward(GROESSE*30) t.back(GROESSE*30) t.left(90) t.forward(GROESSE*100) t.left(90) t.forward(GROESSE*400) t.left(90) t.forward(GROESSE*100) t.end_fill() t.pu() if brennt: zeichneFlamme() def zeichneFlamme(): t.left(90) t.fd(GROESSE*430) t.pd() t.color("yellow") t.dot(GROESSE*60) t.color("black") t.back(GROESSE*30) t.pu() t.home() if __name__=="__main__": zeichneKerze(True) t.hideturtle()