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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9810935ce1e9b871659148630742bda888c71408 | py/capnp/setup.py | py/capnp/setup.py | from setuptools import setup
from setuptools.extension import Extension
import buildtools
# You might also need to set PKG_CONFIG_PATH=/path/to/lib/pkgconfig if
# your capnp is installed in a non-default location
CAPNP = buildtools.read_pkg_config(['capnp'])
setup(
name = 'capnp',
packages = [
'capnp',
],
ext_modules = [
Extension(
'capnp.native',
language = 'c++',
sources = [
'src/module.cc',
'src/schema.cc',
'src/resource-types.cc',
'src/value-types.cc',
],
include_dirs = CAPNP.include_dirs,
library_dirs = CAPNP.library_dirs,
libraries = ['boost_python3'] + CAPNP.libraries,
extra_compile_args = ['-std=c++11'] + CAPNP.extra_compile_args,
),
],
)
| from setuptools import setup
from setuptools.extension import Extension
import buildtools
# You might also need to set PKG_CONFIG_PATH=/path/to/lib/pkgconfig if
# your capnp is installed in a non-default location
CAPNP = buildtools.read_pkg_config(['capnp'])
setup(
name = 'capnp',
packages = [
'capnp',
],
ext_modules = [
Extension(
'capnp.native',
language = 'c++',
sources = [
'src/module.cc',
'src/schema.cc',
'src/resource-types.cc',
'src/value-types.cc',
],
include_dirs = CAPNP.include_dirs,
library_dirs = CAPNP.library_dirs,
libraries = ['boost_python37'] + CAPNP.libraries,
extra_compile_args = ['-std=c++11'] + CAPNP.extra_compile_args,
),
],
)
| Fix py/capnp build for python 3.7 | Fix py/capnp build for python 3.7
| Python | mit | clchiou/garage,clchiou/garage,clchiou/garage,clchiou/garage | from setuptools import setup
from setuptools.extension import Extension
import buildtools
# You might also need to set PKG_CONFIG_PATH=/path/to/lib/pkgconfig if
# your capnp is installed in a non-default location
CAPNP = buildtools.read_pkg_config(['capnp'])
setup(
name = 'capnp',
packages = [
'capnp',
],
ext_modules = [
Extension(
'capnp.native',
language = 'c++',
sources = [
'src/module.cc',
'src/schema.cc',
'src/resource-types.cc',
'src/value-types.cc',
],
include_dirs = CAPNP.include_dirs,
library_dirs = CAPNP.library_dirs,
libraries = ['boost_python3'] + CAPNP.libraries,
extra_compile_args = ['-std=c++11'] + CAPNP.extra_compile_args,
),
],
)
Fix py/capnp build for python 3.7 | from setuptools import setup
from setuptools.extension import Extension
import buildtools
# You might also need to set PKG_CONFIG_PATH=/path/to/lib/pkgconfig if
# your capnp is installed in a non-default location
CAPNP = buildtools.read_pkg_config(['capnp'])
setup(
name = 'capnp',
packages = [
'capnp',
],
ext_modules = [
Extension(
'capnp.native',
language = 'c++',
sources = [
'src/module.cc',
'src/schema.cc',
'src/resource-types.cc',
'src/value-types.cc',
],
include_dirs = CAPNP.include_dirs,
library_dirs = CAPNP.library_dirs,
libraries = ['boost_python37'] + CAPNP.libraries,
extra_compile_args = ['-std=c++11'] + CAPNP.extra_compile_args,
),
],
)
| <commit_before>from setuptools import setup
from setuptools.extension import Extension
import buildtools
# You might also need to set PKG_CONFIG_PATH=/path/to/lib/pkgconfig if
# your capnp is installed in a non-default location
CAPNP = buildtools.read_pkg_config(['capnp'])
setup(
name = 'capnp',
packages = [
'capnp',
],
ext_modules = [
Extension(
'capnp.native',
language = 'c++',
sources = [
'src/module.cc',
'src/schema.cc',
'src/resource-types.cc',
'src/value-types.cc',
],
include_dirs = CAPNP.include_dirs,
library_dirs = CAPNP.library_dirs,
libraries = ['boost_python3'] + CAPNP.libraries,
extra_compile_args = ['-std=c++11'] + CAPNP.extra_compile_args,
),
],
)
<commit_msg>Fix py/capnp build for python 3.7<commit_after> | from setuptools import setup
from setuptools.extension import Extension
import buildtools
# You might also need to set PKG_CONFIG_PATH=/path/to/lib/pkgconfig if
# your capnp is installed in a non-default location
CAPNP = buildtools.read_pkg_config(['capnp'])
setup(
name = 'capnp',
packages = [
'capnp',
],
ext_modules = [
Extension(
'capnp.native',
language = 'c++',
sources = [
'src/module.cc',
'src/schema.cc',
'src/resource-types.cc',
'src/value-types.cc',
],
include_dirs = CAPNP.include_dirs,
library_dirs = CAPNP.library_dirs,
libraries = ['boost_python37'] + CAPNP.libraries,
extra_compile_args = ['-std=c++11'] + CAPNP.extra_compile_args,
),
],
)
| from setuptools import setup
from setuptools.extension import Extension
import buildtools
# You might also need to set PKG_CONFIG_PATH=/path/to/lib/pkgconfig if
# your capnp is installed in a non-default location
CAPNP = buildtools.read_pkg_config(['capnp'])
setup(
name = 'capnp',
packages = [
'capnp',
],
ext_modules = [
Extension(
'capnp.native',
language = 'c++',
sources = [
'src/module.cc',
'src/schema.cc',
'src/resource-types.cc',
'src/value-types.cc',
],
include_dirs = CAPNP.include_dirs,
library_dirs = CAPNP.library_dirs,
libraries = ['boost_python3'] + CAPNP.libraries,
extra_compile_args = ['-std=c++11'] + CAPNP.extra_compile_args,
),
],
)
Fix py/capnp build for python 3.7from setuptools import setup
from setuptools.extension import Extension
import buildtools
# You might also need to set PKG_CONFIG_PATH=/path/to/lib/pkgconfig if
# your capnp is installed in a non-default location
CAPNP = buildtools.read_pkg_config(['capnp'])
setup(
name = 'capnp',
packages = [
'capnp',
],
ext_modules = [
Extension(
'capnp.native',
language = 'c++',
sources = [
'src/module.cc',
'src/schema.cc',
'src/resource-types.cc',
'src/value-types.cc',
],
include_dirs = CAPNP.include_dirs,
library_dirs = CAPNP.library_dirs,
libraries = ['boost_python37'] + CAPNP.libraries,
extra_compile_args = ['-std=c++11'] + CAPNP.extra_compile_args,
),
],
)
| <commit_before>from setuptools import setup
from setuptools.extension import Extension
import buildtools
# You might also need to set PKG_CONFIG_PATH=/path/to/lib/pkgconfig if
# your capnp is installed in a non-default location
CAPNP = buildtools.read_pkg_config(['capnp'])
setup(
name = 'capnp',
packages = [
'capnp',
],
ext_modules = [
Extension(
'capnp.native',
language = 'c++',
sources = [
'src/module.cc',
'src/schema.cc',
'src/resource-types.cc',
'src/value-types.cc',
],
include_dirs = CAPNP.include_dirs,
library_dirs = CAPNP.library_dirs,
libraries = ['boost_python3'] + CAPNP.libraries,
extra_compile_args = ['-std=c++11'] + CAPNP.extra_compile_args,
),
],
)
<commit_msg>Fix py/capnp build for python 3.7<commit_after>from setuptools import setup
from setuptools.extension import Extension
import buildtools
# You might also need to set PKG_CONFIG_PATH=/path/to/lib/pkgconfig if
# your capnp is installed in a non-default location
CAPNP = buildtools.read_pkg_config(['capnp'])
setup(
name = 'capnp',
packages = [
'capnp',
],
ext_modules = [
Extension(
'capnp.native',
language = 'c++',
sources = [
'src/module.cc',
'src/schema.cc',
'src/resource-types.cc',
'src/value-types.cc',
],
include_dirs = CAPNP.include_dirs,
library_dirs = CAPNP.library_dirs,
libraries = ['boost_python37'] + CAPNP.libraries,
extra_compile_args = ['-std=c++11'] + CAPNP.extra_compile_args,
),
],
)
|
fb0fa15ce9618aac58f45fee0ecda852f3b00ed6 | testdoc/tests/test_finder.py | testdoc/tests/test_finder.py | import unittest
from testdoc.finder import find_tests
class MockFinder(object):
def __init__(self):
self.log = []
def got_module(self, module):
self.log.append(('module', module))
def got_test_class(self, klass):
self.log.append(('class', klass))
def got_test(self, method):
self.log.append(('method', method))
class TestFinder(unittest.TestCase):
def setUp(self):
self.finder = MockFinder()
def test_empty(self):
from testdoc.tests import empty
find_tests(self.finder, empty)
self.assertEqual(self.finder.log, [('module', empty)])
def test_hasemptycase(self):
from testdoc.tests import hasemptycase
find_tests(self.finder, hasemptycase)
self.assertEqual(
self.finder.log, [
('module', hasemptycase),
('class', hasemptycase.SomeTest)])
def test_hastests(self):
from testdoc.tests import hastests
find_tests(self.finder, hastests)
self.assertEqual(
self.finder.log, [
('module', hastests),
('class', hastests.SomeTest),
('method', hastests.SomeTest.test_foo_handles_qux),
('method', hastests.SomeTest.test_bar),
('class', hastests.AnotherTest),
('method', hastests.AnotherTest.test_baz)])
| import unittest
from testdoc.finder import find_tests
class MockCollector(object):
def __init__(self):
self.log = []
def got_module(self, module):
self.log.append(('module', module))
def got_test_class(self, klass):
self.log.append(('class', klass))
def got_test(self, method):
self.log.append(('method', method))
class TestPassiveFinder(unittest.TestCase):
"""One approach to finding tests is to look inside a module for test
classes and then look inside those test classes for test methods. The
default finder uses this approach.
"""
def setUp(self):
self.collector = MockCollector()
def test_empty(self):
from testdoc.tests import empty
find_tests(self.collector, empty)
self.assertEqual(self.collector.log, [('module', empty)])
def test_hasemptycase(self):
from testdoc.tests import hasemptycase
find_tests(self.collector, hasemptycase)
self.assertEqual(
self.collector.log, [
('module', hasemptycase),
('class', hasemptycase.SomeTest)])
def test_hastests(self):
from testdoc.tests import hastests
find_tests(self.collector, hastests)
self.assertEqual(
self.collector.log, [
('module', hastests),
('class', hastests.SomeTest),
('method', hastests.SomeTest.test_foo_handles_qux),
('method', hastests.SomeTest.test_bar),
('class', hastests.AnotherTest),
('method', hastests.AnotherTest.test_baz)])
| Document finder tests better and use better terminology (the thing that collects found objects isn't a finder, it's a collector) | Document finder tests better and use better terminology (the thing that
collects found objects isn't a finder, it's a collector)
| Python | mit | testing-cabal/testdoc | import unittest
from testdoc.finder import find_tests
class MockFinder(object):
def __init__(self):
self.log = []
def got_module(self, module):
self.log.append(('module', module))
def got_test_class(self, klass):
self.log.append(('class', klass))
def got_test(self, method):
self.log.append(('method', method))
class TestFinder(unittest.TestCase):
def setUp(self):
self.finder = MockFinder()
def test_empty(self):
from testdoc.tests import empty
find_tests(self.finder, empty)
self.assertEqual(self.finder.log, [('module', empty)])
def test_hasemptycase(self):
from testdoc.tests import hasemptycase
find_tests(self.finder, hasemptycase)
self.assertEqual(
self.finder.log, [
('module', hasemptycase),
('class', hasemptycase.SomeTest)])
def test_hastests(self):
from testdoc.tests import hastests
find_tests(self.finder, hastests)
self.assertEqual(
self.finder.log, [
('module', hastests),
('class', hastests.SomeTest),
('method', hastests.SomeTest.test_foo_handles_qux),
('method', hastests.SomeTest.test_bar),
('class', hastests.AnotherTest),
('method', hastests.AnotherTest.test_baz)])
Document finder tests better and use better terminology (the thing that
collects found objects isn't a finder, it's a collector) | import unittest
from testdoc.finder import find_tests
class MockCollector(object):
def __init__(self):
self.log = []
def got_module(self, module):
self.log.append(('module', module))
def got_test_class(self, klass):
self.log.append(('class', klass))
def got_test(self, method):
self.log.append(('method', method))
class TestPassiveFinder(unittest.TestCase):
"""One approach to finding tests is to look inside a module for test
classes and then look inside those test classes for test methods. The
default finder uses this approach.
"""
def setUp(self):
self.collector = MockCollector()
def test_empty(self):
from testdoc.tests import empty
find_tests(self.collector, empty)
self.assertEqual(self.collector.log, [('module', empty)])
def test_hasemptycase(self):
from testdoc.tests import hasemptycase
find_tests(self.collector, hasemptycase)
self.assertEqual(
self.collector.log, [
('module', hasemptycase),
('class', hasemptycase.SomeTest)])
def test_hastests(self):
from testdoc.tests import hastests
find_tests(self.collector, hastests)
self.assertEqual(
self.collector.log, [
('module', hastests),
('class', hastests.SomeTest),
('method', hastests.SomeTest.test_foo_handles_qux),
('method', hastests.SomeTest.test_bar),
('class', hastests.AnotherTest),
('method', hastests.AnotherTest.test_baz)])
| <commit_before>import unittest
from testdoc.finder import find_tests
class MockFinder(object):
def __init__(self):
self.log = []
def got_module(self, module):
self.log.append(('module', module))
def got_test_class(self, klass):
self.log.append(('class', klass))
def got_test(self, method):
self.log.append(('method', method))
class TestFinder(unittest.TestCase):
def setUp(self):
self.finder = MockFinder()
def test_empty(self):
from testdoc.tests import empty
find_tests(self.finder, empty)
self.assertEqual(self.finder.log, [('module', empty)])
def test_hasemptycase(self):
from testdoc.tests import hasemptycase
find_tests(self.finder, hasemptycase)
self.assertEqual(
self.finder.log, [
('module', hasemptycase),
('class', hasemptycase.SomeTest)])
def test_hastests(self):
from testdoc.tests import hastests
find_tests(self.finder, hastests)
self.assertEqual(
self.finder.log, [
('module', hastests),
('class', hastests.SomeTest),
('method', hastests.SomeTest.test_foo_handles_qux),
('method', hastests.SomeTest.test_bar),
('class', hastests.AnotherTest),
('method', hastests.AnotherTest.test_baz)])
<commit_msg>Document finder tests better and use better terminology (the thing that
collects found objects isn't a finder, it's a collector)<commit_after> | import unittest
from testdoc.finder import find_tests
class MockCollector(object):
def __init__(self):
self.log = []
def got_module(self, module):
self.log.append(('module', module))
def got_test_class(self, klass):
self.log.append(('class', klass))
def got_test(self, method):
self.log.append(('method', method))
class TestPassiveFinder(unittest.TestCase):
"""One approach to finding tests is to look inside a module for test
classes and then look inside those test classes for test methods. The
default finder uses this approach.
"""
def setUp(self):
self.collector = MockCollector()
def test_empty(self):
from testdoc.tests import empty
find_tests(self.collector, empty)
self.assertEqual(self.collector.log, [('module', empty)])
def test_hasemptycase(self):
from testdoc.tests import hasemptycase
find_tests(self.collector, hasemptycase)
self.assertEqual(
self.collector.log, [
('module', hasemptycase),
('class', hasemptycase.SomeTest)])
def test_hastests(self):
from testdoc.tests import hastests
find_tests(self.collector, hastests)
self.assertEqual(
self.collector.log, [
('module', hastests),
('class', hastests.SomeTest),
('method', hastests.SomeTest.test_foo_handles_qux),
('method', hastests.SomeTest.test_bar),
('class', hastests.AnotherTest),
('method', hastests.AnotherTest.test_baz)])
| import unittest
from testdoc.finder import find_tests
class MockFinder(object):
def __init__(self):
self.log = []
def got_module(self, module):
self.log.append(('module', module))
def got_test_class(self, klass):
self.log.append(('class', klass))
def got_test(self, method):
self.log.append(('method', method))
class TestFinder(unittest.TestCase):
def setUp(self):
self.finder = MockFinder()
def test_empty(self):
from testdoc.tests import empty
find_tests(self.finder, empty)
self.assertEqual(self.finder.log, [('module', empty)])
def test_hasemptycase(self):
from testdoc.tests import hasemptycase
find_tests(self.finder, hasemptycase)
self.assertEqual(
self.finder.log, [
('module', hasemptycase),
('class', hasemptycase.SomeTest)])
def test_hastests(self):
from testdoc.tests import hastests
find_tests(self.finder, hastests)
self.assertEqual(
self.finder.log, [
('module', hastests),
('class', hastests.SomeTest),
('method', hastests.SomeTest.test_foo_handles_qux),
('method', hastests.SomeTest.test_bar),
('class', hastests.AnotherTest),
('method', hastests.AnotherTest.test_baz)])
Document finder tests better and use better terminology (the thing that
collects found objects isn't a finder, it's a collector)import unittest
from testdoc.finder import find_tests
class MockCollector(object):
def __init__(self):
self.log = []
def got_module(self, module):
self.log.append(('module', module))
def got_test_class(self, klass):
self.log.append(('class', klass))
def got_test(self, method):
self.log.append(('method', method))
class TestPassiveFinder(unittest.TestCase):
"""One approach to finding tests is to look inside a module for test
classes and then look inside those test classes for test methods. The
default finder uses this approach.
"""
def setUp(self):
self.collector = MockCollector()
def test_empty(self):
from testdoc.tests import empty
find_tests(self.collector, empty)
self.assertEqual(self.collector.log, [('module', empty)])
def test_hasemptycase(self):
from testdoc.tests import hasemptycase
find_tests(self.collector, hasemptycase)
self.assertEqual(
self.collector.log, [
('module', hasemptycase),
('class', hasemptycase.SomeTest)])
def test_hastests(self):
from testdoc.tests import hastests
find_tests(self.collector, hastests)
self.assertEqual(
self.collector.log, [
('module', hastests),
('class', hastests.SomeTest),
('method', hastests.SomeTest.test_foo_handles_qux),
('method', hastests.SomeTest.test_bar),
('class', hastests.AnotherTest),
('method', hastests.AnotherTest.test_baz)])
| <commit_before>import unittest
from testdoc.finder import find_tests
class MockFinder(object):
def __init__(self):
self.log = []
def got_module(self, module):
self.log.append(('module', module))
def got_test_class(self, klass):
self.log.append(('class', klass))
def got_test(self, method):
self.log.append(('method', method))
class TestFinder(unittest.TestCase):
def setUp(self):
self.finder = MockFinder()
def test_empty(self):
from testdoc.tests import empty
find_tests(self.finder, empty)
self.assertEqual(self.finder.log, [('module', empty)])
def test_hasemptycase(self):
from testdoc.tests import hasemptycase
find_tests(self.finder, hasemptycase)
self.assertEqual(
self.finder.log, [
('module', hasemptycase),
('class', hasemptycase.SomeTest)])
def test_hastests(self):
from testdoc.tests import hastests
find_tests(self.finder, hastests)
self.assertEqual(
self.finder.log, [
('module', hastests),
('class', hastests.SomeTest),
('method', hastests.SomeTest.test_foo_handles_qux),
('method', hastests.SomeTest.test_bar),
('class', hastests.AnotherTest),
('method', hastests.AnotherTest.test_baz)])
<commit_msg>Document finder tests better and use better terminology (the thing that
collects found objects isn't a finder, it's a collector)<commit_after>import unittest
from testdoc.finder import find_tests
class MockCollector(object):
def __init__(self):
self.log = []
def got_module(self, module):
self.log.append(('module', module))
def got_test_class(self, klass):
self.log.append(('class', klass))
def got_test(self, method):
self.log.append(('method', method))
class TestPassiveFinder(unittest.TestCase):
"""One approach to finding tests is to look inside a module for test
classes and then look inside those test classes for test methods. The
default finder uses this approach.
"""
def setUp(self):
self.collector = MockCollector()
def test_empty(self):
from testdoc.tests import empty
find_tests(self.collector, empty)
self.assertEqual(self.collector.log, [('module', empty)])
def test_hasemptycase(self):
from testdoc.tests import hasemptycase
find_tests(self.collector, hasemptycase)
self.assertEqual(
self.collector.log, [
('module', hasemptycase),
('class', hasemptycase.SomeTest)])
def test_hastests(self):
from testdoc.tests import hastests
find_tests(self.collector, hastests)
self.assertEqual(
self.collector.log, [
('module', hastests),
('class', hastests.SomeTest),
('method', hastests.SomeTest.test_foo_handles_qux),
('method', hastests.SomeTest.test_bar),
('class', hastests.AnotherTest),
('method', hastests.AnotherTest.test_baz)])
|
1e6aeb9c7b07313a9efe7cb0e1380f4f2219c7dc | tests/utils.py | tests/utils.py | import os
from carrot.connection import BrokerConnection
AMQP_HOST = os.environ.get('AMQP_HOST', "localhost")
AMQP_PORT = os.environ.get('AMQP_PORT', 5672)
AMQP_VHOST = os.environ.get('AMQP_VHOST', "/")
AMQP_USER = os.environ.get('AMQP_USER', "guest")
AMQP_PASSWORD = os.environ.get('AMQP_PASSWORD', "guest")
STOMP_HOST = os.environ.get('STOMP_HOST', 'localhost')
STOMP_PORT = os.environ.get('STOMP_PORT', 61613)
def test_connection_args():
return {"hostname": AMQP_HOST, "port": AMQP_PORT,
"virtual_host": AMQP_VHOST, "userid": AMQP_USER,
"password": AMQP_PASSWORD}
def test_stomp_connection_args():
return {"hostname": STOMP_HOST, "port": STOMP_PORT}
def establish_test_connection():
return BrokerConnection(**test_connection_args())
| import os
from carrot.connection import BrokerConnection
AMQP_HOST = os.environ.get('AMQP_HOST', "localhost")
AMQP_PORT = os.environ.get('AMQP_PORT', 5672)
AMQP_VHOST = os.environ.get('AMQP_VHOST', "/")
AMQP_USER = os.environ.get('AMQP_USER', "guest")
AMQP_PASSWORD = os.environ.get('AMQP_PASSWORD', "guest")
STOMP_HOST = os.environ.get('STOMP_HOST', 'localhost')
STOMP_PORT = os.environ.get('STOMP_PORT', 61613)
STOMP_QUEUE = os.environ.get('STOMP_QUEUE', '/queue/testcarrot')
def test_connection_args():
return {"hostname": AMQP_HOST, "port": AMQP_PORT,
"virtual_host": AMQP_VHOST, "userid": AMQP_USER,
"password": AMQP_PASSWORD}
def test_stomp_connection_args():
return {"hostname": STOMP_HOST, "port": STOMP_PORT}
def establish_test_connection():
return BrokerConnection(**test_connection_args())
| Add test configuration vars: STOMP_HOST + STOMP_PORT | Add test configuration vars: STOMP_HOST + STOMP_PORT
| Python | bsd-3-clause | ask/carrot,ask/carrot | import os
from carrot.connection import BrokerConnection
AMQP_HOST = os.environ.get('AMQP_HOST', "localhost")
AMQP_PORT = os.environ.get('AMQP_PORT', 5672)
AMQP_VHOST = os.environ.get('AMQP_VHOST', "/")
AMQP_USER = os.environ.get('AMQP_USER', "guest")
AMQP_PASSWORD = os.environ.get('AMQP_PASSWORD', "guest")
STOMP_HOST = os.environ.get('STOMP_HOST', 'localhost')
STOMP_PORT = os.environ.get('STOMP_PORT', 61613)
def test_connection_args():
return {"hostname": AMQP_HOST, "port": AMQP_PORT,
"virtual_host": AMQP_VHOST, "userid": AMQP_USER,
"password": AMQP_PASSWORD}
def test_stomp_connection_args():
return {"hostname": STOMP_HOST, "port": STOMP_PORT}
def establish_test_connection():
return BrokerConnection(**test_connection_args())
Add test configuration vars: STOMP_HOST + STOMP_PORT | import os
from carrot.connection import BrokerConnection
AMQP_HOST = os.environ.get('AMQP_HOST', "localhost")
AMQP_PORT = os.environ.get('AMQP_PORT', 5672)
AMQP_VHOST = os.environ.get('AMQP_VHOST', "/")
AMQP_USER = os.environ.get('AMQP_USER', "guest")
AMQP_PASSWORD = os.environ.get('AMQP_PASSWORD', "guest")
STOMP_HOST = os.environ.get('STOMP_HOST', 'localhost')
STOMP_PORT = os.environ.get('STOMP_PORT', 61613)
STOMP_QUEUE = os.environ.get('STOMP_QUEUE', '/queue/testcarrot')
def test_connection_args():
return {"hostname": AMQP_HOST, "port": AMQP_PORT,
"virtual_host": AMQP_VHOST, "userid": AMQP_USER,
"password": AMQP_PASSWORD}
def test_stomp_connection_args():
return {"hostname": STOMP_HOST, "port": STOMP_PORT}
def establish_test_connection():
return BrokerConnection(**test_connection_args())
| <commit_before>import os
from carrot.connection import BrokerConnection
AMQP_HOST = os.environ.get('AMQP_HOST', "localhost")
AMQP_PORT = os.environ.get('AMQP_PORT', 5672)
AMQP_VHOST = os.environ.get('AMQP_VHOST', "/")
AMQP_USER = os.environ.get('AMQP_USER', "guest")
AMQP_PASSWORD = os.environ.get('AMQP_PASSWORD', "guest")
STOMP_HOST = os.environ.get('STOMP_HOST', 'localhost')
STOMP_PORT = os.environ.get('STOMP_PORT', 61613)
def test_connection_args():
return {"hostname": AMQP_HOST, "port": AMQP_PORT,
"virtual_host": AMQP_VHOST, "userid": AMQP_USER,
"password": AMQP_PASSWORD}
def test_stomp_connection_args():
return {"hostname": STOMP_HOST, "port": STOMP_PORT}
def establish_test_connection():
return BrokerConnection(**test_connection_args())
<commit_msg>Add test configuration vars: STOMP_HOST + STOMP_PORT<commit_after> | import os
from carrot.connection import BrokerConnection
AMQP_HOST = os.environ.get('AMQP_HOST', "localhost")
AMQP_PORT = os.environ.get('AMQP_PORT', 5672)
AMQP_VHOST = os.environ.get('AMQP_VHOST', "/")
AMQP_USER = os.environ.get('AMQP_USER', "guest")
AMQP_PASSWORD = os.environ.get('AMQP_PASSWORD', "guest")
STOMP_HOST = os.environ.get('STOMP_HOST', 'localhost')
STOMP_PORT = os.environ.get('STOMP_PORT', 61613)
STOMP_QUEUE = os.environ.get('STOMP_QUEUE', '/queue/testcarrot')
def test_connection_args():
return {"hostname": AMQP_HOST, "port": AMQP_PORT,
"virtual_host": AMQP_VHOST, "userid": AMQP_USER,
"password": AMQP_PASSWORD}
def test_stomp_connection_args():
return {"hostname": STOMP_HOST, "port": STOMP_PORT}
def establish_test_connection():
return BrokerConnection(**test_connection_args())
| import os
from carrot.connection import BrokerConnection
AMQP_HOST = os.environ.get('AMQP_HOST', "localhost")
AMQP_PORT = os.environ.get('AMQP_PORT', 5672)
AMQP_VHOST = os.environ.get('AMQP_VHOST', "/")
AMQP_USER = os.environ.get('AMQP_USER', "guest")
AMQP_PASSWORD = os.environ.get('AMQP_PASSWORD', "guest")
STOMP_HOST = os.environ.get('STOMP_HOST', 'localhost')
STOMP_PORT = os.environ.get('STOMP_PORT', 61613)
def test_connection_args():
return {"hostname": AMQP_HOST, "port": AMQP_PORT,
"virtual_host": AMQP_VHOST, "userid": AMQP_USER,
"password": AMQP_PASSWORD}
def test_stomp_connection_args():
return {"hostname": STOMP_HOST, "port": STOMP_PORT}
def establish_test_connection():
return BrokerConnection(**test_connection_args())
Add test configuration vars: STOMP_HOST + STOMP_PORTimport os
from carrot.connection import BrokerConnection
AMQP_HOST = os.environ.get('AMQP_HOST', "localhost")
AMQP_PORT = os.environ.get('AMQP_PORT', 5672)
AMQP_VHOST = os.environ.get('AMQP_VHOST', "/")
AMQP_USER = os.environ.get('AMQP_USER', "guest")
AMQP_PASSWORD = os.environ.get('AMQP_PASSWORD', "guest")
STOMP_HOST = os.environ.get('STOMP_HOST', 'localhost')
STOMP_PORT = os.environ.get('STOMP_PORT', 61613)
STOMP_QUEUE = os.environ.get('STOMP_QUEUE', '/queue/testcarrot')
def test_connection_args():
return {"hostname": AMQP_HOST, "port": AMQP_PORT,
"virtual_host": AMQP_VHOST, "userid": AMQP_USER,
"password": AMQP_PASSWORD}
def test_stomp_connection_args():
return {"hostname": STOMP_HOST, "port": STOMP_PORT}
def establish_test_connection():
return BrokerConnection(**test_connection_args())
| <commit_before>import os
from carrot.connection import BrokerConnection
AMQP_HOST = os.environ.get('AMQP_HOST', "localhost")
AMQP_PORT = os.environ.get('AMQP_PORT', 5672)
AMQP_VHOST = os.environ.get('AMQP_VHOST', "/")
AMQP_USER = os.environ.get('AMQP_USER', "guest")
AMQP_PASSWORD = os.environ.get('AMQP_PASSWORD', "guest")
STOMP_HOST = os.environ.get('STOMP_HOST', 'localhost')
STOMP_PORT = os.environ.get('STOMP_PORT', 61613)
def test_connection_args():
return {"hostname": AMQP_HOST, "port": AMQP_PORT,
"virtual_host": AMQP_VHOST, "userid": AMQP_USER,
"password": AMQP_PASSWORD}
def test_stomp_connection_args():
return {"hostname": STOMP_HOST, "port": STOMP_PORT}
def establish_test_connection():
return BrokerConnection(**test_connection_args())
<commit_msg>Add test configuration vars: STOMP_HOST + STOMP_PORT<commit_after>import os
from carrot.connection import BrokerConnection
AMQP_HOST = os.environ.get('AMQP_HOST', "localhost")
AMQP_PORT = os.environ.get('AMQP_PORT', 5672)
AMQP_VHOST = os.environ.get('AMQP_VHOST', "/")
AMQP_USER = os.environ.get('AMQP_USER', "guest")
AMQP_PASSWORD = os.environ.get('AMQP_PASSWORD', "guest")
STOMP_HOST = os.environ.get('STOMP_HOST', 'localhost')
STOMP_PORT = os.environ.get('STOMP_PORT', 61613)
STOMP_QUEUE = os.environ.get('STOMP_QUEUE', '/queue/testcarrot')
def test_connection_args():
return {"hostname": AMQP_HOST, "port": AMQP_PORT,
"virtual_host": AMQP_VHOST, "userid": AMQP_USER,
"password": AMQP_PASSWORD}
def test_stomp_connection_args():
return {"hostname": STOMP_HOST, "port": STOMP_PORT}
def establish_test_connection():
return BrokerConnection(**test_connection_args())
|
77fbacc85450e77ada5ac2c9c5ecc581ea2b480c | src/artgraph/plugins/infobox.py | src/artgraph/plugins/infobox.py | from artgraph.plugins.plugin import Plugin
class InfoboxPlugin(Plugin):
def __init__(self, node):
self._node = node
def get_nodes(self):
from artgraph.node import Node, NodeTypes
from artgraph.relationship import AssociatedActRelationship
wikicode = self.get_wikicode(self._node.get_dbtitle())
templates = wikicode.filter_templates()
relationships = []
for t in templates:
if t.name.matches('Infobox musical artist'):
associated_acts = t.get('associated_acts')
for w in associated_acts.value.filter_wikilinks():
relationships.append(AssociatedActRelationship(self._node, Node(w.title, NodeTypes.ARTIST)))
return relationships
| from artgraph.plugins.plugin import Plugin
class InfoboxPlugin(Plugin):
def __init__(self, node):
self._node = node
def get_nodes(self):
from artgraph.node import Node, NodeTypes
from artgraph.relationship import AssociatedActRelationship
wikicode = self.get_wikicode(self._node.get_dbtitle())
templates = wikicode.filter_templates()
relationships = []
for t in templates:
if t.name.matches('Infobox musical artist'):
associated_acts = t.get('associated_acts')
for w in associated_acts.value.filter_wikilinks():
relationships.append(AssociatedActRelationship(self._node, Node(str(w.title), NodeTypes.ARTIST)))
return relationships
| Use string as node title instead of wikicode | Use string as node title instead of wikicode | Python | mit | dMaggot/ArtistGraph | from artgraph.plugins.plugin import Plugin
class InfoboxPlugin(Plugin):
def __init__(self, node):
self._node = node
def get_nodes(self):
from artgraph.node import Node, NodeTypes
from artgraph.relationship import AssociatedActRelationship
wikicode = self.get_wikicode(self._node.get_dbtitle())
templates = wikicode.filter_templates()
relationships = []
for t in templates:
if t.name.matches('Infobox musical artist'):
associated_acts = t.get('associated_acts')
for w in associated_acts.value.filter_wikilinks():
relationships.append(AssociatedActRelationship(self._node, Node(w.title, NodeTypes.ARTIST)))
return relationships
Use string as node title instead of wikicode | from artgraph.plugins.plugin import Plugin
class InfoboxPlugin(Plugin):
def __init__(self, node):
self._node = node
def get_nodes(self):
from artgraph.node import Node, NodeTypes
from artgraph.relationship import AssociatedActRelationship
wikicode = self.get_wikicode(self._node.get_dbtitle())
templates = wikicode.filter_templates()
relationships = []
for t in templates:
if t.name.matches('Infobox musical artist'):
associated_acts = t.get('associated_acts')
for w in associated_acts.value.filter_wikilinks():
relationships.append(AssociatedActRelationship(self._node, Node(str(w.title), NodeTypes.ARTIST)))
return relationships
| <commit_before>from artgraph.plugins.plugin import Plugin
class InfoboxPlugin(Plugin):
def __init__(self, node):
self._node = node
def get_nodes(self):
from artgraph.node import Node, NodeTypes
from artgraph.relationship import AssociatedActRelationship
wikicode = self.get_wikicode(self._node.get_dbtitle())
templates = wikicode.filter_templates()
relationships = []
for t in templates:
if t.name.matches('Infobox musical artist'):
associated_acts = t.get('associated_acts')
for w in associated_acts.value.filter_wikilinks():
relationships.append(AssociatedActRelationship(self._node, Node(w.title, NodeTypes.ARTIST)))
return relationships
<commit_msg>Use string as node title instead of wikicode<commit_after> | from artgraph.plugins.plugin import Plugin
class InfoboxPlugin(Plugin):
def __init__(self, node):
self._node = node
def get_nodes(self):
from artgraph.node import Node, NodeTypes
from artgraph.relationship import AssociatedActRelationship
wikicode = self.get_wikicode(self._node.get_dbtitle())
templates = wikicode.filter_templates()
relationships = []
for t in templates:
if t.name.matches('Infobox musical artist'):
associated_acts = t.get('associated_acts')
for w in associated_acts.value.filter_wikilinks():
relationships.append(AssociatedActRelationship(self._node, Node(str(w.title), NodeTypes.ARTIST)))
return relationships
| from artgraph.plugins.plugin import Plugin
class InfoboxPlugin(Plugin):
def __init__(self, node):
self._node = node
def get_nodes(self):
from artgraph.node import Node, NodeTypes
from artgraph.relationship import AssociatedActRelationship
wikicode = self.get_wikicode(self._node.get_dbtitle())
templates = wikicode.filter_templates()
relationships = []
for t in templates:
if t.name.matches('Infobox musical artist'):
associated_acts = t.get('associated_acts')
for w in associated_acts.value.filter_wikilinks():
relationships.append(AssociatedActRelationship(self._node, Node(w.title, NodeTypes.ARTIST)))
return relationships
Use string as node title instead of wikicodefrom artgraph.plugins.plugin import Plugin
class InfoboxPlugin(Plugin):
def __init__(self, node):
self._node = node
def get_nodes(self):
from artgraph.node import Node, NodeTypes
from artgraph.relationship import AssociatedActRelationship
wikicode = self.get_wikicode(self._node.get_dbtitle())
templates = wikicode.filter_templates()
relationships = []
for t in templates:
if t.name.matches('Infobox musical artist'):
associated_acts = t.get('associated_acts')
for w in associated_acts.value.filter_wikilinks():
relationships.append(AssociatedActRelationship(self._node, Node(str(w.title), NodeTypes.ARTIST)))
return relationships
| <commit_before>from artgraph.plugins.plugin import Plugin
class InfoboxPlugin(Plugin):
def __init__(self, node):
self._node = node
def get_nodes(self):
from artgraph.node import Node, NodeTypes
from artgraph.relationship import AssociatedActRelationship
wikicode = self.get_wikicode(self._node.get_dbtitle())
templates = wikicode.filter_templates()
relationships = []
for t in templates:
if t.name.matches('Infobox musical artist'):
associated_acts = t.get('associated_acts')
for w in associated_acts.value.filter_wikilinks():
relationships.append(AssociatedActRelationship(self._node, Node(w.title, NodeTypes.ARTIST)))
return relationships
<commit_msg>Use string as node title instead of wikicode<commit_after>from artgraph.plugins.plugin import Plugin
class InfoboxPlugin(Plugin):
def __init__(self, node):
self._node = node
def get_nodes(self):
from artgraph.node import Node, NodeTypes
from artgraph.relationship import AssociatedActRelationship
wikicode = self.get_wikicode(self._node.get_dbtitle())
templates = wikicode.filter_templates()
relationships = []
for t in templates:
if t.name.matches('Infobox musical artist'):
associated_acts = t.get('associated_acts')
for w in associated_acts.value.filter_wikilinks():
relationships.append(AssociatedActRelationship(self._node, Node(str(w.title), NodeTypes.ARTIST)))
return relationships
|
1159939ebd193eef809d5d0f27fcb9ef60b7e283 | src/auspex/instruments/utils.py | src/auspex/instruments/utils.py | from . import bbn
import auspex.config
from auspex.log import logger
from QGL import *
ChannelLibrary()
def pulse_marker(marker_name, length = 100e-9):
""" Utility to generate a square pulse on a APS2 marker. Used for instance to switch a signal between spectrum analyzer and input line
marker_name as defined in measure.yaml """
settings = auspex.config.load_meas_file(auspex.config.find_meas_file())
mkr = settings['markers'][marker_name]
marker = MarkerFactory(marker_name)
APS_name = mkr.split()[0]
APS = bbn.APS2()
APS.connect(settings['instruments'][APS_name]['address'])
APS.set_trigger_source('Software')
seq = [[TRIG(marker,length)]]
APS.set_seq_file(compile_to_hardware(seq, 'Switch\Switch').replace('meta.json', APS_name+'.h5'))
APS.run()
APS.trigger()
APS.stop()
APS.disconnect()
logger.info('Switched marker {} ({})'.format(marker_name, mkr))
| from . import bbn
import auspex.config
from auspex.log import logger
def pulse_marker(marker_name, length = 100e-9):
""" Utility to generate a square pulse on a APS2 marker. Used for instance to switch a signal between spectrum analyzer and input line
marker_name as defined in measure.yaml """
from QGL import *
ChannelLibrary()
settings = auspex.config.load_meas_file(auspex.config.find_meas_file())
mkr = settings['markers'][marker_name]
marker = MarkerFactory(marker_name)
APS_name = mkr.split()[0]
APS = bbn.APS2()
APS.connect(settings['instruments'][APS_name]['address'])
APS.set_trigger_source('Software')
seq = [[TRIG(marker,length)]]
APS.set_seq_file(compile_to_hardware(seq, 'Switch\Switch').replace('meta.json', APS_name+'.h5'))
APS.run()
APS.trigger()
APS.stop()
APS.disconnect()
logger.info('Switched marker {} ({})'.format(marker_name, mkr))
| Move QGL import inside function | Move QGL import inside function
A channel library is not always available
| Python | apache-2.0 | BBN-Q/Auspex,BBN-Q/Auspex,BBN-Q/Auspex,BBN-Q/Auspex | from . import bbn
import auspex.config
from auspex.log import logger
from QGL import *
ChannelLibrary()
def pulse_marker(marker_name, length = 100e-9):
""" Utility to generate a square pulse on a APS2 marker. Used for instance to switch a signal between spectrum analyzer and input line
marker_name as defined in measure.yaml """
settings = auspex.config.load_meas_file(auspex.config.find_meas_file())
mkr = settings['markers'][marker_name]
marker = MarkerFactory(marker_name)
APS_name = mkr.split()[0]
APS = bbn.APS2()
APS.connect(settings['instruments'][APS_name]['address'])
APS.set_trigger_source('Software')
seq = [[TRIG(marker,length)]]
APS.set_seq_file(compile_to_hardware(seq, 'Switch\Switch').replace('meta.json', APS_name+'.h5'))
APS.run()
APS.trigger()
APS.stop()
APS.disconnect()
logger.info('Switched marker {} ({})'.format(marker_name, mkr))
Move QGL import inside function
A channel library is not always available | from . import bbn
import auspex.config
from auspex.log import logger
def pulse_marker(marker_name, length = 100e-9):
""" Utility to generate a square pulse on a APS2 marker. Used for instance to switch a signal between spectrum analyzer and input line
marker_name as defined in measure.yaml """
from QGL import *
ChannelLibrary()
settings = auspex.config.load_meas_file(auspex.config.find_meas_file())
mkr = settings['markers'][marker_name]
marker = MarkerFactory(marker_name)
APS_name = mkr.split()[0]
APS = bbn.APS2()
APS.connect(settings['instruments'][APS_name]['address'])
APS.set_trigger_source('Software')
seq = [[TRIG(marker,length)]]
APS.set_seq_file(compile_to_hardware(seq, 'Switch\Switch').replace('meta.json', APS_name+'.h5'))
APS.run()
APS.trigger()
APS.stop()
APS.disconnect()
logger.info('Switched marker {} ({})'.format(marker_name, mkr))
| <commit_before>from . import bbn
import auspex.config
from auspex.log import logger
from QGL import *
ChannelLibrary()
def pulse_marker(marker_name, length = 100e-9):
""" Utility to generate a square pulse on a APS2 marker. Used for instance to switch a signal between spectrum analyzer and input line
marker_name as defined in measure.yaml """
settings = auspex.config.load_meas_file(auspex.config.find_meas_file())
mkr = settings['markers'][marker_name]
marker = MarkerFactory(marker_name)
APS_name = mkr.split()[0]
APS = bbn.APS2()
APS.connect(settings['instruments'][APS_name]['address'])
APS.set_trigger_source('Software')
seq = [[TRIG(marker,length)]]
APS.set_seq_file(compile_to_hardware(seq, 'Switch\Switch').replace('meta.json', APS_name+'.h5'))
APS.run()
APS.trigger()
APS.stop()
APS.disconnect()
logger.info('Switched marker {} ({})'.format(marker_name, mkr))
<commit_msg>Move QGL import inside function
A channel library is not always available<commit_after> | from . import bbn
import auspex.config
from auspex.log import logger
def pulse_marker(marker_name, length = 100e-9):
""" Utility to generate a square pulse on a APS2 marker. Used for instance to switch a signal between spectrum analyzer and input line
marker_name as defined in measure.yaml """
from QGL import *
ChannelLibrary()
settings = auspex.config.load_meas_file(auspex.config.find_meas_file())
mkr = settings['markers'][marker_name]
marker = MarkerFactory(marker_name)
APS_name = mkr.split()[0]
APS = bbn.APS2()
APS.connect(settings['instruments'][APS_name]['address'])
APS.set_trigger_source('Software')
seq = [[TRIG(marker,length)]]
APS.set_seq_file(compile_to_hardware(seq, 'Switch\Switch').replace('meta.json', APS_name+'.h5'))
APS.run()
APS.trigger()
APS.stop()
APS.disconnect()
logger.info('Switched marker {} ({})'.format(marker_name, mkr))
| from . import bbn
import auspex.config
from auspex.log import logger
from QGL import *
ChannelLibrary()
def pulse_marker(marker_name, length = 100e-9):
""" Utility to generate a square pulse on a APS2 marker. Used for instance to switch a signal between spectrum analyzer and input line
marker_name as defined in measure.yaml """
settings = auspex.config.load_meas_file(auspex.config.find_meas_file())
mkr = settings['markers'][marker_name]
marker = MarkerFactory(marker_name)
APS_name = mkr.split()[0]
APS = bbn.APS2()
APS.connect(settings['instruments'][APS_name]['address'])
APS.set_trigger_source('Software')
seq = [[TRIG(marker,length)]]
APS.set_seq_file(compile_to_hardware(seq, 'Switch\Switch').replace('meta.json', APS_name+'.h5'))
APS.run()
APS.trigger()
APS.stop()
APS.disconnect()
logger.info('Switched marker {} ({})'.format(marker_name, mkr))
Move QGL import inside function
A channel library is not always availablefrom . import bbn
import auspex.config
from auspex.log import logger
def pulse_marker(marker_name, length = 100e-9):
""" Utility to generate a square pulse on a APS2 marker. Used for instance to switch a signal between spectrum analyzer and input line
marker_name as defined in measure.yaml """
from QGL import *
ChannelLibrary()
settings = auspex.config.load_meas_file(auspex.config.find_meas_file())
mkr = settings['markers'][marker_name]
marker = MarkerFactory(marker_name)
APS_name = mkr.split()[0]
APS = bbn.APS2()
APS.connect(settings['instruments'][APS_name]['address'])
APS.set_trigger_source('Software')
seq = [[TRIG(marker,length)]]
APS.set_seq_file(compile_to_hardware(seq, 'Switch\Switch').replace('meta.json', APS_name+'.h5'))
APS.run()
APS.trigger()
APS.stop()
APS.disconnect()
logger.info('Switched marker {} ({})'.format(marker_name, mkr))
| <commit_before>from . import bbn
import auspex.config
from auspex.log import logger
from QGL import *
ChannelLibrary()
def pulse_marker(marker_name, length = 100e-9):
""" Utility to generate a square pulse on a APS2 marker. Used for instance to switch a signal between spectrum analyzer and input line
marker_name as defined in measure.yaml """
settings = auspex.config.load_meas_file(auspex.config.find_meas_file())
mkr = settings['markers'][marker_name]
marker = MarkerFactory(marker_name)
APS_name = mkr.split()[0]
APS = bbn.APS2()
APS.connect(settings['instruments'][APS_name]['address'])
APS.set_trigger_source('Software')
seq = [[TRIG(marker,length)]]
APS.set_seq_file(compile_to_hardware(seq, 'Switch\Switch').replace('meta.json', APS_name+'.h5'))
APS.run()
APS.trigger()
APS.stop()
APS.disconnect()
logger.info('Switched marker {} ({})'.format(marker_name, mkr))
<commit_msg>Move QGL import inside function
A channel library is not always available<commit_after>from . import bbn
import auspex.config
from auspex.log import logger
def pulse_marker(marker_name, length = 100e-9):
""" Utility to generate a square pulse on a APS2 marker. Used for instance to switch a signal between spectrum analyzer and input line
marker_name as defined in measure.yaml """
from QGL import *
ChannelLibrary()
settings = auspex.config.load_meas_file(auspex.config.find_meas_file())
mkr = settings['markers'][marker_name]
marker = MarkerFactory(marker_name)
APS_name = mkr.split()[0]
APS = bbn.APS2()
APS.connect(settings['instruments'][APS_name]['address'])
APS.set_trigger_source('Software')
seq = [[TRIG(marker,length)]]
APS.set_seq_file(compile_to_hardware(seq, 'Switch\Switch').replace('meta.json', APS_name+'.h5'))
APS.run()
APS.trigger()
APS.stop()
APS.disconnect()
logger.info('Switched marker {} ({})'.format(marker_name, mkr))
|
8dcab3b18b603e520f12c3fd5a873a08f32d4a9a | nnsave_app/urls.py | nnsave_app/urls.py | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^location$',views.location, name='location'),
]
| from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^locations/?(?P<id>[0-9]+)?$',views.location, name='location'),
]
| Add id parameter to URL | Add id parameter to URL
| Python | mit | legonigel/nnsave_backend,legonigel/nnsave_backend,legonigel/nnsave_backend,legonigel/nnsave_backend | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^location$',views.location, name='location'),
]
Add id parameter to URL | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^locations/?(?P<id>[0-9]+)?$',views.location, name='location'),
]
| <commit_before>from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^location$',views.location, name='location'),
]
<commit_msg>Add id parameter to URL<commit_after> | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^locations/?(?P<id>[0-9]+)?$',views.location, name='location'),
]
| from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^location$',views.location, name='location'),
]
Add id parameter to URLfrom django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^locations/?(?P<id>[0-9]+)?$',views.location, name='location'),
]
| <commit_before>from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^location$',views.location, name='location'),
]
<commit_msg>Add id parameter to URL<commit_after>from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^locations/?(?P<id>[0-9]+)?$',views.location, name='location'),
]
|
17b9749f2a36499c74effc27ec442a4bb957e877 | typescript/commands/build.py | typescript/commands/build.py | import sublime_plugin
from ..libs.global_vars import *
from ..libs import cli
class TypescriptBuildCommand(sublime_plugin.WindowCommand):
def run(self):
if get_node_path() is None:
print("Cannot found node. Build cancelled.")
return
file_name = self.window.active_view().file_name()
project_info = cli.service.project_info(file_name)
if project_info["success"]:
if "configFileName" in project_info["body"]:
tsconfig_dir = dirname(project_info["body"]["configFileName"])
self.window.run_command("exec", {
"cmd": [get_node_path(), TSC_PATH, "-p", tsconfig_dir],
"file_regex": "^(.+?)\\((\\d+),(\\d+)\\): (.+)$",
"shell": True
})
else:
sublime.active_window().show_input_panel(
"Build parameters: ",
"", # initial text
self.compile_inferred_project,
None, # on change
None # on cancel
)
def compile_inferred_project(self, params=""):
file_name = self.window.active_view().file_name()
cmd = [get_node_path(), TSC_PATH, file_name]
if params != "":
cmd.extend(params.split(' '))
self.window.run_command("exec", {
"cmd": cmd,
"file_regex": "^(.+?)\\((\\d+),(\\d+)\\): (.+)$",
"shell": True
})
| import sublime_plugin
from ..libs.global_vars import *
from ..libs import cli
class TypescriptBuildCommand(sublime_plugin.WindowCommand):
def run(self):
if get_node_path() is None:
print("Cannot found node. Build cancelled.")
return
file_name = self.window.active_view().file_name()
project_info = cli.service.project_info(file_name)
if project_info["success"]:
if "configFileName" in project_info["body"]:
tsconfig_dir = dirname(project_info["body"]["configFileName"])
self.window.run_command("exec", {
"cmd": [get_node_path(), TSC_PATH, "-p", tsconfig_dir],
"file_regex": "^(.+?)\\((\\d+),(\\d+)\\): (.+)$"
})
else:
sublime.active_window().show_input_panel(
"Build parameters: ",
"", # initial text
self.compile_inferred_project,
None, # on change
None # on cancel
)
def compile_inferred_project(self, params=""):
file_name = self.window.active_view().file_name()
cmd = [get_node_path(), TSC_PATH, file_name]
print(cmd)
if params != "":
cmd.extend(params.split(' '))
self.window.run_command("exec", {
"cmd": cmd,
"file_regex": "^(.+?)\\((\\d+),(\\d+)\\): (.+)$"
})
| Remove shell requirement to avoid escaping | Remove shell requirement to avoid escaping
| Python | apache-2.0 | fongandrew/TypeScript-Sublime-JSX-Plugin,Microsoft/TypeScript-Sublime-Plugin,fongandrew/TypeScript-Sublime-JSX-Plugin,zhengbli/TypeScript-Sublime-Plugin,kungfusheep/TypeScript-Sublime-Plugin,RyanCavanaugh/TypeScript-Sublime-Plugin,zhengbli/TypeScript-Sublime-Plugin,kungfusheep/TypeScript-Sublime-Plugin,RyanCavanaugh/TypeScript-Sublime-Plugin,fongandrew/TypeScript-Sublime-JSX-Plugin,Microsoft/TypeScript-Sublime-Plugin,Microsoft/TypeScript-Sublime-Plugin,zhengbli/TypeScript-Sublime-Plugin,kungfusheep/TypeScript-Sublime-Plugin,hoanhtien/TypeScript-Sublime-Plugin,hoanhtien/TypeScript-Sublime-Plugin,hoanhtien/TypeScript-Sublime-Plugin,RyanCavanaugh/TypeScript-Sublime-Plugin | import sublime_plugin
from ..libs.global_vars import *
from ..libs import cli
class TypescriptBuildCommand(sublime_plugin.WindowCommand):
def run(self):
if get_node_path() is None:
print("Cannot found node. Build cancelled.")
return
file_name = self.window.active_view().file_name()
project_info = cli.service.project_info(file_name)
if project_info["success"]:
if "configFileName" in project_info["body"]:
tsconfig_dir = dirname(project_info["body"]["configFileName"])
self.window.run_command("exec", {
"cmd": [get_node_path(), TSC_PATH, "-p", tsconfig_dir],
"file_regex": "^(.+?)\\((\\d+),(\\d+)\\): (.+)$",
"shell": True
})
else:
sublime.active_window().show_input_panel(
"Build parameters: ",
"", # initial text
self.compile_inferred_project,
None, # on change
None # on cancel
)
def compile_inferred_project(self, params=""):
file_name = self.window.active_view().file_name()
cmd = [get_node_path(), TSC_PATH, file_name]
if params != "":
cmd.extend(params.split(' '))
self.window.run_command("exec", {
"cmd": cmd,
"file_regex": "^(.+?)\\((\\d+),(\\d+)\\): (.+)$",
"shell": True
})
Remove shell requirement to avoid escaping | import sublime_plugin
from ..libs.global_vars import *
from ..libs import cli
class TypescriptBuildCommand(sublime_plugin.WindowCommand):
def run(self):
if get_node_path() is None:
print("Cannot found node. Build cancelled.")
return
file_name = self.window.active_view().file_name()
project_info = cli.service.project_info(file_name)
if project_info["success"]:
if "configFileName" in project_info["body"]:
tsconfig_dir = dirname(project_info["body"]["configFileName"])
self.window.run_command("exec", {
"cmd": [get_node_path(), TSC_PATH, "-p", tsconfig_dir],
"file_regex": "^(.+?)\\((\\d+),(\\d+)\\): (.+)$"
})
else:
sublime.active_window().show_input_panel(
"Build parameters: ",
"", # initial text
self.compile_inferred_project,
None, # on change
None # on cancel
)
def compile_inferred_project(self, params=""):
file_name = self.window.active_view().file_name()
cmd = [get_node_path(), TSC_PATH, file_name]
print(cmd)
if params != "":
cmd.extend(params.split(' '))
self.window.run_command("exec", {
"cmd": cmd,
"file_regex": "^(.+?)\\((\\d+),(\\d+)\\): (.+)$"
})
| <commit_before>import sublime_plugin
from ..libs.global_vars import *
from ..libs import cli
class TypescriptBuildCommand(sublime_plugin.WindowCommand):
def run(self):
if get_node_path() is None:
print("Cannot found node. Build cancelled.")
return
file_name = self.window.active_view().file_name()
project_info = cli.service.project_info(file_name)
if project_info["success"]:
if "configFileName" in project_info["body"]:
tsconfig_dir = dirname(project_info["body"]["configFileName"])
self.window.run_command("exec", {
"cmd": [get_node_path(), TSC_PATH, "-p", tsconfig_dir],
"file_regex": "^(.+?)\\((\\d+),(\\d+)\\): (.+)$",
"shell": True
})
else:
sublime.active_window().show_input_panel(
"Build parameters: ",
"", # initial text
self.compile_inferred_project,
None, # on change
None # on cancel
)
def compile_inferred_project(self, params=""):
file_name = self.window.active_view().file_name()
cmd = [get_node_path(), TSC_PATH, file_name]
if params != "":
cmd.extend(params.split(' '))
self.window.run_command("exec", {
"cmd": cmd,
"file_regex": "^(.+?)\\((\\d+),(\\d+)\\): (.+)$",
"shell": True
})
<commit_msg>Remove shell requirement to avoid escaping<commit_after> | import sublime_plugin
from ..libs.global_vars import *
from ..libs import cli
class TypescriptBuildCommand(sublime_plugin.WindowCommand):
def run(self):
if get_node_path() is None:
print("Cannot found node. Build cancelled.")
return
file_name = self.window.active_view().file_name()
project_info = cli.service.project_info(file_name)
if project_info["success"]:
if "configFileName" in project_info["body"]:
tsconfig_dir = dirname(project_info["body"]["configFileName"])
self.window.run_command("exec", {
"cmd": [get_node_path(), TSC_PATH, "-p", tsconfig_dir],
"file_regex": "^(.+?)\\((\\d+),(\\d+)\\): (.+)$"
})
else:
sublime.active_window().show_input_panel(
"Build parameters: ",
"", # initial text
self.compile_inferred_project,
None, # on change
None # on cancel
)
def compile_inferred_project(self, params=""):
file_name = self.window.active_view().file_name()
cmd = [get_node_path(), TSC_PATH, file_name]
print(cmd)
if params != "":
cmd.extend(params.split(' '))
self.window.run_command("exec", {
"cmd": cmd,
"file_regex": "^(.+?)\\((\\d+),(\\d+)\\): (.+)$"
})
| import sublime_plugin
from ..libs.global_vars import *
from ..libs import cli
class TypescriptBuildCommand(sublime_plugin.WindowCommand):
def run(self):
if get_node_path() is None:
print("Cannot found node. Build cancelled.")
return
file_name = self.window.active_view().file_name()
project_info = cli.service.project_info(file_name)
if project_info["success"]:
if "configFileName" in project_info["body"]:
tsconfig_dir = dirname(project_info["body"]["configFileName"])
self.window.run_command("exec", {
"cmd": [get_node_path(), TSC_PATH, "-p", tsconfig_dir],
"file_regex": "^(.+?)\\((\\d+),(\\d+)\\): (.+)$",
"shell": True
})
else:
sublime.active_window().show_input_panel(
"Build parameters: ",
"", # initial text
self.compile_inferred_project,
None, # on change
None # on cancel
)
def compile_inferred_project(self, params=""):
file_name = self.window.active_view().file_name()
cmd = [get_node_path(), TSC_PATH, file_name]
if params != "":
cmd.extend(params.split(' '))
self.window.run_command("exec", {
"cmd": cmd,
"file_regex": "^(.+?)\\((\\d+),(\\d+)\\): (.+)$",
"shell": True
})
Remove shell requirement to avoid escapingimport sublime_plugin
from ..libs.global_vars import *
from ..libs import cli
class TypescriptBuildCommand(sublime_plugin.WindowCommand):
def run(self):
if get_node_path() is None:
print("Cannot found node. Build cancelled.")
return
file_name = self.window.active_view().file_name()
project_info = cli.service.project_info(file_name)
if project_info["success"]:
if "configFileName" in project_info["body"]:
tsconfig_dir = dirname(project_info["body"]["configFileName"])
self.window.run_command("exec", {
"cmd": [get_node_path(), TSC_PATH, "-p", tsconfig_dir],
"file_regex": "^(.+?)\\((\\d+),(\\d+)\\): (.+)$"
})
else:
sublime.active_window().show_input_panel(
"Build parameters: ",
"", # initial text
self.compile_inferred_project,
None, # on change
None # on cancel
)
def compile_inferred_project(self, params=""):
file_name = self.window.active_view().file_name()
cmd = [get_node_path(), TSC_PATH, file_name]
print(cmd)
if params != "":
cmd.extend(params.split(' '))
self.window.run_command("exec", {
"cmd": cmd,
"file_regex": "^(.+?)\\((\\d+),(\\d+)\\): (.+)$"
})
| <commit_before>import sublime_plugin
from ..libs.global_vars import *
from ..libs import cli
class TypescriptBuildCommand(sublime_plugin.WindowCommand):
def run(self):
if get_node_path() is None:
print("Cannot found node. Build cancelled.")
return
file_name = self.window.active_view().file_name()
project_info = cli.service.project_info(file_name)
if project_info["success"]:
if "configFileName" in project_info["body"]:
tsconfig_dir = dirname(project_info["body"]["configFileName"])
self.window.run_command("exec", {
"cmd": [get_node_path(), TSC_PATH, "-p", tsconfig_dir],
"file_regex": "^(.+?)\\((\\d+),(\\d+)\\): (.+)$",
"shell": True
})
else:
sublime.active_window().show_input_panel(
"Build parameters: ",
"", # initial text
self.compile_inferred_project,
None, # on change
None # on cancel
)
def compile_inferred_project(self, params=""):
file_name = self.window.active_view().file_name()
cmd = [get_node_path(), TSC_PATH, file_name]
if params != "":
cmd.extend(params.split(' '))
self.window.run_command("exec", {
"cmd": cmd,
"file_regex": "^(.+?)\\((\\d+),(\\d+)\\): (.+)$",
"shell": True
})
<commit_msg>Remove shell requirement to avoid escaping<commit_after>import sublime_plugin
from ..libs.global_vars import *
from ..libs import cli
class TypescriptBuildCommand(sublime_plugin.WindowCommand):
def run(self):
if get_node_path() is None:
print("Cannot found node. Build cancelled.")
return
file_name = self.window.active_view().file_name()
project_info = cli.service.project_info(file_name)
if project_info["success"]:
if "configFileName" in project_info["body"]:
tsconfig_dir = dirname(project_info["body"]["configFileName"])
self.window.run_command("exec", {
"cmd": [get_node_path(), TSC_PATH, "-p", tsconfig_dir],
"file_regex": "^(.+?)\\((\\d+),(\\d+)\\): (.+)$"
})
else:
sublime.active_window().show_input_panel(
"Build parameters: ",
"", # initial text
self.compile_inferred_project,
None, # on change
None # on cancel
)
def compile_inferred_project(self, params=""):
file_name = self.window.active_view().file_name()
cmd = [get_node_path(), TSC_PATH, file_name]
print(cmd)
if params != "":
cmd.extend(params.split(' '))
self.window.run_command("exec", {
"cmd": cmd,
"file_regex": "^(.+?)\\((\\d+),(\\d+)\\): (.+)$"
})
|
a14fcec19471bffcb1dcbad1d0cff7100d0ef6bc | web/blueprints/host/forms.py | web/blueprints/host/forms.py | from wtforms.validators import DataRequired, Optional
from web.blueprints.facilities.forms import SelectRoomForm
from web.form.fields.core import TextField, QuerySelectField, \
SelectMultipleField
from web.form.fields.custom import UserIDField, MacField
from flask_wtf import FlaskForm as Form
from web.form.fields.validators import MacAddress
class HostForm(SelectRoomForm):
owner_id = UserIDField(u"Besitzer-ID")
name = TextField(u"Name", validators=[Optional()],
description=u"z.B. TP-LINK WR841, FritzBox 4040 oder MacBook")
_order = ("name", "owner_id")
class InterfaceForm(Form):
name = TextField(u"Name",description=u"z.B. eth0, en0 oder enp0s29u1u1u5")
mac = MacField(u"MAC", [MacAddress(message=u"MAC ist ungültig!")])
ips = SelectMultipleField(u"IPs", validators=[Optional()])
| from wtforms.validators import DataRequired, Optional
from web.blueprints.facilities.forms import SelectRoomForm
from web.form.fields.core import TextField, QuerySelectField, \
SelectMultipleField
from web.form.fields.custom import UserIDField, MacField
from flask_wtf import FlaskForm as Form
from web.form.fields.validators import MacAddress
class HostForm(SelectRoomForm):
owner_id = UserIDField("Besitzer-ID")
name = TextField("Name", validators=[Optional()],
description="z.B. TP-LINK WR841, FritzBox 4040 oder MacBook")
_order = ("name", "owner_id")
class InterfaceForm(Form):
name = TextField("Name",
description="z.B. eth0, en0 oder enp0s29u1u1u5",
validators=[Optional()])
mac = MacField("MAC", [MacAddress(message="MAC ist ungültig!")])
ips = SelectMultipleField(u"IPs", validators=[Optional()])
| Make interface name optional and remove unicode prefixes | Make interface name optional and remove unicode prefixes
| Python | apache-2.0 | agdsn/pycroft,agdsn/pycroft,agdsn/pycroft,agdsn/pycroft,agdsn/pycroft | from wtforms.validators import DataRequired, Optional
from web.blueprints.facilities.forms import SelectRoomForm
from web.form.fields.core import TextField, QuerySelectField, \
SelectMultipleField
from web.form.fields.custom import UserIDField, MacField
from flask_wtf import FlaskForm as Form
from web.form.fields.validators import MacAddress
class HostForm(SelectRoomForm):
owner_id = UserIDField(u"Besitzer-ID")
name = TextField(u"Name", validators=[Optional()],
description=u"z.B. TP-LINK WR841, FritzBox 4040 oder MacBook")
_order = ("name", "owner_id")
class InterfaceForm(Form):
name = TextField(u"Name",description=u"z.B. eth0, en0 oder enp0s29u1u1u5")
mac = MacField(u"MAC", [MacAddress(message=u"MAC ist ungültig!")])
ips = SelectMultipleField(u"IPs", validators=[Optional()])
Make interface name optional and remove unicode prefixes | from wtforms.validators import DataRequired, Optional
from web.blueprints.facilities.forms import SelectRoomForm
from web.form.fields.core import TextField, QuerySelectField, \
SelectMultipleField
from web.form.fields.custom import UserIDField, MacField
from flask_wtf import FlaskForm as Form
from web.form.fields.validators import MacAddress
class HostForm(SelectRoomForm):
owner_id = UserIDField("Besitzer-ID")
name = TextField("Name", validators=[Optional()],
description="z.B. TP-LINK WR841, FritzBox 4040 oder MacBook")
_order = ("name", "owner_id")
class InterfaceForm(Form):
name = TextField("Name",
description="z.B. eth0, en0 oder enp0s29u1u1u5",
validators=[Optional()])
mac = MacField("MAC", [MacAddress(message="MAC ist ungültig!")])
ips = SelectMultipleField(u"IPs", validators=[Optional()])
| <commit_before>from wtforms.validators import DataRequired, Optional
from web.blueprints.facilities.forms import SelectRoomForm
from web.form.fields.core import TextField, QuerySelectField, \
SelectMultipleField
from web.form.fields.custom import UserIDField, MacField
from flask_wtf import FlaskForm as Form
from web.form.fields.validators import MacAddress
class HostForm(SelectRoomForm):
owner_id = UserIDField(u"Besitzer-ID")
name = TextField(u"Name", validators=[Optional()],
description=u"z.B. TP-LINK WR841, FritzBox 4040 oder MacBook")
_order = ("name", "owner_id")
class InterfaceForm(Form):
name = TextField(u"Name",description=u"z.B. eth0, en0 oder enp0s29u1u1u5")
mac = MacField(u"MAC", [MacAddress(message=u"MAC ist ungültig!")])
ips = SelectMultipleField(u"IPs", validators=[Optional()])
<commit_msg>Make interface name optional and remove unicode prefixes<commit_after> | from wtforms.validators import DataRequired, Optional
from web.blueprints.facilities.forms import SelectRoomForm
from web.form.fields.core import TextField, QuerySelectField, \
SelectMultipleField
from web.form.fields.custom import UserIDField, MacField
from flask_wtf import FlaskForm as Form
from web.form.fields.validators import MacAddress
class HostForm(SelectRoomForm):
owner_id = UserIDField("Besitzer-ID")
name = TextField("Name", validators=[Optional()],
description="z.B. TP-LINK WR841, FritzBox 4040 oder MacBook")
_order = ("name", "owner_id")
class InterfaceForm(Form):
name = TextField("Name",
description="z.B. eth0, en0 oder enp0s29u1u1u5",
validators=[Optional()])
mac = MacField("MAC", [MacAddress(message="MAC ist ungültig!")])
ips = SelectMultipleField(u"IPs", validators=[Optional()])
| from wtforms.validators import DataRequired, Optional
from web.blueprints.facilities.forms import SelectRoomForm
from web.form.fields.core import TextField, QuerySelectField, \
SelectMultipleField
from web.form.fields.custom import UserIDField, MacField
from flask_wtf import FlaskForm as Form
from web.form.fields.validators import MacAddress
class HostForm(SelectRoomForm):
owner_id = UserIDField(u"Besitzer-ID")
name = TextField(u"Name", validators=[Optional()],
description=u"z.B. TP-LINK WR841, FritzBox 4040 oder MacBook")
_order = ("name", "owner_id")
class InterfaceForm(Form):
name = TextField(u"Name",description=u"z.B. eth0, en0 oder enp0s29u1u1u5")
mac = MacField(u"MAC", [MacAddress(message=u"MAC ist ungültig!")])
ips = SelectMultipleField(u"IPs", validators=[Optional()])
Make interface name optional and remove unicode prefixesfrom wtforms.validators import DataRequired, Optional
from web.blueprints.facilities.forms import SelectRoomForm
from web.form.fields.core import TextField, QuerySelectField, \
SelectMultipleField
from web.form.fields.custom import UserIDField, MacField
from flask_wtf import FlaskForm as Form
from web.form.fields.validators import MacAddress
class HostForm(SelectRoomForm):
owner_id = UserIDField("Besitzer-ID")
name = TextField("Name", validators=[Optional()],
description="z.B. TP-LINK WR841, FritzBox 4040 oder MacBook")
_order = ("name", "owner_id")
class InterfaceForm(Form):
name = TextField("Name",
description="z.B. eth0, en0 oder enp0s29u1u1u5",
validators=[Optional()])
mac = MacField("MAC", [MacAddress(message="MAC ist ungültig!")])
ips = SelectMultipleField(u"IPs", validators=[Optional()])
| <commit_before>from wtforms.validators import DataRequired, Optional
from web.blueprints.facilities.forms import SelectRoomForm
from web.form.fields.core import TextField, QuerySelectField, \
SelectMultipleField
from web.form.fields.custom import UserIDField, MacField
from flask_wtf import FlaskForm as Form
from web.form.fields.validators import MacAddress
class HostForm(SelectRoomForm):
owner_id = UserIDField(u"Besitzer-ID")
name = TextField(u"Name", validators=[Optional()],
description=u"z.B. TP-LINK WR841, FritzBox 4040 oder MacBook")
_order = ("name", "owner_id")
class InterfaceForm(Form):
name = TextField(u"Name",description=u"z.B. eth0, en0 oder enp0s29u1u1u5")
mac = MacField(u"MAC", [MacAddress(message=u"MAC ist ungültig!")])
ips = SelectMultipleField(u"IPs", validators=[Optional()])
<commit_msg>Make interface name optional and remove unicode prefixes<commit_after>from wtforms.validators import DataRequired, Optional
from web.blueprints.facilities.forms import SelectRoomForm
from web.form.fields.core import TextField, QuerySelectField, \
SelectMultipleField
from web.form.fields.custom import UserIDField, MacField
from flask_wtf import FlaskForm as Form
from web.form.fields.validators import MacAddress
class HostForm(SelectRoomForm):
owner_id = UserIDField("Besitzer-ID")
name = TextField("Name", validators=[Optional()],
description="z.B. TP-LINK WR841, FritzBox 4040 oder MacBook")
_order = ("name", "owner_id")
class InterfaceForm(Form):
name = TextField("Name",
description="z.B. eth0, en0 oder enp0s29u1u1u5",
validators=[Optional()])
mac = MacField("MAC", [MacAddress(message="MAC ist ungültig!")])
ips = SelectMultipleField(u"IPs", validators=[Optional()])
|
75b4df9437ca277709e9b61fbb9aa5c20d96820e | wallace/app.py | wallace/app.py | from flask import Flask
import experiments
import db
app = Flask(__name__)
session = db.init_db(drop_all=True)
@app.route('/')
def index():
return 'Index page'
@app.route('/demo2')
def start():
experiment = experiments.Demo2(session)
experiment.add_and_trigger_sources() # Add any sources
process = experiment.process # Step through the process
for i in xrange(experiment.num_steps):
process.step()
if __name__ == "__main__":
app.run()
print session
| from flask import Flask
import experiments
import db
app = Flask(__name__)
session = db.init_db(drop_all=True)
@app.route('/')
def index():
return 'Index page'
@app.route('/demo2')
def start():
experiment = experiments.Demo2(session)
experiment.add_and_trigger_sources() # Add any sources
process = experiment.process # Step through the process
for i in xrange(experiment.num_steps):
process.step()
if __name__ == "__main__":
app.debug = True
app.run()
| Put Flask in debug mode | Put Flask in debug mode
| Python | mit | jcpeterson/Dallinger,suchow/Wallace,Dallinger/Dallinger,Dallinger/Dallinger,jcpeterson/Dallinger,Dallinger/Dallinger,jcpeterson/Dallinger,Dallinger/Dallinger,berkeley-cocosci/Wallace,berkeley-cocosci/Wallace,Dallinger/Dallinger,suchow/Wallace,jcpeterson/Dallinger,suchow/Wallace,jcpeterson/Dallinger,berkeley-cocosci/Wallace | from flask import Flask
import experiments
import db
app = Flask(__name__)
session = db.init_db(drop_all=True)
@app.route('/')
def index():
return 'Index page'
@app.route('/demo2')
def start():
experiment = experiments.Demo2(session)
experiment.add_and_trigger_sources() # Add any sources
process = experiment.process # Step through the process
for i in xrange(experiment.num_steps):
process.step()
if __name__ == "__main__":
app.run()
print session
Put Flask in debug mode | from flask import Flask
import experiments
import db
app = Flask(__name__)
session = db.init_db(drop_all=True)
@app.route('/')
def index():
return 'Index page'
@app.route('/demo2')
def start():
experiment = experiments.Demo2(session)
experiment.add_and_trigger_sources() # Add any sources
process = experiment.process # Step through the process
for i in xrange(experiment.num_steps):
process.step()
if __name__ == "__main__":
app.debug = True
app.run()
| <commit_before>from flask import Flask
import experiments
import db
app = Flask(__name__)
session = db.init_db(drop_all=True)
@app.route('/')
def index():
return 'Index page'
@app.route('/demo2')
def start():
experiment = experiments.Demo2(session)
experiment.add_and_trigger_sources() # Add any sources
process = experiment.process # Step through the process
for i in xrange(experiment.num_steps):
process.step()
if __name__ == "__main__":
app.run()
print session
<commit_msg>Put Flask in debug mode<commit_after> | from flask import Flask
import experiments
import db
app = Flask(__name__)
session = db.init_db(drop_all=True)
@app.route('/')
def index():
return 'Index page'
@app.route('/demo2')
def start():
experiment = experiments.Demo2(session)
experiment.add_and_trigger_sources() # Add any sources
process = experiment.process # Step through the process
for i in xrange(experiment.num_steps):
process.step()
if __name__ == "__main__":
app.debug = True
app.run()
| from flask import Flask
import experiments
import db
app = Flask(__name__)
session = db.init_db(drop_all=True)
@app.route('/')
def index():
return 'Index page'
@app.route('/demo2')
def start():
experiment = experiments.Demo2(session)
experiment.add_and_trigger_sources() # Add any sources
process = experiment.process # Step through the process
for i in xrange(experiment.num_steps):
process.step()
if __name__ == "__main__":
app.run()
print session
Put Flask in debug modefrom flask import Flask
import experiments
import db
app = Flask(__name__)
session = db.init_db(drop_all=True)
@app.route('/')
def index():
return 'Index page'
@app.route('/demo2')
def start():
experiment = experiments.Demo2(session)
experiment.add_and_trigger_sources() # Add any sources
process = experiment.process # Step through the process
for i in xrange(experiment.num_steps):
process.step()
if __name__ == "__main__":
app.debug = True
app.run()
| <commit_before>from flask import Flask
import experiments
import db
app = Flask(__name__)
session = db.init_db(drop_all=True)
@app.route('/')
def index():
return 'Index page'
@app.route('/demo2')
def start():
experiment = experiments.Demo2(session)
experiment.add_and_trigger_sources() # Add any sources
process = experiment.process # Step through the process
for i in xrange(experiment.num_steps):
process.step()
if __name__ == "__main__":
app.run()
print session
<commit_msg>Put Flask in debug mode<commit_after>from flask import Flask
import experiments
import db
app = Flask(__name__)
session = db.init_db(drop_all=True)
@app.route('/')
def index():
return 'Index page'
@app.route('/demo2')
def start():
experiment = experiments.Demo2(session)
experiment.add_and_trigger_sources() # Add any sources
process = experiment.process # Step through the process
for i in xrange(experiment.num_steps):
process.step()
if __name__ == "__main__":
app.debug = True
app.run()
|
2f18718f2650c3f5a34748588839899d09cac588 | tests/fields/test_strings.py | tests/fields/test_strings.py | import steel
import unittest
class BytesTests(unittest.TestCase):
def test_encode(self):
field = steel.Bytes(size=3)
self.assertEqual(field.encode(b'abc'), b'abc')
def test_decode(self):
field = steel.Bytes(size=3)
self.assertEqual(field.decode(b'abc'), b'abc')
| import steel
import unittest
class BytesTests(unittest.TestCase):
def test_encode(self):
field = steel.Bytes(size=3)
self.assertEqual(field.encode(b'abc'), b'abc')
def test_decode(self):
field = steel.Bytes(size=3)
self.assertEqual(field.decode(b'abc'), b'ac')
| Break a test to see if Travis picks it up | Break a test to see if Travis picks it up
| Python | bsd-3-clause | gulopine/steel-experiment | import steel
import unittest
class BytesTests(unittest.TestCase):
def test_encode(self):
field = steel.Bytes(size=3)
self.assertEqual(field.encode(b'abc'), b'abc')
def test_decode(self):
field = steel.Bytes(size=3)
self.assertEqual(field.decode(b'abc'), b'abc')
Break a test to see if Travis picks it up | import steel
import unittest
class BytesTests(unittest.TestCase):
def test_encode(self):
field = steel.Bytes(size=3)
self.assertEqual(field.encode(b'abc'), b'abc')
def test_decode(self):
field = steel.Bytes(size=3)
self.assertEqual(field.decode(b'abc'), b'ac')
| <commit_before>import steel
import unittest
class BytesTests(unittest.TestCase):
def test_encode(self):
field = steel.Bytes(size=3)
self.assertEqual(field.encode(b'abc'), b'abc')
def test_decode(self):
field = steel.Bytes(size=3)
self.assertEqual(field.decode(b'abc'), b'abc')
<commit_msg>Break a test to see if Travis picks it up<commit_after> | import steel
import unittest
class BytesTests(unittest.TestCase):
def test_encode(self):
field = steel.Bytes(size=3)
self.assertEqual(field.encode(b'abc'), b'abc')
def test_decode(self):
field = steel.Bytes(size=3)
self.assertEqual(field.decode(b'abc'), b'ac')
| import steel
import unittest
class BytesTests(unittest.TestCase):
def test_encode(self):
field = steel.Bytes(size=3)
self.assertEqual(field.encode(b'abc'), b'abc')
def test_decode(self):
field = steel.Bytes(size=3)
self.assertEqual(field.decode(b'abc'), b'abc')
Break a test to see if Travis picks it upimport steel
import unittest
class BytesTests(unittest.TestCase):
def test_encode(self):
field = steel.Bytes(size=3)
self.assertEqual(field.encode(b'abc'), b'abc')
def test_decode(self):
field = steel.Bytes(size=3)
self.assertEqual(field.decode(b'abc'), b'ac')
| <commit_before>import steel
import unittest
class BytesTests(unittest.TestCase):
def test_encode(self):
field = steel.Bytes(size=3)
self.assertEqual(field.encode(b'abc'), b'abc')
def test_decode(self):
field = steel.Bytes(size=3)
self.assertEqual(field.decode(b'abc'), b'abc')
<commit_msg>Break a test to see if Travis picks it up<commit_after>import steel
import unittest
class BytesTests(unittest.TestCase):
def test_encode(self):
field = steel.Bytes(size=3)
self.assertEqual(field.encode(b'abc'), b'abc')
def test_decode(self):
field = steel.Bytes(size=3)
self.assertEqual(field.decode(b'abc'), b'ac')
|
e7766ce068eabea30c81ba699c77ed2fe488d69d | yacs/settings/development.py | yacs/settings/development.py | from yacs.settings.base import settings
__all__ = ['settings']
with settings as s:
s.DEBUG = True
s.MIDDLEWARE_CLASSES += (
'devserver.middleware.DevServerMiddleware',
)
@s.lazy_eval
def debug_install_apps(s):
if s.DEBUG:
s.INSTALLED_APPS += (
'django_jasmine',
'devserver',
)
s.DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'yacs',
'USER': 'timetable',
'PASSWORD': 'thereisn0sp00n',
'HOST': 'localhost',
'PORT': '',
'OPTIONS': {
'autocommit': True,
}
}
}
| from yacs.settings.base import settings
__all__ = ['settings']
with settings as s:
s.DEBUG = True
s.MIDDLEWARE_CLASSES += (
'devserver.middleware.DevServerMiddleware',
)
@s.lazy_eval
def debug_install_apps(s):
if s.DEBUG:
s.INSTALLED_APPS += (
'django_jasmine',
'devserver',
)
s.DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'mydata',
'USER': 'postgreuser',
'PASSWORD': 'postgre',
'HOST': 'localhost',
'PORT': '',
'OPTIONS': {
'autocommit': True,
}
}
}
| Revert "corrected database settings merge again" | Revert "corrected database settings merge again"
This reverts commit 8d04d1c731aaed33c586993002f5e713c3fa1408.
| Python | mit | JGrippo/YACS,jeffh/YACS,jeffh/YACS,JGrippo/YACS,jeffh/YACS,JGrippo/YACS,JGrippo/YACS,jeffh/YACS | from yacs.settings.base import settings
__all__ = ['settings']
with settings as s:
s.DEBUG = True
s.MIDDLEWARE_CLASSES += (
'devserver.middleware.DevServerMiddleware',
)
@s.lazy_eval
def debug_install_apps(s):
if s.DEBUG:
s.INSTALLED_APPS += (
'django_jasmine',
'devserver',
)
s.DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'yacs',
'USER': 'timetable',
'PASSWORD': 'thereisn0sp00n',
'HOST': 'localhost',
'PORT': '',
'OPTIONS': {
'autocommit': True,
}
}
}
Revert "corrected database settings merge again"
This reverts commit 8d04d1c731aaed33c586993002f5e713c3fa1408. | from yacs.settings.base import settings
__all__ = ['settings']
with settings as s:
s.DEBUG = True
s.MIDDLEWARE_CLASSES += (
'devserver.middleware.DevServerMiddleware',
)
@s.lazy_eval
def debug_install_apps(s):
if s.DEBUG:
s.INSTALLED_APPS += (
'django_jasmine',
'devserver',
)
s.DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'mydata',
'USER': 'postgreuser',
'PASSWORD': 'postgre',
'HOST': 'localhost',
'PORT': '',
'OPTIONS': {
'autocommit': True,
}
}
}
| <commit_before>from yacs.settings.base import settings
__all__ = ['settings']
with settings as s:
s.DEBUG = True
s.MIDDLEWARE_CLASSES += (
'devserver.middleware.DevServerMiddleware',
)
@s.lazy_eval
def debug_install_apps(s):
if s.DEBUG:
s.INSTALLED_APPS += (
'django_jasmine',
'devserver',
)
s.DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'yacs',
'USER': 'timetable',
'PASSWORD': 'thereisn0sp00n',
'HOST': 'localhost',
'PORT': '',
'OPTIONS': {
'autocommit': True,
}
}
}
<commit_msg>Revert "corrected database settings merge again"
This reverts commit 8d04d1c731aaed33c586993002f5e713c3fa1408.<commit_after> | from yacs.settings.base import settings
__all__ = ['settings']
with settings as s:
s.DEBUG = True
s.MIDDLEWARE_CLASSES += (
'devserver.middleware.DevServerMiddleware',
)
@s.lazy_eval
def debug_install_apps(s):
if s.DEBUG:
s.INSTALLED_APPS += (
'django_jasmine',
'devserver',
)
s.DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'mydata',
'USER': 'postgreuser',
'PASSWORD': 'postgre',
'HOST': 'localhost',
'PORT': '',
'OPTIONS': {
'autocommit': True,
}
}
}
| from yacs.settings.base import settings
__all__ = ['settings']
with settings as s:
s.DEBUG = True
s.MIDDLEWARE_CLASSES += (
'devserver.middleware.DevServerMiddleware',
)
@s.lazy_eval
def debug_install_apps(s):
if s.DEBUG:
s.INSTALLED_APPS += (
'django_jasmine',
'devserver',
)
s.DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'yacs',
'USER': 'timetable',
'PASSWORD': 'thereisn0sp00n',
'HOST': 'localhost',
'PORT': '',
'OPTIONS': {
'autocommit': True,
}
}
}
Revert "corrected database settings merge again"
This reverts commit 8d04d1c731aaed33c586993002f5e713c3fa1408.from yacs.settings.base import settings
__all__ = ['settings']
with settings as s:
s.DEBUG = True
s.MIDDLEWARE_CLASSES += (
'devserver.middleware.DevServerMiddleware',
)
@s.lazy_eval
def debug_install_apps(s):
if s.DEBUG:
s.INSTALLED_APPS += (
'django_jasmine',
'devserver',
)
s.DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'mydata',
'USER': 'postgreuser',
'PASSWORD': 'postgre',
'HOST': 'localhost',
'PORT': '',
'OPTIONS': {
'autocommit': True,
}
}
}
| <commit_before>from yacs.settings.base import settings
__all__ = ['settings']
with settings as s:
s.DEBUG = True
s.MIDDLEWARE_CLASSES += (
'devserver.middleware.DevServerMiddleware',
)
@s.lazy_eval
def debug_install_apps(s):
if s.DEBUG:
s.INSTALLED_APPS += (
'django_jasmine',
'devserver',
)
s.DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'yacs',
'USER': 'timetable',
'PASSWORD': 'thereisn0sp00n',
'HOST': 'localhost',
'PORT': '',
'OPTIONS': {
'autocommit': True,
}
}
}
<commit_msg>Revert "corrected database settings merge again"
This reverts commit 8d04d1c731aaed33c586993002f5e713c3fa1408.<commit_after>from yacs.settings.base import settings
__all__ = ['settings']
with settings as s:
s.DEBUG = True
s.MIDDLEWARE_CLASSES += (
'devserver.middleware.DevServerMiddleware',
)
@s.lazy_eval
def debug_install_apps(s):
if s.DEBUG:
s.INSTALLED_APPS += (
'django_jasmine',
'devserver',
)
s.DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'mydata',
'USER': 'postgreuser',
'PASSWORD': 'postgre',
'HOST': 'localhost',
'PORT': '',
'OPTIONS': {
'autocommit': True,
}
}
}
|
1e3f60518402835336c16017b5ba172dc0ef6087 | opps/core/admin.py | opps/core/admin.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.contrib import admin
from django.utils import timezone
from django.conf import settings
from django.contrib.sites.models import Site
from django.contrib.auth import get_user_model
class PublishableAdmin(admin.ModelAdmin):
"""
Overrides standard admin.ModelAdmin save_model method
It sets user (author) based on data from requet.
"""
list_display = ['title', 'channel_name', 'date_available', 'published']
list_filter = ['date_available', 'published', 'channel_name',
'child_class']
search_fields = ['title', 'slug', 'headline', 'channel_name']
exclude = ('user',)
def save_model(self, request, obj, form, change):
print request.user, request.user.id
if getattr(obj, 'pk', None) is None:
obj.user = get_user_model().objects.get(pk=request.user.pk)
obj.date_insert = timezone.now()
obj.site = Site.objects.get(pk=settings.SITE_ID)
obj.date_update = timezone.now()
obj.save()
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.contrib import admin
from django.utils import timezone
from django.conf import settings
from django.contrib.sites.models import Site
from django.contrib.auth import get_user_model
class PublishableAdmin(admin.ModelAdmin):
"""
Overrides standard admin.ModelAdmin save_model method
It sets user (author) based on data from requet.
"""
list_display = ['title', 'channel_name', 'date_available', 'published']
list_filter = ['date_available', 'published', 'channel_name',
'child_class']
search_fields = ['title', 'slug', 'headline', 'channel_name']
exclude = ('user',)
def save_model(self, request, obj, form, change):
if getattr(obj, 'pk', None) is None:
obj.user = get_user_model().objects.get(pk=request.user.pk)
obj.date_insert = timezone.now()
obj.site = Site.objects.get(pk=settings.SITE_ID)
obj.date_update = timezone.now()
obj.save()
| Remove prin on save_model PublishableAdmin | Remove prin on save_model PublishableAdmin
| Python | mit | jeanmask/opps,YACOWS/opps,opps/opps,YACOWS/opps,YACOWS/opps,williamroot/opps,williamroot/opps,opps/opps,williamroot/opps,jeanmask/opps,jeanmask/opps,opps/opps,jeanmask/opps,YACOWS/opps,opps/opps,williamroot/opps | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.contrib import admin
from django.utils import timezone
from django.conf import settings
from django.contrib.sites.models import Site
from django.contrib.auth import get_user_model
class PublishableAdmin(admin.ModelAdmin):
"""
Overrides standard admin.ModelAdmin save_model method
It sets user (author) based on data from requet.
"""
list_display = ['title', 'channel_name', 'date_available', 'published']
list_filter = ['date_available', 'published', 'channel_name',
'child_class']
search_fields = ['title', 'slug', 'headline', 'channel_name']
exclude = ('user',)
def save_model(self, request, obj, form, change):
print request.user, request.user.id
if getattr(obj, 'pk', None) is None:
obj.user = get_user_model().objects.get(pk=request.user.pk)
obj.date_insert = timezone.now()
obj.site = Site.objects.get(pk=settings.SITE_ID)
obj.date_update = timezone.now()
obj.save()
Remove prin on save_model PublishableAdmin | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.contrib import admin
from django.utils import timezone
from django.conf import settings
from django.contrib.sites.models import Site
from django.contrib.auth import get_user_model
class PublishableAdmin(admin.ModelAdmin):
"""
Overrides standard admin.ModelAdmin save_model method
It sets user (author) based on data from requet.
"""
list_display = ['title', 'channel_name', 'date_available', 'published']
list_filter = ['date_available', 'published', 'channel_name',
'child_class']
search_fields = ['title', 'slug', 'headline', 'channel_name']
exclude = ('user',)
def save_model(self, request, obj, form, change):
if getattr(obj, 'pk', None) is None:
obj.user = get_user_model().objects.get(pk=request.user.pk)
obj.date_insert = timezone.now()
obj.site = Site.objects.get(pk=settings.SITE_ID)
obj.date_update = timezone.now()
obj.save()
| <commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.contrib import admin
from django.utils import timezone
from django.conf import settings
from django.contrib.sites.models import Site
from django.contrib.auth import get_user_model
class PublishableAdmin(admin.ModelAdmin):
"""
Overrides standard admin.ModelAdmin save_model method
It sets user (author) based on data from requet.
"""
list_display = ['title', 'channel_name', 'date_available', 'published']
list_filter = ['date_available', 'published', 'channel_name',
'child_class']
search_fields = ['title', 'slug', 'headline', 'channel_name']
exclude = ('user',)
def save_model(self, request, obj, form, change):
print request.user, request.user.id
if getattr(obj, 'pk', None) is None:
obj.user = get_user_model().objects.get(pk=request.user.pk)
obj.date_insert = timezone.now()
obj.site = Site.objects.get(pk=settings.SITE_ID)
obj.date_update = timezone.now()
obj.save()
<commit_msg>Remove prin on save_model PublishableAdmin<commit_after> | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.contrib import admin
from django.utils import timezone
from django.conf import settings
from django.contrib.sites.models import Site
from django.contrib.auth import get_user_model
class PublishableAdmin(admin.ModelAdmin):
"""
Overrides standard admin.ModelAdmin save_model method
It sets user (author) based on data from requet.
"""
list_display = ['title', 'channel_name', 'date_available', 'published']
list_filter = ['date_available', 'published', 'channel_name',
'child_class']
search_fields = ['title', 'slug', 'headline', 'channel_name']
exclude = ('user',)
def save_model(self, request, obj, form, change):
if getattr(obj, 'pk', None) is None:
obj.user = get_user_model().objects.get(pk=request.user.pk)
obj.date_insert = timezone.now()
obj.site = Site.objects.get(pk=settings.SITE_ID)
obj.date_update = timezone.now()
obj.save()
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.contrib import admin
from django.utils import timezone
from django.conf import settings
from django.contrib.sites.models import Site
from django.contrib.auth import get_user_model
class PublishableAdmin(admin.ModelAdmin):
"""
Overrides standard admin.ModelAdmin save_model method
It sets user (author) based on data from requet.
"""
list_display = ['title', 'channel_name', 'date_available', 'published']
list_filter = ['date_available', 'published', 'channel_name',
'child_class']
search_fields = ['title', 'slug', 'headline', 'channel_name']
exclude = ('user',)
def save_model(self, request, obj, form, change):
print request.user, request.user.id
if getattr(obj, 'pk', None) is None:
obj.user = get_user_model().objects.get(pk=request.user.pk)
obj.date_insert = timezone.now()
obj.site = Site.objects.get(pk=settings.SITE_ID)
obj.date_update = timezone.now()
obj.save()
Remove prin on save_model PublishableAdmin#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.contrib import admin
from django.utils import timezone
from django.conf import settings
from django.contrib.sites.models import Site
from django.contrib.auth import get_user_model
class PublishableAdmin(admin.ModelAdmin):
"""
Overrides standard admin.ModelAdmin save_model method
It sets user (author) based on data from requet.
"""
list_display = ['title', 'channel_name', 'date_available', 'published']
list_filter = ['date_available', 'published', 'channel_name',
'child_class']
search_fields = ['title', 'slug', 'headline', 'channel_name']
exclude = ('user',)
def save_model(self, request, obj, form, change):
if getattr(obj, 'pk', None) is None:
obj.user = get_user_model().objects.get(pk=request.user.pk)
obj.date_insert = timezone.now()
obj.site = Site.objects.get(pk=settings.SITE_ID)
obj.date_update = timezone.now()
obj.save()
| <commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.contrib import admin
from django.utils import timezone
from django.conf import settings
from django.contrib.sites.models import Site
from django.contrib.auth import get_user_model
class PublishableAdmin(admin.ModelAdmin):
"""
Overrides standard admin.ModelAdmin save_model method
It sets user (author) based on data from requet.
"""
list_display = ['title', 'channel_name', 'date_available', 'published']
list_filter = ['date_available', 'published', 'channel_name',
'child_class']
search_fields = ['title', 'slug', 'headline', 'channel_name']
exclude = ('user',)
def save_model(self, request, obj, form, change):
print request.user, request.user.id
if getattr(obj, 'pk', None) is None:
obj.user = get_user_model().objects.get(pk=request.user.pk)
obj.date_insert = timezone.now()
obj.site = Site.objects.get(pk=settings.SITE_ID)
obj.date_update = timezone.now()
obj.save()
<commit_msg>Remove prin on save_model PublishableAdmin<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.contrib import admin
from django.utils import timezone
from django.conf import settings
from django.contrib.sites.models import Site
from django.contrib.auth import get_user_model
class PublishableAdmin(admin.ModelAdmin):
"""
Overrides standard admin.ModelAdmin save_model method
It sets user (author) based on data from requet.
"""
list_display = ['title', 'channel_name', 'date_available', 'published']
list_filter = ['date_available', 'published', 'channel_name',
'child_class']
search_fields = ['title', 'slug', 'headline', 'channel_name']
exclude = ('user',)
def save_model(self, request, obj, form, change):
if getattr(obj, 'pk', None) is None:
obj.user = get_user_model().objects.get(pk=request.user.pk)
obj.date_insert = timezone.now()
obj.site = Site.objects.get(pk=settings.SITE_ID)
obj.date_update = timezone.now()
obj.save()
|
da01999b6adcb79955a416ce3b3de50769adfe34 | opps/core/utils.py | opps/core/utils.py | # coding: utf-8
from django.db.models import get_models, get_app
def get_app_model(appname, suffix=""):
app_label = appname.split('.')[-1]
models = [model for model in get_models(get_app(app_label))
if (model.__name__.endswith(suffix) or not suffix)
and model._meta.app_label == app_label]
return models and models[0]
def class_load(name):
mod = __import__(name)
components = name.split('.')
for comp in components[1:]:
mod = getattr(mod, comp)
return mod
| # coding: utf-8
from django.db.models import get_models, get_app
from django.template import loader, TemplateDoesNotExist
def get_app_model(appname, suffix=""):
app_label = appname.split('.')[-1]
models = [model for model in get_models(get_app(app_label))
if (model.__name__.endswith(suffix) or not suffix)
and model._meta.app_label == app_label]
return models and models[0]
def class_load(name):
mod = __import__(name)
components = name.split('.')
for comp in components[1:]:
mod = getattr(mod, comp)
return mod
def get_template_path(path):
try:
template = loader.find_template(path)
if template[1]:
return template[1].name
for template_loader in loader.template_source_loaders:
try:
source, origin = template_loader.load_template_source(path)
return origin
except TemplateDoesNotExist:
pass
raise TemplateDoesNotExist(path)
except TemplateDoesNotExist:
return None
| Add new module, get template path return absolut file path | Add new module, get template path
return absolut file path
| Python | mit | opps/opps,jeanmask/opps,YACOWS/opps,YACOWS/opps,YACOWS/opps,opps/opps,YACOWS/opps,williamroot/opps,jeanmask/opps,williamroot/opps,opps/opps,jeanmask/opps,williamroot/opps,opps/opps,jeanmask/opps,williamroot/opps | # coding: utf-8
from django.db.models import get_models, get_app
def get_app_model(appname, suffix=""):
app_label = appname.split('.')[-1]
models = [model for model in get_models(get_app(app_label))
if (model.__name__.endswith(suffix) or not suffix)
and model._meta.app_label == app_label]
return models and models[0]
def class_load(name):
mod = __import__(name)
components = name.split('.')
for comp in components[1:]:
mod = getattr(mod, comp)
return mod
Add new module, get template path
return absolut file path | # coding: utf-8
from django.db.models import get_models, get_app
from django.template import loader, TemplateDoesNotExist
def get_app_model(appname, suffix=""):
app_label = appname.split('.')[-1]
models = [model for model in get_models(get_app(app_label))
if (model.__name__.endswith(suffix) or not suffix)
and model._meta.app_label == app_label]
return models and models[0]
def class_load(name):
mod = __import__(name)
components = name.split('.')
for comp in components[1:]:
mod = getattr(mod, comp)
return mod
def get_template_path(path):
try:
template = loader.find_template(path)
if template[1]:
return template[1].name
for template_loader in loader.template_source_loaders:
try:
source, origin = template_loader.load_template_source(path)
return origin
except TemplateDoesNotExist:
pass
raise TemplateDoesNotExist(path)
except TemplateDoesNotExist:
return None
| <commit_before># coding: utf-8
from django.db.models import get_models, get_app
def get_app_model(appname, suffix=""):
app_label = appname.split('.')[-1]
models = [model for model in get_models(get_app(app_label))
if (model.__name__.endswith(suffix) or not suffix)
and model._meta.app_label == app_label]
return models and models[0]
def class_load(name):
mod = __import__(name)
components = name.split('.')
for comp in components[1:]:
mod = getattr(mod, comp)
return mod
<commit_msg>Add new module, get template path
return absolut file path<commit_after> | # coding: utf-8
from django.db.models import get_models, get_app
from django.template import loader, TemplateDoesNotExist
def get_app_model(appname, suffix=""):
app_label = appname.split('.')[-1]
models = [model for model in get_models(get_app(app_label))
if (model.__name__.endswith(suffix) or not suffix)
and model._meta.app_label == app_label]
return models and models[0]
def class_load(name):
mod = __import__(name)
components = name.split('.')
for comp in components[1:]:
mod = getattr(mod, comp)
return mod
def get_template_path(path):
try:
template = loader.find_template(path)
if template[1]:
return template[1].name
for template_loader in loader.template_source_loaders:
try:
source, origin = template_loader.load_template_source(path)
return origin
except TemplateDoesNotExist:
pass
raise TemplateDoesNotExist(path)
except TemplateDoesNotExist:
return None
| # coding: utf-8
from django.db.models import get_models, get_app
def get_app_model(appname, suffix=""):
app_label = appname.split('.')[-1]
models = [model for model in get_models(get_app(app_label))
if (model.__name__.endswith(suffix) or not suffix)
and model._meta.app_label == app_label]
return models and models[0]
def class_load(name):
mod = __import__(name)
components = name.split('.')
for comp in components[1:]:
mod = getattr(mod, comp)
return mod
Add new module, get template path
return absolut file path# coding: utf-8
from django.db.models import get_models, get_app
from django.template import loader, TemplateDoesNotExist
def get_app_model(appname, suffix=""):
app_label = appname.split('.')[-1]
models = [model for model in get_models(get_app(app_label))
if (model.__name__.endswith(suffix) or not suffix)
and model._meta.app_label == app_label]
return models and models[0]
def class_load(name):
mod = __import__(name)
components = name.split('.')
for comp in components[1:]:
mod = getattr(mod, comp)
return mod
def get_template_path(path):
try:
template = loader.find_template(path)
if template[1]:
return template[1].name
for template_loader in loader.template_source_loaders:
try:
source, origin = template_loader.load_template_source(path)
return origin
except TemplateDoesNotExist:
pass
raise TemplateDoesNotExist(path)
except TemplateDoesNotExist:
return None
| <commit_before># coding: utf-8
from django.db.models import get_models, get_app
def get_app_model(appname, suffix=""):
app_label = appname.split('.')[-1]
models = [model for model in get_models(get_app(app_label))
if (model.__name__.endswith(suffix) or not suffix)
and model._meta.app_label == app_label]
return models and models[0]
def class_load(name):
mod = __import__(name)
components = name.split('.')
for comp in components[1:]:
mod = getattr(mod, comp)
return mod
<commit_msg>Add new module, get template path
return absolut file path<commit_after># coding: utf-8
from django.db.models import get_models, get_app
from django.template import loader, TemplateDoesNotExist
def get_app_model(appname, suffix=""):
app_label = appname.split('.')[-1]
models = [model for model in get_models(get_app(app_label))
if (model.__name__.endswith(suffix) or not suffix)
and model._meta.app_label == app_label]
return models and models[0]
def class_load(name):
mod = __import__(name)
components = name.split('.')
for comp in components[1:]:
mod = getattr(mod, comp)
return mod
def get_template_path(path):
try:
template = loader.find_template(path)
if template[1]:
return template[1].name
for template_loader in loader.template_source_loaders:
try:
source, origin = template_loader.load_template_source(path)
return origin
except TemplateDoesNotExist:
pass
raise TemplateDoesNotExist(path)
except TemplateDoesNotExist:
return None
|
379be172944f8ae0111842e199470effd4afdaf5 | rest/authUtils.py | rest/authUtils.py | # Author: Braedy Kuzma
from rest_framework import authentication
from rest_framework import exceptions
from ipware.ip import get_ip
from .models import RemoteNode
class nodeToNodeBasicAuth(authentication.BaseAuthentication):
def authenticate(self, request):
"""
This is an authentication backend for our rest API. It implements
HTTP Basic Auth using admin controlled passwords separate from users.
"""
ip = get_ip(request)
print('IP:', ip)
return (None, None)
| # Author: Braedy Kuzma
import base64
from rest_framework import authentication
from rest_framework import exceptions
from ipware.ip import get_ip
from .models import RemoteNode
def createBasicAuthToken(username, password):
"""
This creates an HTTP Basic Auth token from a username and password.
"""
# Format into the HTTP Basic Auth format
tokenString = '{}:{}'.format(username, password)
# Encode into bytes for b64, then into b64
bytesString = tokenString.encode('utf-8')
return base64.b64encode(bytesString)
def parseBasicAuthToken(token):
"""
This parses an HTTP Basic Auth token and returns a tuple of (username,
password).
"""
# Convert the token into a bytes object so b64 can work with it
if isinstance(token, str):
token = token.encode('utf-8')
# Decode from b64 then bytes
parsedBytes = base64.b64decode(token)
parsedString = parsedBytes.decode('utf-8')
# Split out the username, rejoin the password if it had colons
username, *passwordParts = parsedString.split(':')
password = ':'.join(passwordParts)
return (username, password)
class nodeToNodeBasicAuth(authentication.BaseAuthentication):
def authenticate(self, request):
"""
This is an authentication backend for our rest API. It implements
HTTP Basic Auth using admin controlled passwords separate from users.
"""
ip = get_ip(request)
print('IP:', ip)
return (None, None)
| Add basic auth create and parse utils. | Add basic auth create and parse utils.
| Python | apache-2.0 | CMPUT404W17T06/CMPUT404-project,CMPUT404W17T06/CMPUT404-project,CMPUT404W17T06/CMPUT404-project | # Author: Braedy Kuzma
from rest_framework import authentication
from rest_framework import exceptions
from ipware.ip import get_ip
from .models import RemoteNode
class nodeToNodeBasicAuth(authentication.BaseAuthentication):
def authenticate(self, request):
"""
This is an authentication backend for our rest API. It implements
HTTP Basic Auth using admin controlled passwords separate from users.
"""
ip = get_ip(request)
print('IP:', ip)
return (None, None)
Add basic auth create and parse utils. | # Author: Braedy Kuzma
import base64
from rest_framework import authentication
from rest_framework import exceptions
from ipware.ip import get_ip
from .models import RemoteNode
def createBasicAuthToken(username, password):
"""
This creates an HTTP Basic Auth token from a username and password.
"""
# Format into the HTTP Basic Auth format
tokenString = '{}:{}'.format(username, password)
# Encode into bytes for b64, then into b64
bytesString = tokenString.encode('utf-8')
return base64.b64encode(bytesString)
def parseBasicAuthToken(token):
"""
This parses an HTTP Basic Auth token and returns a tuple of (username,
password).
"""
# Convert the token into a bytes object so b64 can work with it
if isinstance(token, str):
token = token.encode('utf-8')
# Decode from b64 then bytes
parsedBytes = base64.b64decode(token)
parsedString = parsedBytes.decode('utf-8')
# Split out the username, rejoin the password if it had colons
username, *passwordParts = parsedString.split(':')
password = ':'.join(passwordParts)
return (username, password)
class nodeToNodeBasicAuth(authentication.BaseAuthentication):
def authenticate(self, request):
"""
This is an authentication backend for our rest API. It implements
HTTP Basic Auth using admin controlled passwords separate from users.
"""
ip = get_ip(request)
print('IP:', ip)
return (None, None)
| <commit_before># Author: Braedy Kuzma
from rest_framework import authentication
from rest_framework import exceptions
from ipware.ip import get_ip
from .models import RemoteNode
class nodeToNodeBasicAuth(authentication.BaseAuthentication):
def authenticate(self, request):
"""
This is an authentication backend for our rest API. It implements
HTTP Basic Auth using admin controlled passwords separate from users.
"""
ip = get_ip(request)
print('IP:', ip)
return (None, None)
<commit_msg>Add basic auth create and parse utils.<commit_after> | # Author: Braedy Kuzma
import base64
from rest_framework import authentication
from rest_framework import exceptions
from ipware.ip import get_ip
from .models import RemoteNode
def createBasicAuthToken(username, password):
"""
This creates an HTTP Basic Auth token from a username and password.
"""
# Format into the HTTP Basic Auth format
tokenString = '{}:{}'.format(username, password)
# Encode into bytes for b64, then into b64
bytesString = tokenString.encode('utf-8')
return base64.b64encode(bytesString)
def parseBasicAuthToken(token):
"""
This parses an HTTP Basic Auth token and returns a tuple of (username,
password).
"""
# Convert the token into a bytes object so b64 can work with it
if isinstance(token, str):
token = token.encode('utf-8')
# Decode from b64 then bytes
parsedBytes = base64.b64decode(token)
parsedString = parsedBytes.decode('utf-8')
# Split out the username, rejoin the password if it had colons
username, *passwordParts = parsedString.split(':')
password = ':'.join(passwordParts)
return (username, password)
class nodeToNodeBasicAuth(authentication.BaseAuthentication):
def authenticate(self, request):
"""
This is an authentication backend for our rest API. It implements
HTTP Basic Auth using admin controlled passwords separate from users.
"""
ip = get_ip(request)
print('IP:', ip)
return (None, None)
| # Author: Braedy Kuzma
from rest_framework import authentication
from rest_framework import exceptions
from ipware.ip import get_ip
from .models import RemoteNode
class nodeToNodeBasicAuth(authentication.BaseAuthentication):
def authenticate(self, request):
"""
This is an authentication backend for our rest API. It implements
HTTP Basic Auth using admin controlled passwords separate from users.
"""
ip = get_ip(request)
print('IP:', ip)
return (None, None)
Add basic auth create and parse utils.# Author: Braedy Kuzma
import base64
from rest_framework import authentication
from rest_framework import exceptions
from ipware.ip import get_ip
from .models import RemoteNode
def createBasicAuthToken(username, password):
"""
This creates an HTTP Basic Auth token from a username and password.
"""
# Format into the HTTP Basic Auth format
tokenString = '{}:{}'.format(username, password)
# Encode into bytes for b64, then into b64
bytesString = tokenString.encode('utf-8')
return base64.b64encode(bytesString)
def parseBasicAuthToken(token):
"""
This parses an HTTP Basic Auth token and returns a tuple of (username,
password).
"""
# Convert the token into a bytes object so b64 can work with it
if isinstance(token, str):
token = token.encode('utf-8')
# Decode from b64 then bytes
parsedBytes = base64.b64decode(token)
parsedString = parsedBytes.decode('utf-8')
# Split out the username, rejoin the password if it had colons
username, *passwordParts = parsedString.split(':')
password = ':'.join(passwordParts)
return (username, password)
class nodeToNodeBasicAuth(authentication.BaseAuthentication):
def authenticate(self, request):
"""
This is an authentication backend for our rest API. It implements
HTTP Basic Auth using admin controlled passwords separate from users.
"""
ip = get_ip(request)
print('IP:', ip)
return (None, None)
| <commit_before># Author: Braedy Kuzma
from rest_framework import authentication
from rest_framework import exceptions
from ipware.ip import get_ip
from .models import RemoteNode
class nodeToNodeBasicAuth(authentication.BaseAuthentication):
def authenticate(self, request):
"""
This is an authentication backend for our rest API. It implements
HTTP Basic Auth using admin controlled passwords separate from users.
"""
ip = get_ip(request)
print('IP:', ip)
return (None, None)
<commit_msg>Add basic auth create and parse utils.<commit_after># Author: Braedy Kuzma
import base64
from rest_framework import authentication
from rest_framework import exceptions
from ipware.ip import get_ip
from .models import RemoteNode
def createBasicAuthToken(username, password):
"""
This creates an HTTP Basic Auth token from a username and password.
"""
# Format into the HTTP Basic Auth format
tokenString = '{}:{}'.format(username, password)
# Encode into bytes for b64, then into b64
bytesString = tokenString.encode('utf-8')
return base64.b64encode(bytesString)
def parseBasicAuthToken(token):
"""
This parses an HTTP Basic Auth token and returns a tuple of (username,
password).
"""
# Convert the token into a bytes object so b64 can work with it
if isinstance(token, str):
token = token.encode('utf-8')
# Decode from b64 then bytes
parsedBytes = base64.b64decode(token)
parsedString = parsedBytes.decode('utf-8')
# Split out the username, rejoin the password if it had colons
username, *passwordParts = parsedString.split(':')
password = ':'.join(passwordParts)
return (username, password)
class nodeToNodeBasicAuth(authentication.BaseAuthentication):
def authenticate(self, request):
"""
This is an authentication backend for our rest API. It implements
HTTP Basic Auth using admin controlled passwords separate from users.
"""
ip = get_ip(request)
print('IP:', ip)
return (None, None)
|
a312348380a495c99c1be8adca331e2eec2d1720 | topo/tests/__init__.py | topo/tests/__init__.py | """
Unit tests for Topographica
$Id$
"""
__version__='$Revision$'
### JABALERT!
###
### Should change this to be like topo/patterns/__init__.py, i.e.
### to automatically discover the test files. That way new tests
### can be just dropped in.
import unittest, os
import testboundingregion
import testdummy
import testbitmap
import testsheet
import testsheetview
import testplot
import testplotgroup
import testplotfilesaver
import testsimulator
import testpalette
import testcfsom
import testpatterngenerator
import testmatplotlib
import testpatternpresent
import testdistribution
import testfeaturemap
import testoutputfnsbasic
# CEBHACKALERT: no test for patterns/image.py
# tkgui import calls tkgui/__init__.py, which should contain other test
# imports for that directory.
import tkgui
suite = unittest.TestSuite()
display_loc = os.getenv('DISPLAY')
for key,val in locals().items():
if type(val) == type(unittest) and not val in (unittest, os):
try:
print 'Checking module %s for test suite...' % key,
new_test = getattr(val,'suite')
if hasattr(new_test,'requires_display') and not display_loc:
print 'skipped: No $DISPLAY.'
else:
print 'found.'
suite.addTest(new_test)
except AttributeError,err:
print err
def run(verbosity=1):
unittest.TextTestRunner(verbosity=verbosity).run(suite)
| """
Unit tests for Topographica
$Id$
"""
__version__='$Revision$'
### JABALERT!
###
### Should change this to be like topo/patterns/__init__.py, i.e.
### to automatically discover the test files. That way new tests
### can be just dropped in.
import unittest, os
import testboundingregion
import testdummy
import testbitmap
import testsheet
import testsheetview
import testplot
import testplotgroup
import testplotfilesaver
import testsimulator
import testpalette
import testcfsom
import testpatterngenerator
import testmatplotlib
import testpatternpresent
import testdistribution
import testfeaturemap
import testoutputfnsbasic
import testoutputfnsoptimized
# CEBHACKALERT: no test for patterns/image.py
# tkgui import calls tkgui/__init__.py, which should contain other test
# imports for that directory.
import tkgui
suite = unittest.TestSuite()
display_loc = os.getenv('DISPLAY')
for key,val in locals().items():
if type(val) == type(unittest) and not val in (unittest, os):
try:
print 'Checking module %s for test suite...' % key,
new_test = getattr(val,'suite')
if hasattr(new_test,'requires_display') and not display_loc:
print 'skipped: No $DISPLAY.'
else:
print 'found.'
suite.addTest(new_test)
except AttributeError,err:
print err
def run(verbosity=1):
unittest.TextTestRunner(verbosity=verbosity).run(suite)
| Test of optimized output functions runs automatically. | Test of optimized output functions runs automatically.
| Python | bsd-3-clause | ioam/svn-history,ioam/svn-history,ioam/svn-history,ioam/svn-history,ioam/svn-history | """
Unit tests for Topographica
$Id$
"""
__version__='$Revision$'
### JABALERT!
###
### Should change this to be like topo/patterns/__init__.py, i.e.
### to automatically discover the test files. That way new tests
### can be just dropped in.
import unittest, os
import testboundingregion
import testdummy
import testbitmap
import testsheet
import testsheetview
import testplot
import testplotgroup
import testplotfilesaver
import testsimulator
import testpalette
import testcfsom
import testpatterngenerator
import testmatplotlib
import testpatternpresent
import testdistribution
import testfeaturemap
import testoutputfnsbasic
# CEBHACKALERT: no test for patterns/image.py
# tkgui import calls tkgui/__init__.py, which should contain other test
# imports for that directory.
import tkgui
suite = unittest.TestSuite()
display_loc = os.getenv('DISPLAY')
for key,val in locals().items():
if type(val) == type(unittest) and not val in (unittest, os):
try:
print 'Checking module %s for test suite...' % key,
new_test = getattr(val,'suite')
if hasattr(new_test,'requires_display') and not display_loc:
print 'skipped: No $DISPLAY.'
else:
print 'found.'
suite.addTest(new_test)
except AttributeError,err:
print err
def run(verbosity=1):
unittest.TextTestRunner(verbosity=verbosity).run(suite)
Test of optimized output functions runs automatically. | """
Unit tests for Topographica
$Id$
"""
__version__='$Revision$'
### JABALERT!
###
### Should change this to be like topo/patterns/__init__.py, i.e.
### to automatically discover the test files. That way new tests
### can be just dropped in.
import unittest, os
import testboundingregion
import testdummy
import testbitmap
import testsheet
import testsheetview
import testplot
import testplotgroup
import testplotfilesaver
import testsimulator
import testpalette
import testcfsom
import testpatterngenerator
import testmatplotlib
import testpatternpresent
import testdistribution
import testfeaturemap
import testoutputfnsbasic
import testoutputfnsoptimized
# CEBHACKALERT: no test for patterns/image.py
# tkgui import calls tkgui/__init__.py, which should contain other test
# imports for that directory.
import tkgui
suite = unittest.TestSuite()
display_loc = os.getenv('DISPLAY')
for key,val in locals().items():
if type(val) == type(unittest) and not val in (unittest, os):
try:
print 'Checking module %s for test suite...' % key,
new_test = getattr(val,'suite')
if hasattr(new_test,'requires_display') and not display_loc:
print 'skipped: No $DISPLAY.'
else:
print 'found.'
suite.addTest(new_test)
except AttributeError,err:
print err
def run(verbosity=1):
unittest.TextTestRunner(verbosity=verbosity).run(suite)
| <commit_before>"""
Unit tests for Topographica
$Id$
"""
__version__='$Revision$'
### JABALERT!
###
### Should change this to be like topo/patterns/__init__.py, i.e.
### to automatically discover the test files. That way new tests
### can be just dropped in.
import unittest, os
import testboundingregion
import testdummy
import testbitmap
import testsheet
import testsheetview
import testplot
import testplotgroup
import testplotfilesaver
import testsimulator
import testpalette
import testcfsom
import testpatterngenerator
import testmatplotlib
import testpatternpresent
import testdistribution
import testfeaturemap
import testoutputfnsbasic
# CEBHACKALERT: no test for patterns/image.py
# tkgui import calls tkgui/__init__.py, which should contain other test
# imports for that directory.
import tkgui
suite = unittest.TestSuite()
display_loc = os.getenv('DISPLAY')
for key,val in locals().items():
if type(val) == type(unittest) and not val in (unittest, os):
try:
print 'Checking module %s for test suite...' % key,
new_test = getattr(val,'suite')
if hasattr(new_test,'requires_display') and not display_loc:
print 'skipped: No $DISPLAY.'
else:
print 'found.'
suite.addTest(new_test)
except AttributeError,err:
print err
def run(verbosity=1):
unittest.TextTestRunner(verbosity=verbosity).run(suite)
<commit_msg>Test of optimized output functions runs automatically.<commit_after> | """
Unit tests for Topographica
$Id$
"""
__version__='$Revision$'
### JABALERT!
###
### Should change this to be like topo/patterns/__init__.py, i.e.
### to automatically discover the test files. That way new tests
### can be just dropped in.
import unittest, os
import testboundingregion
import testdummy
import testbitmap
import testsheet
import testsheetview
import testplot
import testplotgroup
import testplotfilesaver
import testsimulator
import testpalette
import testcfsom
import testpatterngenerator
import testmatplotlib
import testpatternpresent
import testdistribution
import testfeaturemap
import testoutputfnsbasic
import testoutputfnsoptimized
# CEBHACKALERT: no test for patterns/image.py
# tkgui import calls tkgui/__init__.py, which should contain other test
# imports for that directory.
import tkgui
suite = unittest.TestSuite()
display_loc = os.getenv('DISPLAY')
for key,val in locals().items():
if type(val) == type(unittest) and not val in (unittest, os):
try:
print 'Checking module %s for test suite...' % key,
new_test = getattr(val,'suite')
if hasattr(new_test,'requires_display') and not display_loc:
print 'skipped: No $DISPLAY.'
else:
print 'found.'
suite.addTest(new_test)
except AttributeError,err:
print err
def run(verbosity=1):
unittest.TextTestRunner(verbosity=verbosity).run(suite)
| """
Unit tests for Topographica
$Id$
"""
__version__='$Revision$'
### JABALERT!
###
### Should change this to be like topo/patterns/__init__.py, i.e.
### to automatically discover the test files. That way new tests
### can be just dropped in.
import unittest, os
import testboundingregion
import testdummy
import testbitmap
import testsheet
import testsheetview
import testplot
import testplotgroup
import testplotfilesaver
import testsimulator
import testpalette
import testcfsom
import testpatterngenerator
import testmatplotlib
import testpatternpresent
import testdistribution
import testfeaturemap
import testoutputfnsbasic
# CEBHACKALERT: no test for patterns/image.py
# tkgui import calls tkgui/__init__.py, which should contain other test
# imports for that directory.
import tkgui
suite = unittest.TestSuite()
display_loc = os.getenv('DISPLAY')
for key,val in locals().items():
if type(val) == type(unittest) and not val in (unittest, os):
try:
print 'Checking module %s for test suite...' % key,
new_test = getattr(val,'suite')
if hasattr(new_test,'requires_display') and not display_loc:
print 'skipped: No $DISPLAY.'
else:
print 'found.'
suite.addTest(new_test)
except AttributeError,err:
print err
def run(verbosity=1):
unittest.TextTestRunner(verbosity=verbosity).run(suite)
Test of optimized output functions runs automatically."""
Unit tests for Topographica
$Id$
"""
__version__='$Revision$'
### JABALERT!
###
### Should change this to be like topo/patterns/__init__.py, i.e.
### to automatically discover the test files. That way new tests
### can be just dropped in.
import unittest, os
import testboundingregion
import testdummy
import testbitmap
import testsheet
import testsheetview
import testplot
import testplotgroup
import testplotfilesaver
import testsimulator
import testpalette
import testcfsom
import testpatterngenerator
import testmatplotlib
import testpatternpresent
import testdistribution
import testfeaturemap
import testoutputfnsbasic
import testoutputfnsoptimized
# CEBHACKALERT: no test for patterns/image.py
# tkgui import calls tkgui/__init__.py, which should contain other test
# imports for that directory.
import tkgui
suite = unittest.TestSuite()
display_loc = os.getenv('DISPLAY')
for key,val in locals().items():
if type(val) == type(unittest) and not val in (unittest, os):
try:
print 'Checking module %s for test suite...' % key,
new_test = getattr(val,'suite')
if hasattr(new_test,'requires_display') and not display_loc:
print 'skipped: No $DISPLAY.'
else:
print 'found.'
suite.addTest(new_test)
except AttributeError,err:
print err
def run(verbosity=1):
unittest.TextTestRunner(verbosity=verbosity).run(suite)
| <commit_before>"""
Unit tests for Topographica
$Id$
"""
__version__='$Revision$'
### JABALERT!
###
### Should change this to be like topo/patterns/__init__.py, i.e.
### to automatically discover the test files. That way new tests
### can be just dropped in.
import unittest, os
import testboundingregion
import testdummy
import testbitmap
import testsheet
import testsheetview
import testplot
import testplotgroup
import testplotfilesaver
import testsimulator
import testpalette
import testcfsom
import testpatterngenerator
import testmatplotlib
import testpatternpresent
import testdistribution
import testfeaturemap
import testoutputfnsbasic
# CEBHACKALERT: no test for patterns/image.py
# tkgui import calls tkgui/__init__.py, which should contain other test
# imports for that directory.
import tkgui
suite = unittest.TestSuite()
display_loc = os.getenv('DISPLAY')
for key,val in locals().items():
if type(val) == type(unittest) and not val in (unittest, os):
try:
print 'Checking module %s for test suite...' % key,
new_test = getattr(val,'suite')
if hasattr(new_test,'requires_display') and not display_loc:
print 'skipped: No $DISPLAY.'
else:
print 'found.'
suite.addTest(new_test)
except AttributeError,err:
print err
def run(verbosity=1):
unittest.TextTestRunner(verbosity=verbosity).run(suite)
<commit_msg>Test of optimized output functions runs automatically.<commit_after>"""
Unit tests for Topographica
$Id$
"""
__version__='$Revision$'
### JABALERT!
###
### Should change this to be like topo/patterns/__init__.py, i.e.
### to automatically discover the test files. That way new tests
### can be just dropped in.
import unittest, os
import testboundingregion
import testdummy
import testbitmap
import testsheet
import testsheetview
import testplot
import testplotgroup
import testplotfilesaver
import testsimulator
import testpalette
import testcfsom
import testpatterngenerator
import testmatplotlib
import testpatternpresent
import testdistribution
import testfeaturemap
import testoutputfnsbasic
import testoutputfnsoptimized
# CEBHACKALERT: no test for patterns/image.py
# tkgui import calls tkgui/__init__.py, which should contain other test
# imports for that directory.
import tkgui
suite = unittest.TestSuite()
display_loc = os.getenv('DISPLAY')
for key,val in locals().items():
if type(val) == type(unittest) and not val in (unittest, os):
try:
print 'Checking module %s for test suite...' % key,
new_test = getattr(val,'suite')
if hasattr(new_test,'requires_display') and not display_loc:
print 'skipped: No $DISPLAY.'
else:
print 'found.'
suite.addTest(new_test)
except AttributeError,err:
print err
def run(verbosity=1):
unittest.TextTestRunner(verbosity=verbosity).run(suite)
|
80448aa6664d13dd58ed42c06248ca4532431aab | dakota_utils/convert.py | dakota_utils/convert.py | #! /usr/bin/env python
#
# Dakota utility programs for converting output.
#
# Mark Piper (mark.piper@colorado.edu)
import shutil
from subprocess import check_call, CalledProcessError
from dakota_utils.read import get_names
def has_interface_column(tab_file):
'''
Returns True if the tabular output file has the v6.1 'interface' column.
'''
try:
val = get_names(tab_file)[1] == 'interface'
except IOError:
raise
else:
return(val)
def strip_interface_column(tab_file):
'''
Strips the 'interface' column from a Dakota 6.1 tabular output file.
'''
try:
bak_file = tab_file + '.orig'
shutil.copyfile(tab_file, bak_file)
cmd = 'cat ' + bak_file +' | colrm 9 18 > ' + tab_file
check_call(cmd, shell=True)
except (IOError, CalledProcessError):
raise
| #! /usr/bin/env python
#
# Dakota utility programs for converting output.
#
# Mark Piper (mark.piper@colorado.edu)
import shutil
from subprocess import check_call, CalledProcessError
from .read import get_names
def has_interface_column(tab_file):
'''
Returns True if the tabular output file has the v6.1 'interface' column.
'''
try:
val = get_names(tab_file)[1] == 'interface'
except IOError:
raise
else:
return(val)
def strip_interface_column(tab_file):
'''
Strips the 'interface' column from a Dakota 6.1 tabular output file.
'''
try:
bak_file = tab_file + '.orig'
shutil.copyfile(tab_file, bak_file)
cmd = 'cat ' + bak_file +' | colrm 9 18 > ' + tab_file
check_call(cmd, shell=True)
except (IOError, CalledProcessError):
raise
| Use a relative import to get the read module | Use a relative import to get the read module
| Python | mit | mdpiper/dakota-experiments,mdpiper/dakota-experiments,mcflugen/dakota-experiments,mdpiper/dakota-experiments,mcflugen/dakota-experiments | #! /usr/bin/env python
#
# Dakota utility programs for converting output.
#
# Mark Piper (mark.piper@colorado.edu)
import shutil
from subprocess import check_call, CalledProcessError
from dakota_utils.read import get_names
def has_interface_column(tab_file):
'''
Returns True if the tabular output file has the v6.1 'interface' column.
'''
try:
val = get_names(tab_file)[1] == 'interface'
except IOError:
raise
else:
return(val)
def strip_interface_column(tab_file):
'''
Strips the 'interface' column from a Dakota 6.1 tabular output file.
'''
try:
bak_file = tab_file + '.orig'
shutil.copyfile(tab_file, bak_file)
cmd = 'cat ' + bak_file +' | colrm 9 18 > ' + tab_file
check_call(cmd, shell=True)
except (IOError, CalledProcessError):
raise
Use a relative import to get the read module | #! /usr/bin/env python
#
# Dakota utility programs for converting output.
#
# Mark Piper (mark.piper@colorado.edu)
import shutil
from subprocess import check_call, CalledProcessError
from .read import get_names
def has_interface_column(tab_file):
'''
Returns True if the tabular output file has the v6.1 'interface' column.
'''
try:
val = get_names(tab_file)[1] == 'interface'
except IOError:
raise
else:
return(val)
def strip_interface_column(tab_file):
'''
Strips the 'interface' column from a Dakota 6.1 tabular output file.
'''
try:
bak_file = tab_file + '.orig'
shutil.copyfile(tab_file, bak_file)
cmd = 'cat ' + bak_file +' | colrm 9 18 > ' + tab_file
check_call(cmd, shell=True)
except (IOError, CalledProcessError):
raise
| <commit_before>#! /usr/bin/env python
#
# Dakota utility programs for converting output.
#
# Mark Piper (mark.piper@colorado.edu)
import shutil
from subprocess import check_call, CalledProcessError
from dakota_utils.read import get_names
def has_interface_column(tab_file):
'''
Returns True if the tabular output file has the v6.1 'interface' column.
'''
try:
val = get_names(tab_file)[1] == 'interface'
except IOError:
raise
else:
return(val)
def strip_interface_column(tab_file):
'''
Strips the 'interface' column from a Dakota 6.1 tabular output file.
'''
try:
bak_file = tab_file + '.orig'
shutil.copyfile(tab_file, bak_file)
cmd = 'cat ' + bak_file +' | colrm 9 18 > ' + tab_file
check_call(cmd, shell=True)
except (IOError, CalledProcessError):
raise
<commit_msg>Use a relative import to get the read module<commit_after> | #! /usr/bin/env python
#
# Dakota utility programs for converting output.
#
# Mark Piper (mark.piper@colorado.edu)
import shutil
from subprocess import check_call, CalledProcessError
from .read import get_names
def has_interface_column(tab_file):
'''
Returns True if the tabular output file has the v6.1 'interface' column.
'''
try:
val = get_names(tab_file)[1] == 'interface'
except IOError:
raise
else:
return(val)
def strip_interface_column(tab_file):
'''
Strips the 'interface' column from a Dakota 6.1 tabular output file.
'''
try:
bak_file = tab_file + '.orig'
shutil.copyfile(tab_file, bak_file)
cmd = 'cat ' + bak_file +' | colrm 9 18 > ' + tab_file
check_call(cmd, shell=True)
except (IOError, CalledProcessError):
raise
| #! /usr/bin/env python
#
# Dakota utility programs for converting output.
#
# Mark Piper (mark.piper@colorado.edu)
import shutil
from subprocess import check_call, CalledProcessError
from dakota_utils.read import get_names
def has_interface_column(tab_file):
'''
Returns True if the tabular output file has the v6.1 'interface' column.
'''
try:
val = get_names(tab_file)[1] == 'interface'
except IOError:
raise
else:
return(val)
def strip_interface_column(tab_file):
'''
Strips the 'interface' column from a Dakota 6.1 tabular output file.
'''
try:
bak_file = tab_file + '.orig'
shutil.copyfile(tab_file, bak_file)
cmd = 'cat ' + bak_file +' | colrm 9 18 > ' + tab_file
check_call(cmd, shell=True)
except (IOError, CalledProcessError):
raise
Use a relative import to get the read module#! /usr/bin/env python
#
# Dakota utility programs for converting output.
#
# Mark Piper (mark.piper@colorado.edu)
import shutil
from subprocess import check_call, CalledProcessError
from .read import get_names
def has_interface_column(tab_file):
'''
Returns True if the tabular output file has the v6.1 'interface' column.
'''
try:
val = get_names(tab_file)[1] == 'interface'
except IOError:
raise
else:
return(val)
def strip_interface_column(tab_file):
'''
Strips the 'interface' column from a Dakota 6.1 tabular output file.
'''
try:
bak_file = tab_file + '.orig'
shutil.copyfile(tab_file, bak_file)
cmd = 'cat ' + bak_file +' | colrm 9 18 > ' + tab_file
check_call(cmd, shell=True)
except (IOError, CalledProcessError):
raise
| <commit_before>#! /usr/bin/env python
#
# Dakota utility programs for converting output.
#
# Mark Piper (mark.piper@colorado.edu)
import shutil
from subprocess import check_call, CalledProcessError
from dakota_utils.read import get_names
def has_interface_column(tab_file):
'''
Returns True if the tabular output file has the v6.1 'interface' column.
'''
try:
val = get_names(tab_file)[1] == 'interface'
except IOError:
raise
else:
return(val)
def strip_interface_column(tab_file):
'''
Strips the 'interface' column from a Dakota 6.1 tabular output file.
'''
try:
bak_file = tab_file + '.orig'
shutil.copyfile(tab_file, bak_file)
cmd = 'cat ' + bak_file +' | colrm 9 18 > ' + tab_file
check_call(cmd, shell=True)
except (IOError, CalledProcessError):
raise
<commit_msg>Use a relative import to get the read module<commit_after>#! /usr/bin/env python
#
# Dakota utility programs for converting output.
#
# Mark Piper (mark.piper@colorado.edu)
import shutil
from subprocess import check_call, CalledProcessError
from .read import get_names
def has_interface_column(tab_file):
'''
Returns True if the tabular output file has the v6.1 'interface' column.
'''
try:
val = get_names(tab_file)[1] == 'interface'
except IOError:
raise
else:
return(val)
def strip_interface_column(tab_file):
'''
Strips the 'interface' column from a Dakota 6.1 tabular output file.
'''
try:
bak_file = tab_file + '.orig'
shutil.copyfile(tab_file, bak_file)
cmd = 'cat ' + bak_file +' | colrm 9 18 > ' + tab_file
check_call(cmd, shell=True)
except (IOError, CalledProcessError):
raise
|
36f7cd5c57de123bbbd88d63fd6f47a8c54a41ec | contactmps/urls.py | contactmps/urls.py | from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
url(r'^$', 'contactmps.views.home', name='home'),
url(r'^embed.html$', 'contactmps.views.embed', name='embed-info'),
url(r'^campaign/noconfidence/$', 'contactmps.views.create_mail', name='noconfidence'),
url(r'^email/$', 'contactmps.views.email', name='email'),
url(r'^email/(?P<uuid>[\a-z0-0-]+)$', 'contactmps.views.email_detail', name='email-detail'),
url(r'^admin/', include(admin.site.urls)),
url(r'^robots.txt$', 'contactmps.views.robots'),
)
| from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
url(r'^$', 'contactmps.views.home', name='home'),
url(r'^embed.html$', 'contactmps.views.embed', name='embed-info'),
url(r'^campaign/noconfidence/$', 'contactmps.views.create_mail', name='noconfidence'),
url(r'^email/$', 'contactmps.views.email', name='email'),
url(r'^email/(?P<uuid>[\a-z0-0-]+)/$', 'contactmps.views.email_detail', name='email-detail'),
url(r'^admin/', include(admin.site.urls)),
url(r'^robots.txt$', 'contactmps.views.robots'),
)
| Add slash after email detail url for ADD_SLASHES https fail | Add slash after email detail url for ADD_SLASHES https fail
| Python | mit | OpenUpSA/contact-mps,OpenUpSA/contact-mps,OpenUpSA/contact-mps,OpenUpSA/contact-mps | from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
url(r'^$', 'contactmps.views.home', name='home'),
url(r'^embed.html$', 'contactmps.views.embed', name='embed-info'),
url(r'^campaign/noconfidence/$', 'contactmps.views.create_mail', name='noconfidence'),
url(r'^email/$', 'contactmps.views.email', name='email'),
url(r'^email/(?P<uuid>[\a-z0-0-]+)$', 'contactmps.views.email_detail', name='email-detail'),
url(r'^admin/', include(admin.site.urls)),
url(r'^robots.txt$', 'contactmps.views.robots'),
)
Add slash after email detail url for ADD_SLASHES https fail | from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
url(r'^$', 'contactmps.views.home', name='home'),
url(r'^embed.html$', 'contactmps.views.embed', name='embed-info'),
url(r'^campaign/noconfidence/$', 'contactmps.views.create_mail', name='noconfidence'),
url(r'^email/$', 'contactmps.views.email', name='email'),
url(r'^email/(?P<uuid>[\a-z0-0-]+)/$', 'contactmps.views.email_detail', name='email-detail'),
url(r'^admin/', include(admin.site.urls)),
url(r'^robots.txt$', 'contactmps.views.robots'),
)
| <commit_before>from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
url(r'^$', 'contactmps.views.home', name='home'),
url(r'^embed.html$', 'contactmps.views.embed', name='embed-info'),
url(r'^campaign/noconfidence/$', 'contactmps.views.create_mail', name='noconfidence'),
url(r'^email/$', 'contactmps.views.email', name='email'),
url(r'^email/(?P<uuid>[\a-z0-0-]+)$', 'contactmps.views.email_detail', name='email-detail'),
url(r'^admin/', include(admin.site.urls)),
url(r'^robots.txt$', 'contactmps.views.robots'),
)
<commit_msg>Add slash after email detail url for ADD_SLASHES https fail<commit_after> | from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
url(r'^$', 'contactmps.views.home', name='home'),
url(r'^embed.html$', 'contactmps.views.embed', name='embed-info'),
url(r'^campaign/noconfidence/$', 'contactmps.views.create_mail', name='noconfidence'),
url(r'^email/$', 'contactmps.views.email', name='email'),
url(r'^email/(?P<uuid>[\a-z0-0-]+)/$', 'contactmps.views.email_detail', name='email-detail'),
url(r'^admin/', include(admin.site.urls)),
url(r'^robots.txt$', 'contactmps.views.robots'),
)
| from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
url(r'^$', 'contactmps.views.home', name='home'),
url(r'^embed.html$', 'contactmps.views.embed', name='embed-info'),
url(r'^campaign/noconfidence/$', 'contactmps.views.create_mail', name='noconfidence'),
url(r'^email/$', 'contactmps.views.email', name='email'),
url(r'^email/(?P<uuid>[\a-z0-0-]+)$', 'contactmps.views.email_detail', name='email-detail'),
url(r'^admin/', include(admin.site.urls)),
url(r'^robots.txt$', 'contactmps.views.robots'),
)
Add slash after email detail url for ADD_SLASHES https failfrom django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
url(r'^$', 'contactmps.views.home', name='home'),
url(r'^embed.html$', 'contactmps.views.embed', name='embed-info'),
url(r'^campaign/noconfidence/$', 'contactmps.views.create_mail', name='noconfidence'),
url(r'^email/$', 'contactmps.views.email', name='email'),
url(r'^email/(?P<uuid>[\a-z0-0-]+)/$', 'contactmps.views.email_detail', name='email-detail'),
url(r'^admin/', include(admin.site.urls)),
url(r'^robots.txt$', 'contactmps.views.robots'),
)
| <commit_before>from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
url(r'^$', 'contactmps.views.home', name='home'),
url(r'^embed.html$', 'contactmps.views.embed', name='embed-info'),
url(r'^campaign/noconfidence/$', 'contactmps.views.create_mail', name='noconfidence'),
url(r'^email/$', 'contactmps.views.email', name='email'),
url(r'^email/(?P<uuid>[\a-z0-0-]+)$', 'contactmps.views.email_detail', name='email-detail'),
url(r'^admin/', include(admin.site.urls)),
url(r'^robots.txt$', 'contactmps.views.robots'),
)
<commit_msg>Add slash after email detail url for ADD_SLASHES https fail<commit_after>from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
url(r'^$', 'contactmps.views.home', name='home'),
url(r'^embed.html$', 'contactmps.views.embed', name='embed-info'),
url(r'^campaign/noconfidence/$', 'contactmps.views.create_mail', name='noconfidence'),
url(r'^email/$', 'contactmps.views.email', name='email'),
url(r'^email/(?P<uuid>[\a-z0-0-]+)/$', 'contactmps.views.email_detail', name='email-detail'),
url(r'^admin/', include(admin.site.urls)),
url(r'^robots.txt$', 'contactmps.views.robots'),
)
|
2a763b32b4794e97d1ea7bf22ec39c1eeb559804 | pycroft/model/alembic/versions/fb8d553a7268_add_account_pattern.py | pycroft/model/alembic/versions/fb8d553a7268_add_account_pattern.py | """add account_pattern
Revision ID: fb8d553a7268
Revises: 28e56bf6f62c
Create Date: 2021-04-26 22:16:41.772282
"""
from alembic import op
import sqlalchemy as sa
import pycroft
# revision identifiers, used by Alembic.
revision = 'fb8d553a7268'
down_revision = '28e56bf6f62c'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('account_pattern',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('pattern', sa.String(), nullable=False),
sa.Column('account_id', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['account_id'], ['account.id'], ondelete='CASCADE'),
sa.PrimaryKeyConstraint('id')
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('account_pattern')
# ### end Alembic commands ###
| """add account_pattern
Revision ID: fb8d553a7268
Revises: 28e56bf6f62c
Create Date: 2021-04-26 22:16:41.772282
"""
from alembic import op
import sqlalchemy as sa
import pycroft
# revision identifiers, used by Alembic.
revision = 'fb8d553a7268'
down_revision = '0b69e80a9388'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('account_pattern',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('pattern', sa.String(), nullable=False),
sa.Column('account_id', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['account_id'], ['account.id'], ondelete='CASCADE'),
sa.PrimaryKeyConstraint('id')
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('account_pattern')
# ### end Alembic commands ###
| Rebase most recent alembic change onto HEAD | Rebase most recent alembic change onto HEAD
| Python | apache-2.0 | agdsn/pycroft,agdsn/pycroft,agdsn/pycroft,agdsn/pycroft,agdsn/pycroft | """add account_pattern
Revision ID: fb8d553a7268
Revises: 28e56bf6f62c
Create Date: 2021-04-26 22:16:41.772282
"""
from alembic import op
import sqlalchemy as sa
import pycroft
# revision identifiers, used by Alembic.
revision = 'fb8d553a7268'
down_revision = '28e56bf6f62c'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('account_pattern',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('pattern', sa.String(), nullable=False),
sa.Column('account_id', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['account_id'], ['account.id'], ondelete='CASCADE'),
sa.PrimaryKeyConstraint('id')
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('account_pattern')
# ### end Alembic commands ###
Rebase most recent alembic change onto HEAD | """add account_pattern
Revision ID: fb8d553a7268
Revises: 28e56bf6f62c
Create Date: 2021-04-26 22:16:41.772282
"""
from alembic import op
import sqlalchemy as sa
import pycroft
# revision identifiers, used by Alembic.
revision = 'fb8d553a7268'
down_revision = '0b69e80a9388'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('account_pattern',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('pattern', sa.String(), nullable=False),
sa.Column('account_id', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['account_id'], ['account.id'], ondelete='CASCADE'),
sa.PrimaryKeyConstraint('id')
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('account_pattern')
# ### end Alembic commands ###
| <commit_before>"""add account_pattern
Revision ID: fb8d553a7268
Revises: 28e56bf6f62c
Create Date: 2021-04-26 22:16:41.772282
"""
from alembic import op
import sqlalchemy as sa
import pycroft
# revision identifiers, used by Alembic.
revision = 'fb8d553a7268'
down_revision = '28e56bf6f62c'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('account_pattern',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('pattern', sa.String(), nullable=False),
sa.Column('account_id', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['account_id'], ['account.id'], ondelete='CASCADE'),
sa.PrimaryKeyConstraint('id')
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('account_pattern')
# ### end Alembic commands ###
<commit_msg>Rebase most recent alembic change onto HEAD<commit_after> | """add account_pattern
Revision ID: fb8d553a7268
Revises: 28e56bf6f62c
Create Date: 2021-04-26 22:16:41.772282
"""
from alembic import op
import sqlalchemy as sa
import pycroft
# revision identifiers, used by Alembic.
revision = 'fb8d553a7268'
down_revision = '0b69e80a9388'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('account_pattern',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('pattern', sa.String(), nullable=False),
sa.Column('account_id', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['account_id'], ['account.id'], ondelete='CASCADE'),
sa.PrimaryKeyConstraint('id')
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('account_pattern')
# ### end Alembic commands ###
| """add account_pattern
Revision ID: fb8d553a7268
Revises: 28e56bf6f62c
Create Date: 2021-04-26 22:16:41.772282
"""
from alembic import op
import sqlalchemy as sa
import pycroft
# revision identifiers, used by Alembic.
revision = 'fb8d553a7268'
down_revision = '28e56bf6f62c'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('account_pattern',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('pattern', sa.String(), nullable=False),
sa.Column('account_id', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['account_id'], ['account.id'], ondelete='CASCADE'),
sa.PrimaryKeyConstraint('id')
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('account_pattern')
# ### end Alembic commands ###
Rebase most recent alembic change onto HEAD"""add account_pattern
Revision ID: fb8d553a7268
Revises: 28e56bf6f62c
Create Date: 2021-04-26 22:16:41.772282
"""
from alembic import op
import sqlalchemy as sa
import pycroft
# revision identifiers, used by Alembic.
revision = 'fb8d553a7268'
down_revision = '0b69e80a9388'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('account_pattern',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('pattern', sa.String(), nullable=False),
sa.Column('account_id', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['account_id'], ['account.id'], ondelete='CASCADE'),
sa.PrimaryKeyConstraint('id')
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('account_pattern')
# ### end Alembic commands ###
| <commit_before>"""add account_pattern
Revision ID: fb8d553a7268
Revises: 28e56bf6f62c
Create Date: 2021-04-26 22:16:41.772282
"""
from alembic import op
import sqlalchemy as sa
import pycroft
# revision identifiers, used by Alembic.
revision = 'fb8d553a7268'
down_revision = '28e56bf6f62c'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('account_pattern',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('pattern', sa.String(), nullable=False),
sa.Column('account_id', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['account_id'], ['account.id'], ondelete='CASCADE'),
sa.PrimaryKeyConstraint('id')
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('account_pattern')
# ### end Alembic commands ###
<commit_msg>Rebase most recent alembic change onto HEAD<commit_after>"""add account_pattern
Revision ID: fb8d553a7268
Revises: 28e56bf6f62c
Create Date: 2021-04-26 22:16:41.772282
"""
from alembic import op
import sqlalchemy as sa
import pycroft
# revision identifiers, used by Alembic.
revision = 'fb8d553a7268'
down_revision = '0b69e80a9388'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('account_pattern',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('pattern', sa.String(), nullable=False),
sa.Column('account_id', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['account_id'], ['account.id'], ondelete='CASCADE'),
sa.PrimaryKeyConstraint('id')
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('account_pattern')
# ### end Alembic commands ###
|
dbb9792871d9b1d8f1678dbafeed760098547a28 | pdf_parser/pdf_types/compound_types.py | pdf_parser/pdf_types/compound_types.py | from .common import PdfType
class PdfArray(PdfType, list):
def __init__(self, *args, **kwargs):
PdfType.__init__(self)
list.__init__(self, *args, **kwargs)
class PdfDict(PdfType, dict):
def __init__(self, *args, **kwargs):
PdfType.__init__(self)
dict.__init__(self, *args, **kwargs) | from .common import PdfType
class PdfArray(PdfType, list):
def __init__(self, *args, **kwargs):
PdfType.__init__(self)
list.__init__(self, *args, **kwargs)
class PdfDict(PdfType, dict):
def __init__(self, *args, **kwargs):
PdfType.__init__(self)
dict.__init__(self, *args, **kwargs)
def __getattribute__(self, name):
try:
return self[name].parsed_object
except AttributeError:
return self[name]
except KeyError:
raise AttributeError('Object has no attribute "%s"'%name) | Add read-only attribute style access to PdfDict elements with object parsing. | Add read-only attribute style access to PdfDict elements with object parsing.
| Python | mit | ajmarks/gymnast,ajmarks/gymnast | from .common import PdfType
class PdfArray(PdfType, list):
def __init__(self, *args, **kwargs):
PdfType.__init__(self)
list.__init__(self, *args, **kwargs)
class PdfDict(PdfType, dict):
def __init__(self, *args, **kwargs):
PdfType.__init__(self)
dict.__init__(self, *args, **kwargs)Add read-only attribute style access to PdfDict elements with object parsing. | from .common import PdfType
class PdfArray(PdfType, list):
def __init__(self, *args, **kwargs):
PdfType.__init__(self)
list.__init__(self, *args, **kwargs)
class PdfDict(PdfType, dict):
def __init__(self, *args, **kwargs):
PdfType.__init__(self)
dict.__init__(self, *args, **kwargs)
def __getattribute__(self, name):
try:
return self[name].parsed_object
except AttributeError:
return self[name]
except KeyError:
raise AttributeError('Object has no attribute "%s"'%name) | <commit_before>from .common import PdfType
class PdfArray(PdfType, list):
def __init__(self, *args, **kwargs):
PdfType.__init__(self)
list.__init__(self, *args, **kwargs)
class PdfDict(PdfType, dict):
def __init__(self, *args, **kwargs):
PdfType.__init__(self)
dict.__init__(self, *args, **kwargs)<commit_msg>Add read-only attribute style access to PdfDict elements with object parsing.<commit_after> | from .common import PdfType
class PdfArray(PdfType, list):
def __init__(self, *args, **kwargs):
PdfType.__init__(self)
list.__init__(self, *args, **kwargs)
class PdfDict(PdfType, dict):
def __init__(self, *args, **kwargs):
PdfType.__init__(self)
dict.__init__(self, *args, **kwargs)
def __getattribute__(self, name):
try:
return self[name].parsed_object
except AttributeError:
return self[name]
except KeyError:
raise AttributeError('Object has no attribute "%s"'%name) | from .common import PdfType
class PdfArray(PdfType, list):
def __init__(self, *args, **kwargs):
PdfType.__init__(self)
list.__init__(self, *args, **kwargs)
class PdfDict(PdfType, dict):
def __init__(self, *args, **kwargs):
PdfType.__init__(self)
dict.__init__(self, *args, **kwargs)Add read-only attribute style access to PdfDict elements with object parsing.from .common import PdfType
class PdfArray(PdfType, list):
def __init__(self, *args, **kwargs):
PdfType.__init__(self)
list.__init__(self, *args, **kwargs)
class PdfDict(PdfType, dict):
def __init__(self, *args, **kwargs):
PdfType.__init__(self)
dict.__init__(self, *args, **kwargs)
def __getattribute__(self, name):
try:
return self[name].parsed_object
except AttributeError:
return self[name]
except KeyError:
raise AttributeError('Object has no attribute "%s"'%name) | <commit_before>from .common import PdfType
class PdfArray(PdfType, list):
def __init__(self, *args, **kwargs):
PdfType.__init__(self)
list.__init__(self, *args, **kwargs)
class PdfDict(PdfType, dict):
def __init__(self, *args, **kwargs):
PdfType.__init__(self)
dict.__init__(self, *args, **kwargs)<commit_msg>Add read-only attribute style access to PdfDict elements with object parsing.<commit_after>from .common import PdfType
class PdfArray(PdfType, list):
def __init__(self, *args, **kwargs):
PdfType.__init__(self)
list.__init__(self, *args, **kwargs)
class PdfDict(PdfType, dict):
def __init__(self, *args, **kwargs):
PdfType.__init__(self)
dict.__init__(self, *args, **kwargs)
def __getattribute__(self, name):
try:
return self[name].parsed_object
except AttributeError:
return self[name]
except KeyError:
raise AttributeError('Object has no attribute "%s"'%name) |
8de9c51eedaadc68cc64ca7f5763b48a6448dca3 | main.py | main.py | from dogbot.bot import bot
from dogbot.web import app
from mongoengine import connect
from config import config
import getopt
import sys
import threading
from importlib import reload
reload(threading)
def bot_main():
print("QQBot is running...")
try:
bot.start()
except KeyboardInterrupt:
pass
finally:
print('Bye')
def web_main():
app.run(threaded=True)
if __name__ == '__main__':
connect(config.get('db'))
try:
opts, args = getopt.gnu_getopt(sys.argv[1:], 'bw')
except getopt.GetoptError as err:
print(err)
sys.exit(2)
for o, a in opts:
if o == '-b':
bot_main()
elif o in '-w':
reload(threading)
web_main()
else:
assert False, "unhandled option"
| from dogbot.bot import bot
from dogbot.web import app
from mongoengine import connect
from config import config
import getopt
import sys
import threading
from importlib import reload
reload(threading)
def bot_main():
print("QQBot is running...")
try:
bot.start()
except KeyboardInterrupt:
pass
finally:
print('Bye')
def web_main():
app.run(host='0.0.0.0', threaded=True)
if __name__ == '__main__':
connect(config.get('db'))
try:
opts, args = getopt.gnu_getopt(sys.argv[1:], 'bw')
except getopt.GetoptError as err:
print(err)
sys.exit(2)
for o, a in opts:
if o == '-b':
bot_main()
elif o in '-w':
reload(threading)
web_main()
else:
assert False, "unhandled option"
| Edit host from 127.0.0.1 -> 0.0.0.0 | Edit host from 127.0.0.1 -> 0.0.0.0
| Python | apache-2.0 | moondropx/dogbot,moondropx/dogbot | from dogbot.bot import bot
from dogbot.web import app
from mongoengine import connect
from config import config
import getopt
import sys
import threading
from importlib import reload
reload(threading)
def bot_main():
print("QQBot is running...")
try:
bot.start()
except KeyboardInterrupt:
pass
finally:
print('Bye')
def web_main():
app.run(threaded=True)
if __name__ == '__main__':
connect(config.get('db'))
try:
opts, args = getopt.gnu_getopt(sys.argv[1:], 'bw')
except getopt.GetoptError as err:
print(err)
sys.exit(2)
for o, a in opts:
if o == '-b':
bot_main()
elif o in '-w':
reload(threading)
web_main()
else:
assert False, "unhandled option"
Edit host from 127.0.0.1 -> 0.0.0.0 | from dogbot.bot import bot
from dogbot.web import app
from mongoengine import connect
from config import config
import getopt
import sys
import threading
from importlib import reload
reload(threading)
def bot_main():
print("QQBot is running...")
try:
bot.start()
except KeyboardInterrupt:
pass
finally:
print('Bye')
def web_main():
app.run(host='0.0.0.0', threaded=True)
if __name__ == '__main__':
connect(config.get('db'))
try:
opts, args = getopt.gnu_getopt(sys.argv[1:], 'bw')
except getopt.GetoptError as err:
print(err)
sys.exit(2)
for o, a in opts:
if o == '-b':
bot_main()
elif o in '-w':
reload(threading)
web_main()
else:
assert False, "unhandled option"
| <commit_before>from dogbot.bot import bot
from dogbot.web import app
from mongoengine import connect
from config import config
import getopt
import sys
import threading
from importlib import reload
reload(threading)
def bot_main():
print("QQBot is running...")
try:
bot.start()
except KeyboardInterrupt:
pass
finally:
print('Bye')
def web_main():
app.run(threaded=True)
if __name__ == '__main__':
connect(config.get('db'))
try:
opts, args = getopt.gnu_getopt(sys.argv[1:], 'bw')
except getopt.GetoptError as err:
print(err)
sys.exit(2)
for o, a in opts:
if o == '-b':
bot_main()
elif o in '-w':
reload(threading)
web_main()
else:
assert False, "unhandled option"
<commit_msg>Edit host from 127.0.0.1 -> 0.0.0.0<commit_after> | from dogbot.bot import bot
from dogbot.web import app
from mongoengine import connect
from config import config
import getopt
import sys
import threading
from importlib import reload
reload(threading)
def bot_main():
print("QQBot is running...")
try:
bot.start()
except KeyboardInterrupt:
pass
finally:
print('Bye')
def web_main():
app.run(host='0.0.0.0', threaded=True)
if __name__ == '__main__':
connect(config.get('db'))
try:
opts, args = getopt.gnu_getopt(sys.argv[1:], 'bw')
except getopt.GetoptError as err:
print(err)
sys.exit(2)
for o, a in opts:
if o == '-b':
bot_main()
elif o in '-w':
reload(threading)
web_main()
else:
assert False, "unhandled option"
| from dogbot.bot import bot
from dogbot.web import app
from mongoengine import connect
from config import config
import getopt
import sys
import threading
from importlib import reload
reload(threading)
def bot_main():
print("QQBot is running...")
try:
bot.start()
except KeyboardInterrupt:
pass
finally:
print('Bye')
def web_main():
app.run(threaded=True)
if __name__ == '__main__':
connect(config.get('db'))
try:
opts, args = getopt.gnu_getopt(sys.argv[1:], 'bw')
except getopt.GetoptError as err:
print(err)
sys.exit(2)
for o, a in opts:
if o == '-b':
bot_main()
elif o in '-w':
reload(threading)
web_main()
else:
assert False, "unhandled option"
Edit host from 127.0.0.1 -> 0.0.0.0from dogbot.bot import bot
from dogbot.web import app
from mongoengine import connect
from config import config
import getopt
import sys
import threading
from importlib import reload
reload(threading)
def bot_main():
print("QQBot is running...")
try:
bot.start()
except KeyboardInterrupt:
pass
finally:
print('Bye')
def web_main():
app.run(host='0.0.0.0', threaded=True)
if __name__ == '__main__':
connect(config.get('db'))
try:
opts, args = getopt.gnu_getopt(sys.argv[1:], 'bw')
except getopt.GetoptError as err:
print(err)
sys.exit(2)
for o, a in opts:
if o == '-b':
bot_main()
elif o in '-w':
reload(threading)
web_main()
else:
assert False, "unhandled option"
| <commit_before>from dogbot.bot import bot
from dogbot.web import app
from mongoengine import connect
from config import config
import getopt
import sys
import threading
from importlib import reload
reload(threading)
def bot_main():
print("QQBot is running...")
try:
bot.start()
except KeyboardInterrupt:
pass
finally:
print('Bye')
def web_main():
app.run(threaded=True)
if __name__ == '__main__':
connect(config.get('db'))
try:
opts, args = getopt.gnu_getopt(sys.argv[1:], 'bw')
except getopt.GetoptError as err:
print(err)
sys.exit(2)
for o, a in opts:
if o == '-b':
bot_main()
elif o in '-w':
reload(threading)
web_main()
else:
assert False, "unhandled option"
<commit_msg>Edit host from 127.0.0.1 -> 0.0.0.0<commit_after>from dogbot.bot import bot
from dogbot.web import app
from mongoengine import connect
from config import config
import getopt
import sys
import threading
from importlib import reload
reload(threading)
def bot_main():
print("QQBot is running...")
try:
bot.start()
except KeyboardInterrupt:
pass
finally:
print('Bye')
def web_main():
app.run(host='0.0.0.0', threaded=True)
if __name__ == '__main__':
connect(config.get('db'))
try:
opts, args = getopt.gnu_getopt(sys.argv[1:], 'bw')
except getopt.GetoptError as err:
print(err)
sys.exit(2)
for o, a in opts:
if o == '-b':
bot_main()
elif o in '-w':
reload(threading)
web_main()
else:
assert False, "unhandled option"
|
d8502569f0e4c562294415242f096eefdf361ca0 | pyonep/__init__.py | pyonep/__init__.py | __version__ = '0.12.4'
| """An API library with Python bindings for Exosite One Platform APIs."""
__version__ = '0.12.4'
from .onep import OnepV1, DeferredRequests
from .provision import Provision
| Add docstring and imports to package. | Add docstring and imports to package.
| Python | bsd-3-clause | gavinsunde/pyonep,exosite-labs/pyonep,asolz/pyonep,asolz/pyonep,gavinsunde/pyonep,exosite-labs/pyonep | __version__ = '0.12.4'
Add docstring and imports to package. | """An API library with Python bindings for Exosite One Platform APIs."""
__version__ = '0.12.4'
from .onep import OnepV1, DeferredRequests
from .provision import Provision
| <commit_before>__version__ = '0.12.4'
<commit_msg>Add docstring and imports to package.<commit_after> | """An API library with Python bindings for Exosite One Platform APIs."""
__version__ = '0.12.4'
from .onep import OnepV1, DeferredRequests
from .provision import Provision
| __version__ = '0.12.4'
Add docstring and imports to package."""An API library with Python bindings for Exosite One Platform APIs."""
__version__ = '0.12.4'
from .onep import OnepV1, DeferredRequests
from .provision import Provision
| <commit_before>__version__ = '0.12.4'
<commit_msg>Add docstring and imports to package.<commit_after>"""An API library with Python bindings for Exosite One Platform APIs."""
__version__ = '0.12.4'
from .onep import OnepV1, DeferredRequests
from .provision import Provision
|
0be63749c039e16aa1fcc64cfd8227b50829254e | pyvisa/__init__.py | pyvisa/__init__.py | # -*- coding: utf-8 -*-
"""
pyvisa
~~~~~~
Python wrapper of National Instrument (NI) Virtual Instruments Software
Architecture library (VISA).
This file is part of PyVISA.
:copyright: (c) 2014 by the PyVISA authors.
:license: MIT, see COPYING for more details.
"""
from __future__ import division, unicode_literals, print_function, absolute_import
import os
import logging
import subprocess
import pkg_resources
logger = logging.getLogger('pyvisa')
logger.addHandler(logging.NullHandler)
__version__ = "unknown"
try: # try to grab the commit version of our package
__version__ = (subprocess.check_output(["git", "describe"],
stderr=subprocess.STDOUT,
cwd=os.path.dirname(os.path.abspath(__file__)))).strip()
except: # on any error just try to grab the version that is installed on the system
try:
__version__ = pkg_resources.get_distribution('pyvisa').version
except:
pass # we seem to have a local copy without any repository control or installed without setuptools
# so the reported version will be __unknown__
from .visa import instrument, ResourceManager, Instrument, SerialInstrument,
from .errors import *
| # -*- coding: utf-8 -*-
"""
pyvisa
~~~~~~
Python wrapper of National Instrument (NI) Virtual Instruments Software
Architecture library (VISA).
This file is part of PyVISA.
:copyright: (c) 2014 by the PyVISA authors.
:license: MIT, see COPYING for more details.
"""
from __future__ import division, unicode_literals, print_function, absolute_import
import os
import logging
import subprocess
import pkg_resources
logger = logging.getLogger('pyvisa')
logger.addHandler(logging.NullHandler)
__version__ = "unknown"
try: # try to grab the commit version of our package
__version__ = (subprocess.check_output(["git", "describe"],
stderr=subprocess.STDOUT,
cwd=os.path.dirname(os.path.abspath(__file__)))).strip()
except: # on any error just try to grab the version that is installed on the system
try:
__version__ = pkg_resources.get_distribution('pyvisa').version
except:
pass # we seem to have a local copy without any repository control or installed without setuptools
# so the reported version will be __unknown__
import wrapper
from .visa import instrument, ResourceManager, Instrument, SerialInstrument,
from .errors import *
from .library import read_user_settings
_user_lib = read_user_settings()
if _user_lib:
from . import vpp43
vpp43.visa_library.load_library(_user_lib)
| Load legacy visa_library taking user settings into account | Load legacy visa_library taking user settings into account
See #7
| Python | mit | pyvisa/pyvisa,rubund/debian-pyvisa,MatthieuDartiailh/pyvisa,hgrecco/pyvisa | # -*- coding: utf-8 -*-
"""
pyvisa
~~~~~~
Python wrapper of National Instrument (NI) Virtual Instruments Software
Architecture library (VISA).
This file is part of PyVISA.
:copyright: (c) 2014 by the PyVISA authors.
:license: MIT, see COPYING for more details.
"""
from __future__ import division, unicode_literals, print_function, absolute_import
import os
import logging
import subprocess
import pkg_resources
logger = logging.getLogger('pyvisa')
logger.addHandler(logging.NullHandler)
__version__ = "unknown"
try: # try to grab the commit version of our package
__version__ = (subprocess.check_output(["git", "describe"],
stderr=subprocess.STDOUT,
cwd=os.path.dirname(os.path.abspath(__file__)))).strip()
except: # on any error just try to grab the version that is installed on the system
try:
__version__ = pkg_resources.get_distribution('pyvisa').version
except:
pass # we seem to have a local copy without any repository control or installed without setuptools
# so the reported version will be __unknown__
from .visa import instrument, ResourceManager, Instrument, SerialInstrument,
from .errors import *
Load legacy visa_library taking user settings into account
See #7 | # -*- coding: utf-8 -*-
"""
pyvisa
~~~~~~
Python wrapper of National Instrument (NI) Virtual Instruments Software
Architecture library (VISA).
This file is part of PyVISA.
:copyright: (c) 2014 by the PyVISA authors.
:license: MIT, see COPYING for more details.
"""
from __future__ import division, unicode_literals, print_function, absolute_import
import os
import logging
import subprocess
import pkg_resources
logger = logging.getLogger('pyvisa')
logger.addHandler(logging.NullHandler)
__version__ = "unknown"
try: # try to grab the commit version of our package
__version__ = (subprocess.check_output(["git", "describe"],
stderr=subprocess.STDOUT,
cwd=os.path.dirname(os.path.abspath(__file__)))).strip()
except: # on any error just try to grab the version that is installed on the system
try:
__version__ = pkg_resources.get_distribution('pyvisa').version
except:
pass # we seem to have a local copy without any repository control or installed without setuptools
# so the reported version will be __unknown__
import wrapper
from .visa import instrument, ResourceManager, Instrument, SerialInstrument,
from .errors import *
from .library import read_user_settings
_user_lib = read_user_settings()
if _user_lib:
from . import vpp43
vpp43.visa_library.load_library(_user_lib)
| <commit_before># -*- coding: utf-8 -*-
"""
pyvisa
~~~~~~
Python wrapper of National Instrument (NI) Virtual Instruments Software
Architecture library (VISA).
This file is part of PyVISA.
:copyright: (c) 2014 by the PyVISA authors.
:license: MIT, see COPYING for more details.
"""
from __future__ import division, unicode_literals, print_function, absolute_import
import os
import logging
import subprocess
import pkg_resources
logger = logging.getLogger('pyvisa')
logger.addHandler(logging.NullHandler)
__version__ = "unknown"
try: # try to grab the commit version of our package
__version__ = (subprocess.check_output(["git", "describe"],
stderr=subprocess.STDOUT,
cwd=os.path.dirname(os.path.abspath(__file__)))).strip()
except: # on any error just try to grab the version that is installed on the system
try:
__version__ = pkg_resources.get_distribution('pyvisa').version
except:
pass # we seem to have a local copy without any repository control or installed without setuptools
# so the reported version will be __unknown__
from .visa import instrument, ResourceManager, Instrument, SerialInstrument,
from .errors import *
<commit_msg>Load legacy visa_library taking user settings into account
See #7<commit_after> | # -*- coding: utf-8 -*-
"""
pyvisa
~~~~~~
Python wrapper of National Instrument (NI) Virtual Instruments Software
Architecture library (VISA).
This file is part of PyVISA.
:copyright: (c) 2014 by the PyVISA authors.
:license: MIT, see COPYING for more details.
"""
from __future__ import division, unicode_literals, print_function, absolute_import
import os
import logging
import subprocess
import pkg_resources
logger = logging.getLogger('pyvisa')
logger.addHandler(logging.NullHandler)
__version__ = "unknown"
try: # try to grab the commit version of our package
__version__ = (subprocess.check_output(["git", "describe"],
stderr=subprocess.STDOUT,
cwd=os.path.dirname(os.path.abspath(__file__)))).strip()
except: # on any error just try to grab the version that is installed on the system
try:
__version__ = pkg_resources.get_distribution('pyvisa').version
except:
pass # we seem to have a local copy without any repository control or installed without setuptools
# so the reported version will be __unknown__
import wrapper
from .visa import instrument, ResourceManager, Instrument, SerialInstrument,
from .errors import *
from .library import read_user_settings
_user_lib = read_user_settings()
if _user_lib:
from . import vpp43
vpp43.visa_library.load_library(_user_lib)
| # -*- coding: utf-8 -*-
"""
pyvisa
~~~~~~
Python wrapper of National Instrument (NI) Virtual Instruments Software
Architecture library (VISA).
This file is part of PyVISA.
:copyright: (c) 2014 by the PyVISA authors.
:license: MIT, see COPYING for more details.
"""
from __future__ import division, unicode_literals, print_function, absolute_import
import os
import logging
import subprocess
import pkg_resources
logger = logging.getLogger('pyvisa')
logger.addHandler(logging.NullHandler)
__version__ = "unknown"
try: # try to grab the commit version of our package
__version__ = (subprocess.check_output(["git", "describe"],
stderr=subprocess.STDOUT,
cwd=os.path.dirname(os.path.abspath(__file__)))).strip()
except: # on any error just try to grab the version that is installed on the system
try:
__version__ = pkg_resources.get_distribution('pyvisa').version
except:
pass # we seem to have a local copy without any repository control or installed without setuptools
# so the reported version will be __unknown__
from .visa import instrument, ResourceManager, Instrument, SerialInstrument,
from .errors import *
Load legacy visa_library taking user settings into account
See #7# -*- coding: utf-8 -*-
"""
pyvisa
~~~~~~
Python wrapper of National Instrument (NI) Virtual Instruments Software
Architecture library (VISA).
This file is part of PyVISA.
:copyright: (c) 2014 by the PyVISA authors.
:license: MIT, see COPYING for more details.
"""
from __future__ import division, unicode_literals, print_function, absolute_import
import os
import logging
import subprocess
import pkg_resources
logger = logging.getLogger('pyvisa')
logger.addHandler(logging.NullHandler)
__version__ = "unknown"
try: # try to grab the commit version of our package
__version__ = (subprocess.check_output(["git", "describe"],
stderr=subprocess.STDOUT,
cwd=os.path.dirname(os.path.abspath(__file__)))).strip()
except: # on any error just try to grab the version that is installed on the system
try:
__version__ = pkg_resources.get_distribution('pyvisa').version
except:
pass # we seem to have a local copy without any repository control or installed without setuptools
# so the reported version will be __unknown__
import wrapper
from .visa import instrument, ResourceManager, Instrument, SerialInstrument,
from .errors import *
from .library import read_user_settings
_user_lib = read_user_settings()
if _user_lib:
from . import vpp43
vpp43.visa_library.load_library(_user_lib)
| <commit_before># -*- coding: utf-8 -*-
"""
pyvisa
~~~~~~
Python wrapper of National Instrument (NI) Virtual Instruments Software
Architecture library (VISA).
This file is part of PyVISA.
:copyright: (c) 2014 by the PyVISA authors.
:license: MIT, see COPYING for more details.
"""
from __future__ import division, unicode_literals, print_function, absolute_import
import os
import logging
import subprocess
import pkg_resources
logger = logging.getLogger('pyvisa')
logger.addHandler(logging.NullHandler)
__version__ = "unknown"
try: # try to grab the commit version of our package
__version__ = (subprocess.check_output(["git", "describe"],
stderr=subprocess.STDOUT,
cwd=os.path.dirname(os.path.abspath(__file__)))).strip()
except: # on any error just try to grab the version that is installed on the system
try:
__version__ = pkg_resources.get_distribution('pyvisa').version
except:
pass # we seem to have a local copy without any repository control or installed without setuptools
# so the reported version will be __unknown__
from .visa import instrument, ResourceManager, Instrument, SerialInstrument,
from .errors import *
<commit_msg>Load legacy visa_library taking user settings into account
See #7<commit_after># -*- coding: utf-8 -*-
"""
pyvisa
~~~~~~
Python wrapper of National Instrument (NI) Virtual Instruments Software
Architecture library (VISA).
This file is part of PyVISA.
:copyright: (c) 2014 by the PyVISA authors.
:license: MIT, see COPYING for more details.
"""
from __future__ import division, unicode_literals, print_function, absolute_import
import os
import logging
import subprocess
import pkg_resources
logger = logging.getLogger('pyvisa')
logger.addHandler(logging.NullHandler)
__version__ = "unknown"
try: # try to grab the commit version of our package
__version__ = (subprocess.check_output(["git", "describe"],
stderr=subprocess.STDOUT,
cwd=os.path.dirname(os.path.abspath(__file__)))).strip()
except: # on any error just try to grab the version that is installed on the system
try:
__version__ = pkg_resources.get_distribution('pyvisa').version
except:
pass # we seem to have a local copy without any repository control or installed without setuptools
# so the reported version will be __unknown__
import wrapper
from .visa import instrument, ResourceManager, Instrument, SerialInstrument,
from .errors import *
from .library import read_user_settings
_user_lib = read_user_settings()
if _user_lib:
from . import vpp43
vpp43.visa_library.load_library(_user_lib)
|
7b8fe4aa426a8de24b5fc1a496b7b1eba92e7756 | pywind/__init__.py | pywind/__init__.py | """ pywind module.
For more information visit https://github.com/zathras777/pywind
"""
__version__ = '1.0.3'
| """ pywind module.
For more information visit https://github.com/zathras777/pywind
"""
__version__ = '1.0.4'
| Move to next version number. | Move to next version number.
| Python | unlicense | zathras777/pywind,zathras777/pywind | """ pywind module.
For more information visit https://github.com/zathras777/pywind
"""
__version__ = '1.0.3'
Move to next version number. | """ pywind module.
For more information visit https://github.com/zathras777/pywind
"""
__version__ = '1.0.4'
| <commit_before>""" pywind module.
For more information visit https://github.com/zathras777/pywind
"""
__version__ = '1.0.3'
<commit_msg>Move to next version number.<commit_after> | """ pywind module.
For more information visit https://github.com/zathras777/pywind
"""
__version__ = '1.0.4'
| """ pywind module.
For more information visit https://github.com/zathras777/pywind
"""
__version__ = '1.0.3'
Move to next version number.""" pywind module.
For more information visit https://github.com/zathras777/pywind
"""
__version__ = '1.0.4'
| <commit_before>""" pywind module.
For more information visit https://github.com/zathras777/pywind
"""
__version__ = '1.0.3'
<commit_msg>Move to next version number.<commit_after>""" pywind module.
For more information visit https://github.com/zathras777/pywind
"""
__version__ = '1.0.4'
|
fb8cfa8eb7d088ebe11075bff42bea54c97e9c18 | hermes/views.py | hermes/views.py | from django.views.generic import ListView, DetailView
from .models import Post
class PostListView(ListView):
context_object_name = 'posts'
model = Post
template_name = 'hermes/post_list.html'
def get_queryset(self):
return self.model.objects.order_by('created_on')
class CategoryPostListView(PostListView):
def get_queryset(self):
category_slug = self.kwargs.get('slug', '')
return self.model.objects.in_category(category_slug)
class ArchivePostListView(PostListView):
def get_queryset(self):
year = self.kwargs.get('year', None)
month = self.kwargs.get('month', None)
day = self.kwargs.get('day', None)
return self.model.objects.created_on(year=year, month=month, day=day)
class PostDetail(DetailView):
context_object_name = 'post'
model = Post
template_name = "hermes/post_detail.html"
| from django.views.generic import ListView, DetailView
from .models import Post
class PostListView(ListView):
context_object_name = 'posts'
model = Post
template_name = 'hermes/post_list.html'
def get_queryset(self):
return self.model.objects.order_by('created_on')
class CategoryPostListView(PostListView):
slug = None
def get_queryset(self):
category_slug = self.kwargs.get('slug', '')
return self.model.objects.in_category(category_slug)
class ArchivePostListView(PostListView):
def get_queryset(self):
year = self.kwargs.get('year', None)
month = self.kwargs.get('month', None)
day = self.kwargs.get('day', None)
return self.model.objects.created_on(year=year, month=month, day=day)
class PostDetail(DetailView):
context_object_name = 'post'
model = Post
template_name = "hermes/post_detail.html"
| Add slug variable to pass in the URL | Add slug variable to pass in the URL | Python | mit | emilian/django-hermes | from django.views.generic import ListView, DetailView
from .models import Post
class PostListView(ListView):
context_object_name = 'posts'
model = Post
template_name = 'hermes/post_list.html'
def get_queryset(self):
return self.model.objects.order_by('created_on')
class CategoryPostListView(PostListView):
def get_queryset(self):
category_slug = self.kwargs.get('slug', '')
return self.model.objects.in_category(category_slug)
class ArchivePostListView(PostListView):
def get_queryset(self):
year = self.kwargs.get('year', None)
month = self.kwargs.get('month', None)
day = self.kwargs.get('day', None)
return self.model.objects.created_on(year=year, month=month, day=day)
class PostDetail(DetailView):
context_object_name = 'post'
model = Post
template_name = "hermes/post_detail.html"
Add slug variable to pass in the URL | from django.views.generic import ListView, DetailView
from .models import Post
class PostListView(ListView):
context_object_name = 'posts'
model = Post
template_name = 'hermes/post_list.html'
def get_queryset(self):
return self.model.objects.order_by('created_on')
class CategoryPostListView(PostListView):
slug = None
def get_queryset(self):
category_slug = self.kwargs.get('slug', '')
return self.model.objects.in_category(category_slug)
class ArchivePostListView(PostListView):
def get_queryset(self):
year = self.kwargs.get('year', None)
month = self.kwargs.get('month', None)
day = self.kwargs.get('day', None)
return self.model.objects.created_on(year=year, month=month, day=day)
class PostDetail(DetailView):
context_object_name = 'post'
model = Post
template_name = "hermes/post_detail.html"
| <commit_before>from django.views.generic import ListView, DetailView
from .models import Post
class PostListView(ListView):
context_object_name = 'posts'
model = Post
template_name = 'hermes/post_list.html'
def get_queryset(self):
return self.model.objects.order_by('created_on')
class CategoryPostListView(PostListView):
def get_queryset(self):
category_slug = self.kwargs.get('slug', '')
return self.model.objects.in_category(category_slug)
class ArchivePostListView(PostListView):
def get_queryset(self):
year = self.kwargs.get('year', None)
month = self.kwargs.get('month', None)
day = self.kwargs.get('day', None)
return self.model.objects.created_on(year=year, month=month, day=day)
class PostDetail(DetailView):
context_object_name = 'post'
model = Post
template_name = "hermes/post_detail.html"
<commit_msg>Add slug variable to pass in the URL<commit_after> | from django.views.generic import ListView, DetailView
from .models import Post
class PostListView(ListView):
context_object_name = 'posts'
model = Post
template_name = 'hermes/post_list.html'
def get_queryset(self):
return self.model.objects.order_by('created_on')
class CategoryPostListView(PostListView):
slug = None
def get_queryset(self):
category_slug = self.kwargs.get('slug', '')
return self.model.objects.in_category(category_slug)
class ArchivePostListView(PostListView):
def get_queryset(self):
year = self.kwargs.get('year', None)
month = self.kwargs.get('month', None)
day = self.kwargs.get('day', None)
return self.model.objects.created_on(year=year, month=month, day=day)
class PostDetail(DetailView):
context_object_name = 'post'
model = Post
template_name = "hermes/post_detail.html"
| from django.views.generic import ListView, DetailView
from .models import Post
class PostListView(ListView):
context_object_name = 'posts'
model = Post
template_name = 'hermes/post_list.html'
def get_queryset(self):
return self.model.objects.order_by('created_on')
class CategoryPostListView(PostListView):
def get_queryset(self):
category_slug = self.kwargs.get('slug', '')
return self.model.objects.in_category(category_slug)
class ArchivePostListView(PostListView):
def get_queryset(self):
year = self.kwargs.get('year', None)
month = self.kwargs.get('month', None)
day = self.kwargs.get('day', None)
return self.model.objects.created_on(year=year, month=month, day=day)
class PostDetail(DetailView):
context_object_name = 'post'
model = Post
template_name = "hermes/post_detail.html"
Add slug variable to pass in the URLfrom django.views.generic import ListView, DetailView
from .models import Post
class PostListView(ListView):
context_object_name = 'posts'
model = Post
template_name = 'hermes/post_list.html'
def get_queryset(self):
return self.model.objects.order_by('created_on')
class CategoryPostListView(PostListView):
slug = None
def get_queryset(self):
category_slug = self.kwargs.get('slug', '')
return self.model.objects.in_category(category_slug)
class ArchivePostListView(PostListView):
def get_queryset(self):
year = self.kwargs.get('year', None)
month = self.kwargs.get('month', None)
day = self.kwargs.get('day', None)
return self.model.objects.created_on(year=year, month=month, day=day)
class PostDetail(DetailView):
context_object_name = 'post'
model = Post
template_name = "hermes/post_detail.html"
| <commit_before>from django.views.generic import ListView, DetailView
from .models import Post
class PostListView(ListView):
context_object_name = 'posts'
model = Post
template_name = 'hermes/post_list.html'
def get_queryset(self):
return self.model.objects.order_by('created_on')
class CategoryPostListView(PostListView):
def get_queryset(self):
category_slug = self.kwargs.get('slug', '')
return self.model.objects.in_category(category_slug)
class ArchivePostListView(PostListView):
def get_queryset(self):
year = self.kwargs.get('year', None)
month = self.kwargs.get('month', None)
day = self.kwargs.get('day', None)
return self.model.objects.created_on(year=year, month=month, day=day)
class PostDetail(DetailView):
context_object_name = 'post'
model = Post
template_name = "hermes/post_detail.html"
<commit_msg>Add slug variable to pass in the URL<commit_after>from django.views.generic import ListView, DetailView
from .models import Post
class PostListView(ListView):
context_object_name = 'posts'
model = Post
template_name = 'hermes/post_list.html'
def get_queryset(self):
return self.model.objects.order_by('created_on')
class CategoryPostListView(PostListView):
slug = None
def get_queryset(self):
category_slug = self.kwargs.get('slug', '')
return self.model.objects.in_category(category_slug)
class ArchivePostListView(PostListView):
def get_queryset(self):
year = self.kwargs.get('year', None)
month = self.kwargs.get('month', None)
day = self.kwargs.get('day', None)
return self.model.objects.created_on(year=year, month=month, day=day)
class PostDetail(DetailView):
context_object_name = 'post'
model = Post
template_name = "hermes/post_detail.html"
|
51c9413eb1375ff191e03d38933a772923fa55cf | app/__init__.py | app/__init__.py | from flask import Flask
from flask.ext.bootstrap import Bootstrap
from config import config
bootstrap = Bootstrap()
def create_app(config_name):
application = Flask(__name__)
application.config['DEBUG'] = True
application.config.from_object(config[config_name])
config[config_name].init_app(application)
bootstrap.init_app(application)
from .main import main as main_blueprint
application.register_blueprint(main_blueprint)
main_blueprint.config = {
'BASE_TEMPLATE_DATA': application.config['BASE_TEMPLATE_DATA']
}
return application
| from flask import Flask
from flask.ext.bootstrap import Bootstrap
from config import config
from .main import main as main_blueprint
def create_app(config_name):
application = Flask(__name__,
static_folder='static/',
static_url_path=config[config_name].STATIC_URL_PATH)
application.config.from_object(config[config_name])
config[config_name].init_app(application)
bootstrap = Bootstrap()
bootstrap.init_app(application)
application.register_blueprint(main_blueprint,
url_prefix='/supplier')
main_blueprint.config = {
'BASE_TEMPLATE_DATA': application.config['BASE_TEMPLATE_DATA']
}
return application
| Add /supplier prefix to main blueprint and static URLs | Add /supplier prefix to main blueprint and static URLs
| Python | mit | alphagov/digitalmarketplace-supplier-frontend,mtekel/digitalmarketplace-supplier-frontend,mtekel/digitalmarketplace-supplier-frontend,mtekel/digitalmarketplace-supplier-frontend,alphagov/digitalmarketplace-supplier-frontend,alphagov/digitalmarketplace-supplier-frontend,mtekel/digitalmarketplace-supplier-frontend,alphagov/digitalmarketplace-supplier-frontend | from flask import Flask
from flask.ext.bootstrap import Bootstrap
from config import config
bootstrap = Bootstrap()
def create_app(config_name):
application = Flask(__name__)
application.config['DEBUG'] = True
application.config.from_object(config[config_name])
config[config_name].init_app(application)
bootstrap.init_app(application)
from .main import main as main_blueprint
application.register_blueprint(main_blueprint)
main_blueprint.config = {
'BASE_TEMPLATE_DATA': application.config['BASE_TEMPLATE_DATA']
}
return application
Add /supplier prefix to main blueprint and static URLs | from flask import Flask
from flask.ext.bootstrap import Bootstrap
from config import config
from .main import main as main_blueprint
def create_app(config_name):
application = Flask(__name__,
static_folder='static/',
static_url_path=config[config_name].STATIC_URL_PATH)
application.config.from_object(config[config_name])
config[config_name].init_app(application)
bootstrap = Bootstrap()
bootstrap.init_app(application)
application.register_blueprint(main_blueprint,
url_prefix='/supplier')
main_blueprint.config = {
'BASE_TEMPLATE_DATA': application.config['BASE_TEMPLATE_DATA']
}
return application
| <commit_before>from flask import Flask
from flask.ext.bootstrap import Bootstrap
from config import config
bootstrap = Bootstrap()
def create_app(config_name):
application = Flask(__name__)
application.config['DEBUG'] = True
application.config.from_object(config[config_name])
config[config_name].init_app(application)
bootstrap.init_app(application)
from .main import main as main_blueprint
application.register_blueprint(main_blueprint)
main_blueprint.config = {
'BASE_TEMPLATE_DATA': application.config['BASE_TEMPLATE_DATA']
}
return application
<commit_msg>Add /supplier prefix to main blueprint and static URLs<commit_after> | from flask import Flask
from flask.ext.bootstrap import Bootstrap
from config import config
from .main import main as main_blueprint
def create_app(config_name):
application = Flask(__name__,
static_folder='static/',
static_url_path=config[config_name].STATIC_URL_PATH)
application.config.from_object(config[config_name])
config[config_name].init_app(application)
bootstrap = Bootstrap()
bootstrap.init_app(application)
application.register_blueprint(main_blueprint,
url_prefix='/supplier')
main_blueprint.config = {
'BASE_TEMPLATE_DATA': application.config['BASE_TEMPLATE_DATA']
}
return application
| from flask import Flask
from flask.ext.bootstrap import Bootstrap
from config import config
bootstrap = Bootstrap()
def create_app(config_name):
application = Flask(__name__)
application.config['DEBUG'] = True
application.config.from_object(config[config_name])
config[config_name].init_app(application)
bootstrap.init_app(application)
from .main import main as main_blueprint
application.register_blueprint(main_blueprint)
main_blueprint.config = {
'BASE_TEMPLATE_DATA': application.config['BASE_TEMPLATE_DATA']
}
return application
Add /supplier prefix to main blueprint and static URLsfrom flask import Flask
from flask.ext.bootstrap import Bootstrap
from config import config
from .main import main as main_blueprint
def create_app(config_name):
application = Flask(__name__,
static_folder='static/',
static_url_path=config[config_name].STATIC_URL_PATH)
application.config.from_object(config[config_name])
config[config_name].init_app(application)
bootstrap = Bootstrap()
bootstrap.init_app(application)
application.register_blueprint(main_blueprint,
url_prefix='/supplier')
main_blueprint.config = {
'BASE_TEMPLATE_DATA': application.config['BASE_TEMPLATE_DATA']
}
return application
| <commit_before>from flask import Flask
from flask.ext.bootstrap import Bootstrap
from config import config
bootstrap = Bootstrap()
def create_app(config_name):
application = Flask(__name__)
application.config['DEBUG'] = True
application.config.from_object(config[config_name])
config[config_name].init_app(application)
bootstrap.init_app(application)
from .main import main as main_blueprint
application.register_blueprint(main_blueprint)
main_blueprint.config = {
'BASE_TEMPLATE_DATA': application.config['BASE_TEMPLATE_DATA']
}
return application
<commit_msg>Add /supplier prefix to main blueprint and static URLs<commit_after>from flask import Flask
from flask.ext.bootstrap import Bootstrap
from config import config
from .main import main as main_blueprint
def create_app(config_name):
application = Flask(__name__,
static_folder='static/',
static_url_path=config[config_name].STATIC_URL_PATH)
application.config.from_object(config[config_name])
config[config_name].init_app(application)
bootstrap = Bootstrap()
bootstrap.init_app(application)
application.register_blueprint(main_blueprint,
url_prefix='/supplier')
main_blueprint.config = {
'BASE_TEMPLATE_DATA': application.config['BASE_TEMPLATE_DATA']
}
return application
|
6e9159b66cd791561a24bd935aaaab2a4ea6a6af | sgapi/__init__.py | sgapi/__init__.py | from .core import Shotgun, ShotgunError
# For API compatibility
Fault = ShotgunError
| from .core import Shotgun, ShotgunError, TransportError
# For API compatibility
Fault = ShotgunError
| Add TransportError to top-level package | Add TransportError to top-level package
| Python | bsd-3-clause | westernx/sgapi | from .core import Shotgun, ShotgunError
# For API compatibility
Fault = ShotgunError
Add TransportError to top-level package | from .core import Shotgun, ShotgunError, TransportError
# For API compatibility
Fault = ShotgunError
| <commit_before>from .core import Shotgun, ShotgunError
# For API compatibility
Fault = ShotgunError
<commit_msg>Add TransportError to top-level package<commit_after> | from .core import Shotgun, ShotgunError, TransportError
# For API compatibility
Fault = ShotgunError
| from .core import Shotgun, ShotgunError
# For API compatibility
Fault = ShotgunError
Add TransportError to top-level packagefrom .core import Shotgun, ShotgunError, TransportError
# For API compatibility
Fault = ShotgunError
| <commit_before>from .core import Shotgun, ShotgunError
# For API compatibility
Fault = ShotgunError
<commit_msg>Add TransportError to top-level package<commit_after>from .core import Shotgun, ShotgunError, TransportError
# For API compatibility
Fault = ShotgunError
|
a90411116617096c73ba6d188322613a1b529a62 | books/CrackingCodesWithPython/Chapter20/vigenereDictionaryHacker.py | books/CrackingCodesWithPython/Chapter20/vigenereDictionaryHacker.py | # Vigenère Cipher Dictionary Hacker
# https://www.nostarch.com/crackingcodes/ (BSD Licensed)
import detectEnglish, vigenereCipher, pyperclip
def main():
ciphertext = """Tzx isnz eccjxkg nfq lol mys bbqq I lxcz."""
hackedMessage = hackVigenereDictionary(ciphertext)
if hackedMessage != None:
print('Copying hacked message to clipboard:')
print(hackedMessage)
pyperclip.copy(hackedMessage)
else:
print('Failed to hack encryption.')
def hackVigenereDictionary(ciphertext):
fo = open('dictionary.txt')
words = fo.readlines()
fo.close()
for word in words:
word = word.strip() # Remove the newline at the end.
decryptedText = vigenereCipher.decryptMessage(word, ciphertext)
if detectEnglish.isEnglish(decryptedText, wordPercentage=40):
# Check with user to see if the decrypted key has been found:
print()
print('Possible encryption break:')
print('Key ' + str(word) + ': ' + decryptedText[:100])
print()
print('Enter D for done, or just press Enter to continue breaking:')
response = input('> ')
if response.upper().startswith('D'):
return decryptedText
if __name__ == '__main__':
main()
| # Vigenère Cipher Dictionary Hacker
# https://www.nostarch.com/crackingcodes/ (BSD Licensed)
import detectEnglish, vigenereCipher, pyperclip
def main():
ciphertext = """Tzx isnz eccjxkg nfq lol mys bbqq I lxcz."""
hackedMessage = hackVigenereDictionary(ciphertext)
if not hackedMessage:
print('Copying hacked message to clipboard:')
print(hackedMessage)
pyperclip.copy(hackedMessage)
else:
print('Failed to hack encryption.')
def hackVigenereDictionary(ciphertext):
fo = open('dictionary.txt')
words = fo.readlines()
fo.close()
for word in words:
word = word.strip() # Remove the newline at the end.
decryptedText = vigenereCipher.decryptMessage(word, ciphertext)
if detectEnglish.isEnglish(decryptedText, wordPercentage=40):
# Check with user to see if the decrypted key has been found:
print()
print('Possible encryption break:')
print('Key ' + str(word) + ': ' + decryptedText[:100])
print()
print('Enter D for done, or just press Enter to continue breaking:')
response = input('> ')
if response.upper().startswith('D'):
return decryptedText
if __name__ == '__main__':
main()
| Update vigenereDicitonaryHacker: simplified comparison with None | Update vigenereDicitonaryHacker: simplified comparison with None
| Python | mit | JoseALermaIII/python-tutorials,JoseALermaIII/python-tutorials | # Vigenère Cipher Dictionary Hacker
# https://www.nostarch.com/crackingcodes/ (BSD Licensed)
import detectEnglish, vigenereCipher, pyperclip
def main():
ciphertext = """Tzx isnz eccjxkg nfq lol mys bbqq I lxcz."""
hackedMessage = hackVigenereDictionary(ciphertext)
if hackedMessage != None:
print('Copying hacked message to clipboard:')
print(hackedMessage)
pyperclip.copy(hackedMessage)
else:
print('Failed to hack encryption.')
def hackVigenereDictionary(ciphertext):
fo = open('dictionary.txt')
words = fo.readlines()
fo.close()
for word in words:
word = word.strip() # Remove the newline at the end.
decryptedText = vigenereCipher.decryptMessage(word, ciphertext)
if detectEnglish.isEnglish(decryptedText, wordPercentage=40):
# Check with user to see if the decrypted key has been found:
print()
print('Possible encryption break:')
print('Key ' + str(word) + ': ' + decryptedText[:100])
print()
print('Enter D for done, or just press Enter to continue breaking:')
response = input('> ')
if response.upper().startswith('D'):
return decryptedText
if __name__ == '__main__':
main()
Update vigenereDicitonaryHacker: simplified comparison with None | # Vigenère Cipher Dictionary Hacker
# https://www.nostarch.com/crackingcodes/ (BSD Licensed)
import detectEnglish, vigenereCipher, pyperclip
def main():
ciphertext = """Tzx isnz eccjxkg nfq lol mys bbqq I lxcz."""
hackedMessage = hackVigenereDictionary(ciphertext)
if not hackedMessage:
print('Copying hacked message to clipboard:')
print(hackedMessage)
pyperclip.copy(hackedMessage)
else:
print('Failed to hack encryption.')
def hackVigenereDictionary(ciphertext):
fo = open('dictionary.txt')
words = fo.readlines()
fo.close()
for word in words:
word = word.strip() # Remove the newline at the end.
decryptedText = vigenereCipher.decryptMessage(word, ciphertext)
if detectEnglish.isEnglish(decryptedText, wordPercentage=40):
# Check with user to see if the decrypted key has been found:
print()
print('Possible encryption break:')
print('Key ' + str(word) + ': ' + decryptedText[:100])
print()
print('Enter D for done, or just press Enter to continue breaking:')
response = input('> ')
if response.upper().startswith('D'):
return decryptedText
if __name__ == '__main__':
main()
| <commit_before># Vigenère Cipher Dictionary Hacker
# https://www.nostarch.com/crackingcodes/ (BSD Licensed)
import detectEnglish, vigenereCipher, pyperclip
def main():
ciphertext = """Tzx isnz eccjxkg nfq lol mys bbqq I lxcz."""
hackedMessage = hackVigenereDictionary(ciphertext)
if hackedMessage != None:
print('Copying hacked message to clipboard:')
print(hackedMessage)
pyperclip.copy(hackedMessage)
else:
print('Failed to hack encryption.')
def hackVigenereDictionary(ciphertext):
fo = open('dictionary.txt')
words = fo.readlines()
fo.close()
for word in words:
word = word.strip() # Remove the newline at the end.
decryptedText = vigenereCipher.decryptMessage(word, ciphertext)
if detectEnglish.isEnglish(decryptedText, wordPercentage=40):
# Check with user to see if the decrypted key has been found:
print()
print('Possible encryption break:')
print('Key ' + str(word) + ': ' + decryptedText[:100])
print()
print('Enter D for done, or just press Enter to continue breaking:')
response = input('> ')
if response.upper().startswith('D'):
return decryptedText
if __name__ == '__main__':
main()
<commit_msg>Update vigenereDicitonaryHacker: simplified comparison with None<commit_after> | # Vigenère Cipher Dictionary Hacker
# https://www.nostarch.com/crackingcodes/ (BSD Licensed)
import detectEnglish, vigenereCipher, pyperclip
def main():
ciphertext = """Tzx isnz eccjxkg nfq lol mys bbqq I lxcz."""
hackedMessage = hackVigenereDictionary(ciphertext)
if not hackedMessage:
print('Copying hacked message to clipboard:')
print(hackedMessage)
pyperclip.copy(hackedMessage)
else:
print('Failed to hack encryption.')
def hackVigenereDictionary(ciphertext):
fo = open('dictionary.txt')
words = fo.readlines()
fo.close()
for word in words:
word = word.strip() # Remove the newline at the end.
decryptedText = vigenereCipher.decryptMessage(word, ciphertext)
if detectEnglish.isEnglish(decryptedText, wordPercentage=40):
# Check with user to see if the decrypted key has been found:
print()
print('Possible encryption break:')
print('Key ' + str(word) + ': ' + decryptedText[:100])
print()
print('Enter D for done, or just press Enter to continue breaking:')
response = input('> ')
if response.upper().startswith('D'):
return decryptedText
if __name__ == '__main__':
main()
| # Vigenère Cipher Dictionary Hacker
# https://www.nostarch.com/crackingcodes/ (BSD Licensed)
import detectEnglish, vigenereCipher, pyperclip
def main():
ciphertext = """Tzx isnz eccjxkg nfq lol mys bbqq I lxcz."""
hackedMessage = hackVigenereDictionary(ciphertext)
if hackedMessage != None:
print('Copying hacked message to clipboard:')
print(hackedMessage)
pyperclip.copy(hackedMessage)
else:
print('Failed to hack encryption.')
def hackVigenereDictionary(ciphertext):
fo = open('dictionary.txt')
words = fo.readlines()
fo.close()
for word in words:
word = word.strip() # Remove the newline at the end.
decryptedText = vigenereCipher.decryptMessage(word, ciphertext)
if detectEnglish.isEnglish(decryptedText, wordPercentage=40):
# Check with user to see if the decrypted key has been found:
print()
print('Possible encryption break:')
print('Key ' + str(word) + ': ' + decryptedText[:100])
print()
print('Enter D for done, or just press Enter to continue breaking:')
response = input('> ')
if response.upper().startswith('D'):
return decryptedText
if __name__ == '__main__':
main()
Update vigenereDicitonaryHacker: simplified comparison with None# Vigenère Cipher Dictionary Hacker
# https://www.nostarch.com/crackingcodes/ (BSD Licensed)
import detectEnglish, vigenereCipher, pyperclip
def main():
ciphertext = """Tzx isnz eccjxkg nfq lol mys bbqq I lxcz."""
hackedMessage = hackVigenereDictionary(ciphertext)
if not hackedMessage:
print('Copying hacked message to clipboard:')
print(hackedMessage)
pyperclip.copy(hackedMessage)
else:
print('Failed to hack encryption.')
def hackVigenereDictionary(ciphertext):
fo = open('dictionary.txt')
words = fo.readlines()
fo.close()
for word in words:
word = word.strip() # Remove the newline at the end.
decryptedText = vigenereCipher.decryptMessage(word, ciphertext)
if detectEnglish.isEnglish(decryptedText, wordPercentage=40):
# Check with user to see if the decrypted key has been found:
print()
print('Possible encryption break:')
print('Key ' + str(word) + ': ' + decryptedText[:100])
print()
print('Enter D for done, or just press Enter to continue breaking:')
response = input('> ')
if response.upper().startswith('D'):
return decryptedText
if __name__ == '__main__':
main()
| <commit_before># Vigenère Cipher Dictionary Hacker
# https://www.nostarch.com/crackingcodes/ (BSD Licensed)
import detectEnglish, vigenereCipher, pyperclip
def main():
ciphertext = """Tzx isnz eccjxkg nfq lol mys bbqq I lxcz."""
hackedMessage = hackVigenereDictionary(ciphertext)
if hackedMessage != None:
print('Copying hacked message to clipboard:')
print(hackedMessage)
pyperclip.copy(hackedMessage)
else:
print('Failed to hack encryption.')
def hackVigenereDictionary(ciphertext):
fo = open('dictionary.txt')
words = fo.readlines()
fo.close()
for word in words:
word = word.strip() # Remove the newline at the end.
decryptedText = vigenereCipher.decryptMessage(word, ciphertext)
if detectEnglish.isEnglish(decryptedText, wordPercentage=40):
# Check with user to see if the decrypted key has been found:
print()
print('Possible encryption break:')
print('Key ' + str(word) + ': ' + decryptedText[:100])
print()
print('Enter D for done, or just press Enter to continue breaking:')
response = input('> ')
if response.upper().startswith('D'):
return decryptedText
if __name__ == '__main__':
main()
<commit_msg>Update vigenereDicitonaryHacker: simplified comparison with None<commit_after># Vigenère Cipher Dictionary Hacker
# https://www.nostarch.com/crackingcodes/ (BSD Licensed)
import detectEnglish, vigenereCipher, pyperclip
def main():
ciphertext = """Tzx isnz eccjxkg nfq lol mys bbqq I lxcz."""
hackedMessage = hackVigenereDictionary(ciphertext)
if not hackedMessage:
print('Copying hacked message to clipboard:')
print(hackedMessage)
pyperclip.copy(hackedMessage)
else:
print('Failed to hack encryption.')
def hackVigenereDictionary(ciphertext):
fo = open('dictionary.txt')
words = fo.readlines()
fo.close()
for word in words:
word = word.strip() # Remove the newline at the end.
decryptedText = vigenereCipher.decryptMessage(word, ciphertext)
if detectEnglish.isEnglish(decryptedText, wordPercentage=40):
# Check with user to see if the decrypted key has been found:
print()
print('Possible encryption break:')
print('Key ' + str(word) + ': ' + decryptedText[:100])
print()
print('Enter D for done, or just press Enter to continue breaking:')
response = input('> ')
if response.upper().startswith('D'):
return decryptedText
if __name__ == '__main__':
main()
|
c69974ffabc0855db153b7f5a4af6105fae698f9 | docassemble_base/docassemble/base/pdfa.py | docassemble_base/docassemble/base/pdfa.py | import tempfile
import subprocess
import shutil
from docassemble.base.error import DAError
#from docassemble.base.logger import logmessage
def pdf_to_pdfa(filename):
outfile = tempfile.NamedTemporaryFile(suffix=".pdf", delete=False)
directory = tempfile.mkdtemp()
commands = ['gs', '-dPDFA', '-dBATCH', '-dNOPAUSE', '-sProcessColorModel=DeviceCMYK', '-sDEVICE=pdfwrite', '-sPDFACompatibilityPolicy=1', '-sOutputFile=' + outfile.name, filename]
try:
output = subprocess.check_output(commands, cwd=directory, stderr=subprocess.STDOUT).decode()
except subprocess.CalledProcessError as err:
output = err.output.decode()
raise DAError("pdf_to_pdfa: error running ghostscript. " + output)
shutil.move(outfile.name, filename)
| import tempfile
import subprocess
import shutil
from docassemble.base.error import DAError
#from docassemble.base.logger import logmessage
def pdf_to_pdfa(filename):
outfile = tempfile.NamedTemporaryFile(suffix=".pdf", delete=False)
directory = tempfile.mkdtemp()
commands = ['gs', '-dPDFA', '-dBATCH', '-dNOPAUSE', '-sColorConversionStrategy=UseDeviceIndependentColor', '-sProcessColorModel=DeviceCMYK', '-sDEVICE=pdfwrite', '-sPDFACompatibilityPolicy=1', '-sOutputFile=' + outfile.name, filename]
try:
output = subprocess.check_output(commands, cwd=directory, stderr=subprocess.STDOUT).decode()
except subprocess.CalledProcessError as err:
output = err.output.decode()
raise DAError("pdf_to_pdfa: error running ghostscript. " + output)
shutil.move(outfile.name, filename)
| Make ghostscript handle PDF/A colorspace correctly | Make ghostscript handle PDF/A colorspace correctly
Previously, if you tried to verify files generated by pdf_to_pdfa in a
verifier (like https://tools.pdfforge.org/validate-pdfa), you would get
errors relating to the lack of OutputIntent (6.2.3). The info in
https://stackoverflow.com/a/56459053/11416267 and
https://www.ghostscript.com/doc/current/VectorDevices.htm#PDFA suggested
that `-sColorConversionStrategy=UseDeviceIndependentColor` be added,
which corrects those validator errors, and verifies output PDFs as PDF/A-1b.
| Python | mit | jhpyle/docassemble,jhpyle/docassemble,jhpyle/docassemble,jhpyle/docassemble,jhpyle/docassemble | import tempfile
import subprocess
import shutil
from docassemble.base.error import DAError
#from docassemble.base.logger import logmessage
def pdf_to_pdfa(filename):
outfile = tempfile.NamedTemporaryFile(suffix=".pdf", delete=False)
directory = tempfile.mkdtemp()
commands = ['gs', '-dPDFA', '-dBATCH', '-dNOPAUSE', '-sProcessColorModel=DeviceCMYK', '-sDEVICE=pdfwrite', '-sPDFACompatibilityPolicy=1', '-sOutputFile=' + outfile.name, filename]
try:
output = subprocess.check_output(commands, cwd=directory, stderr=subprocess.STDOUT).decode()
except subprocess.CalledProcessError as err:
output = err.output.decode()
raise DAError("pdf_to_pdfa: error running ghostscript. " + output)
shutil.move(outfile.name, filename)
Make ghostscript handle PDF/A colorspace correctly
Previously, if you tried to verify files generated by pdf_to_pdfa in a
verifier (like https://tools.pdfforge.org/validate-pdfa), you would get
errors relating to the lack of OutputIntent (6.2.3). The info in
https://stackoverflow.com/a/56459053/11416267 and
https://www.ghostscript.com/doc/current/VectorDevices.htm#PDFA suggested
that `-sColorConversionStrategy=UseDeviceIndependentColor` be added,
which corrects those validator errors, and verifies output PDFs as PDF/A-1b. | import tempfile
import subprocess
import shutil
from docassemble.base.error import DAError
#from docassemble.base.logger import logmessage
def pdf_to_pdfa(filename):
outfile = tempfile.NamedTemporaryFile(suffix=".pdf", delete=False)
directory = tempfile.mkdtemp()
commands = ['gs', '-dPDFA', '-dBATCH', '-dNOPAUSE', '-sColorConversionStrategy=UseDeviceIndependentColor', '-sProcessColorModel=DeviceCMYK', '-sDEVICE=pdfwrite', '-sPDFACompatibilityPolicy=1', '-sOutputFile=' + outfile.name, filename]
try:
output = subprocess.check_output(commands, cwd=directory, stderr=subprocess.STDOUT).decode()
except subprocess.CalledProcessError as err:
output = err.output.decode()
raise DAError("pdf_to_pdfa: error running ghostscript. " + output)
shutil.move(outfile.name, filename)
| <commit_before>import tempfile
import subprocess
import shutil
from docassemble.base.error import DAError
#from docassemble.base.logger import logmessage
def pdf_to_pdfa(filename):
outfile = tempfile.NamedTemporaryFile(suffix=".pdf", delete=False)
directory = tempfile.mkdtemp()
commands = ['gs', '-dPDFA', '-dBATCH', '-dNOPAUSE', '-sProcessColorModel=DeviceCMYK', '-sDEVICE=pdfwrite', '-sPDFACompatibilityPolicy=1', '-sOutputFile=' + outfile.name, filename]
try:
output = subprocess.check_output(commands, cwd=directory, stderr=subprocess.STDOUT).decode()
except subprocess.CalledProcessError as err:
output = err.output.decode()
raise DAError("pdf_to_pdfa: error running ghostscript. " + output)
shutil.move(outfile.name, filename)
<commit_msg>Make ghostscript handle PDF/A colorspace correctly
Previously, if you tried to verify files generated by pdf_to_pdfa in a
verifier (like https://tools.pdfforge.org/validate-pdfa), you would get
errors relating to the lack of OutputIntent (6.2.3). The info in
https://stackoverflow.com/a/56459053/11416267 and
https://www.ghostscript.com/doc/current/VectorDevices.htm#PDFA suggested
that `-sColorConversionStrategy=UseDeviceIndependentColor` be added,
which corrects those validator errors, and verifies output PDFs as PDF/A-1b.<commit_after> | import tempfile
import subprocess
import shutil
from docassemble.base.error import DAError
#from docassemble.base.logger import logmessage
def pdf_to_pdfa(filename):
outfile = tempfile.NamedTemporaryFile(suffix=".pdf", delete=False)
directory = tempfile.mkdtemp()
commands = ['gs', '-dPDFA', '-dBATCH', '-dNOPAUSE', '-sColorConversionStrategy=UseDeviceIndependentColor', '-sProcessColorModel=DeviceCMYK', '-sDEVICE=pdfwrite', '-sPDFACompatibilityPolicy=1', '-sOutputFile=' + outfile.name, filename]
try:
output = subprocess.check_output(commands, cwd=directory, stderr=subprocess.STDOUT).decode()
except subprocess.CalledProcessError as err:
output = err.output.decode()
raise DAError("pdf_to_pdfa: error running ghostscript. " + output)
shutil.move(outfile.name, filename)
| import tempfile
import subprocess
import shutil
from docassemble.base.error import DAError
#from docassemble.base.logger import logmessage
def pdf_to_pdfa(filename):
outfile = tempfile.NamedTemporaryFile(suffix=".pdf", delete=False)
directory = tempfile.mkdtemp()
commands = ['gs', '-dPDFA', '-dBATCH', '-dNOPAUSE', '-sProcessColorModel=DeviceCMYK', '-sDEVICE=pdfwrite', '-sPDFACompatibilityPolicy=1', '-sOutputFile=' + outfile.name, filename]
try:
output = subprocess.check_output(commands, cwd=directory, stderr=subprocess.STDOUT).decode()
except subprocess.CalledProcessError as err:
output = err.output.decode()
raise DAError("pdf_to_pdfa: error running ghostscript. " + output)
shutil.move(outfile.name, filename)
Make ghostscript handle PDF/A colorspace correctly
Previously, if you tried to verify files generated by pdf_to_pdfa in a
verifier (like https://tools.pdfforge.org/validate-pdfa), you would get
errors relating to the lack of OutputIntent (6.2.3). The info in
https://stackoverflow.com/a/56459053/11416267 and
https://www.ghostscript.com/doc/current/VectorDevices.htm#PDFA suggested
that `-sColorConversionStrategy=UseDeviceIndependentColor` be added,
which corrects those validator errors, and verifies output PDFs as PDF/A-1b.import tempfile
import subprocess
import shutil
from docassemble.base.error import DAError
#from docassemble.base.logger import logmessage
def pdf_to_pdfa(filename):
outfile = tempfile.NamedTemporaryFile(suffix=".pdf", delete=False)
directory = tempfile.mkdtemp()
commands = ['gs', '-dPDFA', '-dBATCH', '-dNOPAUSE', '-sColorConversionStrategy=UseDeviceIndependentColor', '-sProcessColorModel=DeviceCMYK', '-sDEVICE=pdfwrite', '-sPDFACompatibilityPolicy=1', '-sOutputFile=' + outfile.name, filename]
try:
output = subprocess.check_output(commands, cwd=directory, stderr=subprocess.STDOUT).decode()
except subprocess.CalledProcessError as err:
output = err.output.decode()
raise DAError("pdf_to_pdfa: error running ghostscript. " + output)
shutil.move(outfile.name, filename)
| <commit_before>import tempfile
import subprocess
import shutil
from docassemble.base.error import DAError
#from docassemble.base.logger import logmessage
def pdf_to_pdfa(filename):
outfile = tempfile.NamedTemporaryFile(suffix=".pdf", delete=False)
directory = tempfile.mkdtemp()
commands = ['gs', '-dPDFA', '-dBATCH', '-dNOPAUSE', '-sProcessColorModel=DeviceCMYK', '-sDEVICE=pdfwrite', '-sPDFACompatibilityPolicy=1', '-sOutputFile=' + outfile.name, filename]
try:
output = subprocess.check_output(commands, cwd=directory, stderr=subprocess.STDOUT).decode()
except subprocess.CalledProcessError as err:
output = err.output.decode()
raise DAError("pdf_to_pdfa: error running ghostscript. " + output)
shutil.move(outfile.name, filename)
<commit_msg>Make ghostscript handle PDF/A colorspace correctly
Previously, if you tried to verify files generated by pdf_to_pdfa in a
verifier (like https://tools.pdfforge.org/validate-pdfa), you would get
errors relating to the lack of OutputIntent (6.2.3). The info in
https://stackoverflow.com/a/56459053/11416267 and
https://www.ghostscript.com/doc/current/VectorDevices.htm#PDFA suggested
that `-sColorConversionStrategy=UseDeviceIndependentColor` be added,
which corrects those validator errors, and verifies output PDFs as PDF/A-1b.<commit_after>import tempfile
import subprocess
import shutil
from docassemble.base.error import DAError
#from docassemble.base.logger import logmessage
def pdf_to_pdfa(filename):
outfile = tempfile.NamedTemporaryFile(suffix=".pdf", delete=False)
directory = tempfile.mkdtemp()
commands = ['gs', '-dPDFA', '-dBATCH', '-dNOPAUSE', '-sColorConversionStrategy=UseDeviceIndependentColor', '-sProcessColorModel=DeviceCMYK', '-sDEVICE=pdfwrite', '-sPDFACompatibilityPolicy=1', '-sOutputFile=' + outfile.name, filename]
try:
output = subprocess.check_output(commands, cwd=directory, stderr=subprocess.STDOUT).decode()
except subprocess.CalledProcessError as err:
output = err.output.decode()
raise DAError("pdf_to_pdfa: error running ghostscript. " + output)
shutil.move(outfile.name, filename)
|
884e7254bffcef4e5d3733b26f6eb0ea34b11da6 | core/project/Project.py | core/project/Project.py | """
Project
:Authors:
Berend Klein Haneveld
"""
class Project(object):
"""
Project holds the basic information of a project for RegistrationShop
"""
def __init__(self, title=None, fixedData=None, movingData=None, isReference=None):
super(Project, self).__init__()
self.title = title
self.fixedData = fixedData
self.movingData = movingData
self.isReference = isReference
self.folder = None
self.resultData = None
self.fixedSettings = None
self.movingSettings = None
self.multiSettings = None
def __eq__(self, other):
if not isinstance(other, Project):
return False
return (self.title == other.title
and self.fixedData == other.fixedData
and self.movingData == other.movingData
and self.isReference == other.isReference)
def __ne__(self, other):
return not self.__eq__(other)
| """
Project
:Authors:
Berend Klein Haneveld
"""
class Project(object):
"""
Project holds the basic information of a project for RegistrationShop
"""
def __init__(self, title=None, fixedData=None, movingData=None, isReference=None):
super(Project, self).__init__()
self.title = title
self.fixedData = fixedData
self.movingData = movingData
self.isReference = isReference
self.folder = None
self.resultData = None
self.fixedSettings = None
self.movingSettings = None
self.multiSettings = None
self.transformations = None
def __eq__(self, other):
if not isinstance(other, Project):
return False
return (self.title == other.title
and self.fixedData == other.fixedData
and self.movingData == other.movingData
and self.isReference == other.isReference)
def __ne__(self, other):
return not self.__eq__(other)
| Add transformations property to projects. | Add transformations property to projects.
| Python | mit | berendkleinhaneveld/Registrationshop,berendkleinhaneveld/Registrationshop | """
Project
:Authors:
Berend Klein Haneveld
"""
class Project(object):
"""
Project holds the basic information of a project for RegistrationShop
"""
def __init__(self, title=None, fixedData=None, movingData=None, isReference=None):
super(Project, self).__init__()
self.title = title
self.fixedData = fixedData
self.movingData = movingData
self.isReference = isReference
self.folder = None
self.resultData = None
self.fixedSettings = None
self.movingSettings = None
self.multiSettings = None
def __eq__(self, other):
if not isinstance(other, Project):
return False
return (self.title == other.title
and self.fixedData == other.fixedData
and self.movingData == other.movingData
and self.isReference == other.isReference)
def __ne__(self, other):
return not self.__eq__(other)
Add transformations property to projects. | """
Project
:Authors:
Berend Klein Haneveld
"""
class Project(object):
"""
Project holds the basic information of a project for RegistrationShop
"""
def __init__(self, title=None, fixedData=None, movingData=None, isReference=None):
super(Project, self).__init__()
self.title = title
self.fixedData = fixedData
self.movingData = movingData
self.isReference = isReference
self.folder = None
self.resultData = None
self.fixedSettings = None
self.movingSettings = None
self.multiSettings = None
self.transformations = None
def __eq__(self, other):
if not isinstance(other, Project):
return False
return (self.title == other.title
and self.fixedData == other.fixedData
and self.movingData == other.movingData
and self.isReference == other.isReference)
def __ne__(self, other):
return not self.__eq__(other)
| <commit_before>"""
Project
:Authors:
Berend Klein Haneveld
"""
class Project(object):
"""
Project holds the basic information of a project for RegistrationShop
"""
def __init__(self, title=None, fixedData=None, movingData=None, isReference=None):
super(Project, self).__init__()
self.title = title
self.fixedData = fixedData
self.movingData = movingData
self.isReference = isReference
self.folder = None
self.resultData = None
self.fixedSettings = None
self.movingSettings = None
self.multiSettings = None
def __eq__(self, other):
if not isinstance(other, Project):
return False
return (self.title == other.title
and self.fixedData == other.fixedData
and self.movingData == other.movingData
and self.isReference == other.isReference)
def __ne__(self, other):
return not self.__eq__(other)
<commit_msg>Add transformations property to projects.<commit_after> | """
Project
:Authors:
Berend Klein Haneveld
"""
class Project(object):
"""
Project holds the basic information of a project for RegistrationShop
"""
def __init__(self, title=None, fixedData=None, movingData=None, isReference=None):
super(Project, self).__init__()
self.title = title
self.fixedData = fixedData
self.movingData = movingData
self.isReference = isReference
self.folder = None
self.resultData = None
self.fixedSettings = None
self.movingSettings = None
self.multiSettings = None
self.transformations = None
def __eq__(self, other):
if not isinstance(other, Project):
return False
return (self.title == other.title
and self.fixedData == other.fixedData
and self.movingData == other.movingData
and self.isReference == other.isReference)
def __ne__(self, other):
return not self.__eq__(other)
| """
Project
:Authors:
Berend Klein Haneveld
"""
class Project(object):
"""
Project holds the basic information of a project for RegistrationShop
"""
def __init__(self, title=None, fixedData=None, movingData=None, isReference=None):
super(Project, self).__init__()
self.title = title
self.fixedData = fixedData
self.movingData = movingData
self.isReference = isReference
self.folder = None
self.resultData = None
self.fixedSettings = None
self.movingSettings = None
self.multiSettings = None
def __eq__(self, other):
if not isinstance(other, Project):
return False
return (self.title == other.title
and self.fixedData == other.fixedData
and self.movingData == other.movingData
and self.isReference == other.isReference)
def __ne__(self, other):
return not self.__eq__(other)
Add transformations property to projects."""
Project
:Authors:
Berend Klein Haneveld
"""
class Project(object):
"""
Project holds the basic information of a project for RegistrationShop
"""
def __init__(self, title=None, fixedData=None, movingData=None, isReference=None):
super(Project, self).__init__()
self.title = title
self.fixedData = fixedData
self.movingData = movingData
self.isReference = isReference
self.folder = None
self.resultData = None
self.fixedSettings = None
self.movingSettings = None
self.multiSettings = None
self.transformations = None
def __eq__(self, other):
if not isinstance(other, Project):
return False
return (self.title == other.title
and self.fixedData == other.fixedData
and self.movingData == other.movingData
and self.isReference == other.isReference)
def __ne__(self, other):
return not self.__eq__(other)
| <commit_before>"""
Project
:Authors:
Berend Klein Haneveld
"""
class Project(object):
"""
Project holds the basic information of a project for RegistrationShop
"""
def __init__(self, title=None, fixedData=None, movingData=None, isReference=None):
super(Project, self).__init__()
self.title = title
self.fixedData = fixedData
self.movingData = movingData
self.isReference = isReference
self.folder = None
self.resultData = None
self.fixedSettings = None
self.movingSettings = None
self.multiSettings = None
def __eq__(self, other):
if not isinstance(other, Project):
return False
return (self.title == other.title
and self.fixedData == other.fixedData
and self.movingData == other.movingData
and self.isReference == other.isReference)
def __ne__(self, other):
return not self.__eq__(other)
<commit_msg>Add transformations property to projects.<commit_after>"""
Project
:Authors:
Berend Klein Haneveld
"""
class Project(object):
"""
Project holds the basic information of a project for RegistrationShop
"""
def __init__(self, title=None, fixedData=None, movingData=None, isReference=None):
super(Project, self).__init__()
self.title = title
self.fixedData = fixedData
self.movingData = movingData
self.isReference = isReference
self.folder = None
self.resultData = None
self.fixedSettings = None
self.movingSettings = None
self.multiSettings = None
self.transformations = None
def __eq__(self, other):
if not isinstance(other, Project):
return False
return (self.title == other.title
and self.fixedData == other.fixedData
and self.movingData == other.movingData
and self.isReference == other.isReference)
def __ne__(self, other):
return not self.__eq__(other)
|
e68e03fe5e858e9c5c65788d2d1126b8bf37772b | subversion/bindings/swig/python/tests/run_all.py | subversion/bindings/swig/python/tests/run_all.py | import sys, os
bindir = os.path.dirname(sys.argv[0])
sys.path[0:0] = [ os.getcwd(), "%s/.libs" % os.getcwd(), \
"%s/.." % bindir, "%s/../.libs" % bindir ]
import unittest
import pool
import trac.versioncontrol.tests
# Run all tests
def suite():
"""Run all tests"""
suite = unittest.TestSuite()
suite.addTest(pool.suite())
suite.addTest(trac.versioncontrol.tests.suite());
return suite
if __name__ == '__main__':
unittest.main(defaultTest='suite')
| import sys, os
bindir = os.path.dirname(sys.argv[0])
sys.path[0:0] = [ os.getcwd(), "%s/.libs" % os.getcwd(), \
"%s/.." % bindir, "%s/../.libs" % bindir ]
# OSes without RPATH support are going to have to do things here to make
# the correct shared libraries be found.
if sys.platform == 'cygwin':
import glob
svndir = os.path.dirname(os.path.dirname(os.path.dirname(os.getcwd())))
libpath = os.getenv("PATH").split(":")
libpath.insert(0, "%s/libsvn_swig_py/.libs" % os.getcwd())
for libdir in glob.glob("%s/libsvn_*" % svndir):
libpath.insert(0, "%s/.libs" % (libdir))
os.putenv("PATH", ":".join(libpath))
import unittest
import pool
import trac.versioncontrol.tests
# Run all tests
def suite():
"""Run all tests"""
suite = unittest.TestSuite()
suite.addTest(pool.suite())
suite.addTest(trac.versioncontrol.tests.suite());
return suite
if __name__ == '__main__':
unittest.main(defaultTest='suite')
| Make the Python bindings testsuite be able to find the needed shared libraries on Cygwin. Needed to compensate for Windows' complete lack of library RPATHs. | Make the Python bindings testsuite be able to find the needed shared libraries
on Cygwin. Needed to compensate for Windows' complete lack of library RPATHs.
* subversion/bindings/swig/python/tests/run_all.py: On Cygwin, manipulate $PATH
so that the relevant shared libraries are found.
git-svn-id: f8a4e5e023278da1e04e203c7fe051e3c4285d88@856452 13f79535-47bb-0310-9956-ffa450edef68
| Python | apache-2.0 | wbond/subversion,YueLinHo/Subversion,YueLinHo/Subversion,YueLinHo/Subversion,wbond/subversion,wbond/subversion,YueLinHo/Subversion,wbond/subversion,wbond/subversion,YueLinHo/Subversion,YueLinHo/Subversion,wbond/subversion,wbond/subversion,YueLinHo/Subversion,YueLinHo/Subversion | import sys, os
bindir = os.path.dirname(sys.argv[0])
sys.path[0:0] = [ os.getcwd(), "%s/.libs" % os.getcwd(), \
"%s/.." % bindir, "%s/../.libs" % bindir ]
import unittest
import pool
import trac.versioncontrol.tests
# Run all tests
def suite():
"""Run all tests"""
suite = unittest.TestSuite()
suite.addTest(pool.suite())
suite.addTest(trac.versioncontrol.tests.suite());
return suite
if __name__ == '__main__':
unittest.main(defaultTest='suite')
Make the Python bindings testsuite be able to find the needed shared libraries
on Cygwin. Needed to compensate for Windows' complete lack of library RPATHs.
* subversion/bindings/swig/python/tests/run_all.py: On Cygwin, manipulate $PATH
so that the relevant shared libraries are found.
git-svn-id: f8a4e5e023278da1e04e203c7fe051e3c4285d88@856452 13f79535-47bb-0310-9956-ffa450edef68 | import sys, os
bindir = os.path.dirname(sys.argv[0])
sys.path[0:0] = [ os.getcwd(), "%s/.libs" % os.getcwd(), \
"%s/.." % bindir, "%s/../.libs" % bindir ]
# OSes without RPATH support are going to have to do things here to make
# the correct shared libraries be found.
if sys.platform == 'cygwin':
import glob
svndir = os.path.dirname(os.path.dirname(os.path.dirname(os.getcwd())))
libpath = os.getenv("PATH").split(":")
libpath.insert(0, "%s/libsvn_swig_py/.libs" % os.getcwd())
for libdir in glob.glob("%s/libsvn_*" % svndir):
libpath.insert(0, "%s/.libs" % (libdir))
os.putenv("PATH", ":".join(libpath))
import unittest
import pool
import trac.versioncontrol.tests
# Run all tests
def suite():
"""Run all tests"""
suite = unittest.TestSuite()
suite.addTest(pool.suite())
suite.addTest(trac.versioncontrol.tests.suite());
return suite
if __name__ == '__main__':
unittest.main(defaultTest='suite')
| <commit_before>import sys, os
bindir = os.path.dirname(sys.argv[0])
sys.path[0:0] = [ os.getcwd(), "%s/.libs" % os.getcwd(), \
"%s/.." % bindir, "%s/../.libs" % bindir ]
import unittest
import pool
import trac.versioncontrol.tests
# Run all tests
def suite():
"""Run all tests"""
suite = unittest.TestSuite()
suite.addTest(pool.suite())
suite.addTest(trac.versioncontrol.tests.suite());
return suite
if __name__ == '__main__':
unittest.main(defaultTest='suite')
<commit_msg>Make the Python bindings testsuite be able to find the needed shared libraries
on Cygwin. Needed to compensate for Windows' complete lack of library RPATHs.
* subversion/bindings/swig/python/tests/run_all.py: On Cygwin, manipulate $PATH
so that the relevant shared libraries are found.
git-svn-id: f8a4e5e023278da1e04e203c7fe051e3c4285d88@856452 13f79535-47bb-0310-9956-ffa450edef68<commit_after> | import sys, os
bindir = os.path.dirname(sys.argv[0])
sys.path[0:0] = [ os.getcwd(), "%s/.libs" % os.getcwd(), \
"%s/.." % bindir, "%s/../.libs" % bindir ]
# OSes without RPATH support are going to have to do things here to make
# the correct shared libraries be found.
if sys.platform == 'cygwin':
import glob
svndir = os.path.dirname(os.path.dirname(os.path.dirname(os.getcwd())))
libpath = os.getenv("PATH").split(":")
libpath.insert(0, "%s/libsvn_swig_py/.libs" % os.getcwd())
for libdir in glob.glob("%s/libsvn_*" % svndir):
libpath.insert(0, "%s/.libs" % (libdir))
os.putenv("PATH", ":".join(libpath))
import unittest
import pool
import trac.versioncontrol.tests
# Run all tests
def suite():
"""Run all tests"""
suite = unittest.TestSuite()
suite.addTest(pool.suite())
suite.addTest(trac.versioncontrol.tests.suite());
return suite
if __name__ == '__main__':
unittest.main(defaultTest='suite')
| import sys, os
bindir = os.path.dirname(sys.argv[0])
sys.path[0:0] = [ os.getcwd(), "%s/.libs" % os.getcwd(), \
"%s/.." % bindir, "%s/../.libs" % bindir ]
import unittest
import pool
import trac.versioncontrol.tests
# Run all tests
def suite():
"""Run all tests"""
suite = unittest.TestSuite()
suite.addTest(pool.suite())
suite.addTest(trac.versioncontrol.tests.suite());
return suite
if __name__ == '__main__':
unittest.main(defaultTest='suite')
Make the Python bindings testsuite be able to find the needed shared libraries
on Cygwin. Needed to compensate for Windows' complete lack of library RPATHs.
* subversion/bindings/swig/python/tests/run_all.py: On Cygwin, manipulate $PATH
so that the relevant shared libraries are found.
git-svn-id: f8a4e5e023278da1e04e203c7fe051e3c4285d88@856452 13f79535-47bb-0310-9956-ffa450edef68import sys, os
bindir = os.path.dirname(sys.argv[0])
sys.path[0:0] = [ os.getcwd(), "%s/.libs" % os.getcwd(), \
"%s/.." % bindir, "%s/../.libs" % bindir ]
# OSes without RPATH support are going to have to do things here to make
# the correct shared libraries be found.
if sys.platform == 'cygwin':
import glob
svndir = os.path.dirname(os.path.dirname(os.path.dirname(os.getcwd())))
libpath = os.getenv("PATH").split(":")
libpath.insert(0, "%s/libsvn_swig_py/.libs" % os.getcwd())
for libdir in glob.glob("%s/libsvn_*" % svndir):
libpath.insert(0, "%s/.libs" % (libdir))
os.putenv("PATH", ":".join(libpath))
import unittest
import pool
import trac.versioncontrol.tests
# Run all tests
def suite():
"""Run all tests"""
suite = unittest.TestSuite()
suite.addTest(pool.suite())
suite.addTest(trac.versioncontrol.tests.suite());
return suite
if __name__ == '__main__':
unittest.main(defaultTest='suite')
| <commit_before>import sys, os
bindir = os.path.dirname(sys.argv[0])
sys.path[0:0] = [ os.getcwd(), "%s/.libs" % os.getcwd(), \
"%s/.." % bindir, "%s/../.libs" % bindir ]
import unittest
import pool
import trac.versioncontrol.tests
# Run all tests
def suite():
"""Run all tests"""
suite = unittest.TestSuite()
suite.addTest(pool.suite())
suite.addTest(trac.versioncontrol.tests.suite());
return suite
if __name__ == '__main__':
unittest.main(defaultTest='suite')
<commit_msg>Make the Python bindings testsuite be able to find the needed shared libraries
on Cygwin. Needed to compensate for Windows' complete lack of library RPATHs.
* subversion/bindings/swig/python/tests/run_all.py: On Cygwin, manipulate $PATH
so that the relevant shared libraries are found.
git-svn-id: f8a4e5e023278da1e04e203c7fe051e3c4285d88@856452 13f79535-47bb-0310-9956-ffa450edef68<commit_after>import sys, os
bindir = os.path.dirname(sys.argv[0])
sys.path[0:0] = [ os.getcwd(), "%s/.libs" % os.getcwd(), \
"%s/.." % bindir, "%s/../.libs" % bindir ]
# OSes without RPATH support are going to have to do things here to make
# the correct shared libraries be found.
if sys.platform == 'cygwin':
import glob
svndir = os.path.dirname(os.path.dirname(os.path.dirname(os.getcwd())))
libpath = os.getenv("PATH").split(":")
libpath.insert(0, "%s/libsvn_swig_py/.libs" % os.getcwd())
for libdir in glob.glob("%s/libsvn_*" % svndir):
libpath.insert(0, "%s/.libs" % (libdir))
os.putenv("PATH", ":".join(libpath))
import unittest
import pool
import trac.versioncontrol.tests
# Run all tests
def suite():
"""Run all tests"""
suite = unittest.TestSuite()
suite.addTest(pool.suite())
suite.addTest(trac.versioncontrol.tests.suite());
return suite
if __name__ == '__main__':
unittest.main(defaultTest='suite')
|
3b5f1749a8065bb9241d6a8ed77c047a05b3f6e2 | bcbio/distributed/sge.py | bcbio/distributed/sge.py | """Commandline interaction with SGE cluster schedulers.
"""
import re
import subprocess
_jobid_pat = re.compile('Your job (?P<jobid>\d+) \("')
def submit_job(scheduler_args, command):
"""Submit a job to the scheduler, returning the supplied job ID.
"""
cl = ["qsub", "-cwd", "-b", "y", "-j", "y"] + scheduler_args + command
status = subprocess.check_output(cl)
match = _jobid_pat.search(status)
return match.groups("jobid")[0]
def stop_job(jobid):
cl = ["qdel", jobid]
subprocess.check_call(cl)
def are_running(jobids):
"""Check if submitted job IDs are running.
"""
run_info = subprocess.check_output(["qstat"])
running = []
for parts in (l.split() for l in run_info.split("\n") if l.strip()):
if len(parts) >= 5:
pid, _, _, _, status = parts[:5]
if status.lower() in ["r"]:
running.append(pid)
want_running = set(running).intersection(set(jobids))
return len(want_running) == len(jobids)
| """Commandline interaction with SGE cluster schedulers.
"""
import re
import time
import subprocess
_jobid_pat = re.compile('Your job (?P<jobid>\d+) \("')
def submit_job(scheduler_args, command):
"""Submit a job to the scheduler, returning the supplied job ID.
"""
cl = ["qsub", "-cwd", "-b", "y", "-j", "y"] + scheduler_args + command
status = subprocess.check_output(cl)
match = _jobid_pat.search(status)
return match.groups("jobid")[0]
def stop_job(jobid):
cl = ["qdel", jobid]
subprocess.check_call(cl)
def are_running(jobids):
"""Check if submitted job IDs are running.
"""
# handle SGE errors, retrying to get the current status
max_retries = 10
tried = 0
while 1:
try:
run_info = subprocess.check_output(["qstat"])
break
except:
tried += 1
if tried > max_retries:
raise
time.sleep(5)
running = []
for parts in (l.split() for l in run_info.split("\n") if l.strip()):
if len(parts) >= 5:
pid, _, _, _, status = parts[:5]
if status.lower() in ["r"]:
running.append(pid)
want_running = set(running).intersection(set(jobids))
return len(want_running) == len(jobids)
| Handle temporary errors returned from SGE qstat | Handle temporary errors returned from SGE qstat
| Python | mit | biocyberman/bcbio-nextgen,Cyberbio-Lab/bcbio-nextgen,mjafin/bcbio-nextgen,chapmanb/bcbio-nextgen,lpantano/bcbio-nextgen,fw1121/bcbio-nextgen,brainstorm/bcbio-nextgen,fw1121/bcbio-nextgen,elkingtonmcb/bcbio-nextgen,verdurin/bcbio-nextgen,mjafin/bcbio-nextgen,vladsaveliev/bcbio-nextgen,SciLifeLab/bcbio-nextgen,SciLifeLab/bcbio-nextgen,chapmanb/bcbio-nextgen,lbeltrame/bcbio-nextgen,a113n/bcbio-nextgen,biocyberman/bcbio-nextgen,elkingtonmcb/bcbio-nextgen,hjanime/bcbio-nextgen,Cyberbio-Lab/bcbio-nextgen,hjanime/bcbio-nextgen,verdurin/bcbio-nextgen,vladsaveliev/bcbio-nextgen,a113n/bcbio-nextgen,lpantano/bcbio-nextgen,mjafin/bcbio-nextgen,gifford-lab/bcbio-nextgen,gifford-lab/bcbio-nextgen,hjanime/bcbio-nextgen,brainstorm/bcbio-nextgen,gifford-lab/bcbio-nextgen,guillermo-carrasco/bcbio-nextgen,chapmanb/bcbio-nextgen,vladsaveliev/bcbio-nextgen,lpantano/bcbio-nextgen,a113n/bcbio-nextgen,brainstorm/bcbio-nextgen,elkingtonmcb/bcbio-nextgen,guillermo-carrasco/bcbio-nextgen,biocyberman/bcbio-nextgen,Cyberbio-Lab/bcbio-nextgen,SciLifeLab/bcbio-nextgen,fw1121/bcbio-nextgen,verdurin/bcbio-nextgen,lbeltrame/bcbio-nextgen,guillermo-carrasco/bcbio-nextgen,lbeltrame/bcbio-nextgen | """Commandline interaction with SGE cluster schedulers.
"""
import re
import subprocess
_jobid_pat = re.compile('Your job (?P<jobid>\d+) \("')
def submit_job(scheduler_args, command):
"""Submit a job to the scheduler, returning the supplied job ID.
"""
cl = ["qsub", "-cwd", "-b", "y", "-j", "y"] + scheduler_args + command
status = subprocess.check_output(cl)
match = _jobid_pat.search(status)
return match.groups("jobid")[0]
def stop_job(jobid):
cl = ["qdel", jobid]
subprocess.check_call(cl)
def are_running(jobids):
"""Check if submitted job IDs are running.
"""
run_info = subprocess.check_output(["qstat"])
running = []
for parts in (l.split() for l in run_info.split("\n") if l.strip()):
if len(parts) >= 5:
pid, _, _, _, status = parts[:5]
if status.lower() in ["r"]:
running.append(pid)
want_running = set(running).intersection(set(jobids))
return len(want_running) == len(jobids)
Handle temporary errors returned from SGE qstat | """Commandline interaction with SGE cluster schedulers.
"""
import re
import time
import subprocess
_jobid_pat = re.compile('Your job (?P<jobid>\d+) \("')
def submit_job(scheduler_args, command):
"""Submit a job to the scheduler, returning the supplied job ID.
"""
cl = ["qsub", "-cwd", "-b", "y", "-j", "y"] + scheduler_args + command
status = subprocess.check_output(cl)
match = _jobid_pat.search(status)
return match.groups("jobid")[0]
def stop_job(jobid):
cl = ["qdel", jobid]
subprocess.check_call(cl)
def are_running(jobids):
"""Check if submitted job IDs are running.
"""
# handle SGE errors, retrying to get the current status
max_retries = 10
tried = 0
while 1:
try:
run_info = subprocess.check_output(["qstat"])
break
except:
tried += 1
if tried > max_retries:
raise
time.sleep(5)
running = []
for parts in (l.split() for l in run_info.split("\n") if l.strip()):
if len(parts) >= 5:
pid, _, _, _, status = parts[:5]
if status.lower() in ["r"]:
running.append(pid)
want_running = set(running).intersection(set(jobids))
return len(want_running) == len(jobids)
| <commit_before>"""Commandline interaction with SGE cluster schedulers.
"""
import re
import subprocess
_jobid_pat = re.compile('Your job (?P<jobid>\d+) \("')
def submit_job(scheduler_args, command):
"""Submit a job to the scheduler, returning the supplied job ID.
"""
cl = ["qsub", "-cwd", "-b", "y", "-j", "y"] + scheduler_args + command
status = subprocess.check_output(cl)
match = _jobid_pat.search(status)
return match.groups("jobid")[0]
def stop_job(jobid):
cl = ["qdel", jobid]
subprocess.check_call(cl)
def are_running(jobids):
"""Check if submitted job IDs are running.
"""
run_info = subprocess.check_output(["qstat"])
running = []
for parts in (l.split() for l in run_info.split("\n") if l.strip()):
if len(parts) >= 5:
pid, _, _, _, status = parts[:5]
if status.lower() in ["r"]:
running.append(pid)
want_running = set(running).intersection(set(jobids))
return len(want_running) == len(jobids)
<commit_msg>Handle temporary errors returned from SGE qstat<commit_after> | """Commandline interaction with SGE cluster schedulers.
"""
import re
import time
import subprocess
_jobid_pat = re.compile('Your job (?P<jobid>\d+) \("')
def submit_job(scheduler_args, command):
"""Submit a job to the scheduler, returning the supplied job ID.
"""
cl = ["qsub", "-cwd", "-b", "y", "-j", "y"] + scheduler_args + command
status = subprocess.check_output(cl)
match = _jobid_pat.search(status)
return match.groups("jobid")[0]
def stop_job(jobid):
cl = ["qdel", jobid]
subprocess.check_call(cl)
def are_running(jobids):
"""Check if submitted job IDs are running.
"""
# handle SGE errors, retrying to get the current status
max_retries = 10
tried = 0
while 1:
try:
run_info = subprocess.check_output(["qstat"])
break
except:
tried += 1
if tried > max_retries:
raise
time.sleep(5)
running = []
for parts in (l.split() for l in run_info.split("\n") if l.strip()):
if len(parts) >= 5:
pid, _, _, _, status = parts[:5]
if status.lower() in ["r"]:
running.append(pid)
want_running = set(running).intersection(set(jobids))
return len(want_running) == len(jobids)
| """Commandline interaction with SGE cluster schedulers.
"""
import re
import subprocess
_jobid_pat = re.compile('Your job (?P<jobid>\d+) \("')
def submit_job(scheduler_args, command):
"""Submit a job to the scheduler, returning the supplied job ID.
"""
cl = ["qsub", "-cwd", "-b", "y", "-j", "y"] + scheduler_args + command
status = subprocess.check_output(cl)
match = _jobid_pat.search(status)
return match.groups("jobid")[0]
def stop_job(jobid):
cl = ["qdel", jobid]
subprocess.check_call(cl)
def are_running(jobids):
"""Check if submitted job IDs are running.
"""
run_info = subprocess.check_output(["qstat"])
running = []
for parts in (l.split() for l in run_info.split("\n") if l.strip()):
if len(parts) >= 5:
pid, _, _, _, status = parts[:5]
if status.lower() in ["r"]:
running.append(pid)
want_running = set(running).intersection(set(jobids))
return len(want_running) == len(jobids)
Handle temporary errors returned from SGE qstat"""Commandline interaction with SGE cluster schedulers.
"""
import re
import time
import subprocess
_jobid_pat = re.compile('Your job (?P<jobid>\d+) \("')
def submit_job(scheduler_args, command):
"""Submit a job to the scheduler, returning the supplied job ID.
"""
cl = ["qsub", "-cwd", "-b", "y", "-j", "y"] + scheduler_args + command
status = subprocess.check_output(cl)
match = _jobid_pat.search(status)
return match.groups("jobid")[0]
def stop_job(jobid):
cl = ["qdel", jobid]
subprocess.check_call(cl)
def are_running(jobids):
"""Check if submitted job IDs are running.
"""
# handle SGE errors, retrying to get the current status
max_retries = 10
tried = 0
while 1:
try:
run_info = subprocess.check_output(["qstat"])
break
except:
tried += 1
if tried > max_retries:
raise
time.sleep(5)
running = []
for parts in (l.split() for l in run_info.split("\n") if l.strip()):
if len(parts) >= 5:
pid, _, _, _, status = parts[:5]
if status.lower() in ["r"]:
running.append(pid)
want_running = set(running).intersection(set(jobids))
return len(want_running) == len(jobids)
| <commit_before>"""Commandline interaction with SGE cluster schedulers.
"""
import re
import subprocess
_jobid_pat = re.compile('Your job (?P<jobid>\d+) \("')
def submit_job(scheduler_args, command):
"""Submit a job to the scheduler, returning the supplied job ID.
"""
cl = ["qsub", "-cwd", "-b", "y", "-j", "y"] + scheduler_args + command
status = subprocess.check_output(cl)
match = _jobid_pat.search(status)
return match.groups("jobid")[0]
def stop_job(jobid):
cl = ["qdel", jobid]
subprocess.check_call(cl)
def are_running(jobids):
"""Check if submitted job IDs are running.
"""
run_info = subprocess.check_output(["qstat"])
running = []
for parts in (l.split() for l in run_info.split("\n") if l.strip()):
if len(parts) >= 5:
pid, _, _, _, status = parts[:5]
if status.lower() in ["r"]:
running.append(pid)
want_running = set(running).intersection(set(jobids))
return len(want_running) == len(jobids)
<commit_msg>Handle temporary errors returned from SGE qstat<commit_after>"""Commandline interaction with SGE cluster schedulers.
"""
import re
import time
import subprocess
_jobid_pat = re.compile('Your job (?P<jobid>\d+) \("')
def submit_job(scheduler_args, command):
"""Submit a job to the scheduler, returning the supplied job ID.
"""
cl = ["qsub", "-cwd", "-b", "y", "-j", "y"] + scheduler_args + command
status = subprocess.check_output(cl)
match = _jobid_pat.search(status)
return match.groups("jobid")[0]
def stop_job(jobid):
cl = ["qdel", jobid]
subprocess.check_call(cl)
def are_running(jobids):
"""Check if submitted job IDs are running.
"""
# handle SGE errors, retrying to get the current status
max_retries = 10
tried = 0
while 1:
try:
run_info = subprocess.check_output(["qstat"])
break
except:
tried += 1
if tried > max_retries:
raise
time.sleep(5)
running = []
for parts in (l.split() for l in run_info.split("\n") if l.strip()):
if len(parts) >= 5:
pid, _, _, _, status = parts[:5]
if status.lower() in ["r"]:
running.append(pid)
want_running = set(running).intersection(set(jobids))
return len(want_running) == len(jobids)
|
6b07646f085de7f5eae2c0695584bce48f812b44 | save_na_results.py | save_na_results.py | #!/usr/bin/python
import os
import sys
def save_na_results(folder_path=None):
"""Move the results of a Neighborhood Algorithm run to a folder with metadata.
This will copy all files with extensions of:
npy, txt, eps, png and dat
to the specified folder_path.
For now there is nothing stored in the folder that will be taken in by this
but we should be careful not to introduce anything that will be copied, or
at least modify this script accordingly if we do.
"""
if sys.platform is 'win32':
raise NotImplementedError('Will not currently work on Windows.')
if folder_path is None:
folder_path = sys.argv[1]
if not os.path.exists(folder_path):
os.makedirs(folder_path)
else:
raise Exception('Directory already exists; %s' % folder_path)
try:
os.system("cp *.npy %s" % folder_path)
os.system("cp *.txt %s" % folder_path)
os.system("cp *.png %s" % folder_path)
os.system("cp *.dat %s" % folder_path)
except OSError('Something went wrong while copying.'), e:
print 'Got:', e.args
else:
print 'Results were copied into %s' % folder_path
if __name__ == '__main__':
save_na_results()
| #!/usr/bin/python
import os
import sys
def save_na_results(folder_path=None):
"""Move the results of a Neighborhood Algorithm run to a folder with metadata.
This will copy all files with extensions of:
npy, txt, eps, png and dat
to the specified folder_path.
For now there is nothing stored in the folder that will be taken in by this
but we should be careful not to introduce anything that will be copied, or
at least modify this script accordingly if we do.
"""
if sys.platform is 'win32':
raise NotImplementedError('Will not currently work on Windows.')
if folder_path is None:
folder_path = sys.argv[1]
if not os.path.exists(folder_path):
os.makedirs(folder_path)
else:
raise Exception('Directory already exists; %s' % folder_path)
try:
os.system("cp *.npy %s" % folder_path)
os.system("cp *.txt %s" % folder_path)
os.system("cp *.png %s" % folder_path)
os.system("cp *.svg %s" % folder_path)
os.system("cp *.dat %s" % folder_path)
except OSError('Something went wrong while copying.'), e:
print 'Got:', e.args
else:
print 'Results were copied into %s' % folder_path
if __name__ == '__main__':
save_na_results()
| Save svg files, eps are not used anymore because they don't hand transparency. | Save svg files, eps are not used anymore because they don't hand transparency.
| Python | bsd-2-clause | cosmolab/cosmogenic | #!/usr/bin/python
import os
import sys
def save_na_results(folder_path=None):
"""Move the results of a Neighborhood Algorithm run to a folder with metadata.
This will copy all files with extensions of:
npy, txt, eps, png and dat
to the specified folder_path.
For now there is nothing stored in the folder that will be taken in by this
but we should be careful not to introduce anything that will be copied, or
at least modify this script accordingly if we do.
"""
if sys.platform is 'win32':
raise NotImplementedError('Will not currently work on Windows.')
if folder_path is None:
folder_path = sys.argv[1]
if not os.path.exists(folder_path):
os.makedirs(folder_path)
else:
raise Exception('Directory already exists; %s' % folder_path)
try:
os.system("cp *.npy %s" % folder_path)
os.system("cp *.txt %s" % folder_path)
os.system("cp *.png %s" % folder_path)
os.system("cp *.dat %s" % folder_path)
except OSError('Something went wrong while copying.'), e:
print 'Got:', e.args
else:
print 'Results were copied into %s' % folder_path
if __name__ == '__main__':
save_na_results()
Save svg files, eps are not used anymore because they don't hand transparency. | #!/usr/bin/python
import os
import sys
def save_na_results(folder_path=None):
"""Move the results of a Neighborhood Algorithm run to a folder with metadata.
This will copy all files with extensions of:
npy, txt, eps, png and dat
to the specified folder_path.
For now there is nothing stored in the folder that will be taken in by this
but we should be careful not to introduce anything that will be copied, or
at least modify this script accordingly if we do.
"""
if sys.platform is 'win32':
raise NotImplementedError('Will not currently work on Windows.')
if folder_path is None:
folder_path = sys.argv[1]
if not os.path.exists(folder_path):
os.makedirs(folder_path)
else:
raise Exception('Directory already exists; %s' % folder_path)
try:
os.system("cp *.npy %s" % folder_path)
os.system("cp *.txt %s" % folder_path)
os.system("cp *.png %s" % folder_path)
os.system("cp *.svg %s" % folder_path)
os.system("cp *.dat %s" % folder_path)
except OSError('Something went wrong while copying.'), e:
print 'Got:', e.args
else:
print 'Results were copied into %s' % folder_path
if __name__ == '__main__':
save_na_results()
| <commit_before>#!/usr/bin/python
import os
import sys
def save_na_results(folder_path=None):
"""Move the results of a Neighborhood Algorithm run to a folder with metadata.
This will copy all files with extensions of:
npy, txt, eps, png and dat
to the specified folder_path.
For now there is nothing stored in the folder that will be taken in by this
but we should be careful not to introduce anything that will be copied, or
at least modify this script accordingly if we do.
"""
if sys.platform is 'win32':
raise NotImplementedError('Will not currently work on Windows.')
if folder_path is None:
folder_path = sys.argv[1]
if not os.path.exists(folder_path):
os.makedirs(folder_path)
else:
raise Exception('Directory already exists; %s' % folder_path)
try:
os.system("cp *.npy %s" % folder_path)
os.system("cp *.txt %s" % folder_path)
os.system("cp *.png %s" % folder_path)
os.system("cp *.dat %s" % folder_path)
except OSError('Something went wrong while copying.'), e:
print 'Got:', e.args
else:
print 'Results were copied into %s' % folder_path
if __name__ == '__main__':
save_na_results()
<commit_msg>Save svg files, eps are not used anymore because they don't hand transparency.<commit_after> | #!/usr/bin/python
import os
import sys
def save_na_results(folder_path=None):
"""Move the results of a Neighborhood Algorithm run to a folder with metadata.
This will copy all files with extensions of:
npy, txt, eps, png and dat
to the specified folder_path.
For now there is nothing stored in the folder that will be taken in by this
but we should be careful not to introduce anything that will be copied, or
at least modify this script accordingly if we do.
"""
if sys.platform is 'win32':
raise NotImplementedError('Will not currently work on Windows.')
if folder_path is None:
folder_path = sys.argv[1]
if not os.path.exists(folder_path):
os.makedirs(folder_path)
else:
raise Exception('Directory already exists; %s' % folder_path)
try:
os.system("cp *.npy %s" % folder_path)
os.system("cp *.txt %s" % folder_path)
os.system("cp *.png %s" % folder_path)
os.system("cp *.svg %s" % folder_path)
os.system("cp *.dat %s" % folder_path)
except OSError('Something went wrong while copying.'), e:
print 'Got:', e.args
else:
print 'Results were copied into %s' % folder_path
if __name__ == '__main__':
save_na_results()
| #!/usr/bin/python
import os
import sys
def save_na_results(folder_path=None):
"""Move the results of a Neighborhood Algorithm run to a folder with metadata.
This will copy all files with extensions of:
npy, txt, eps, png and dat
to the specified folder_path.
For now there is nothing stored in the folder that will be taken in by this
but we should be careful not to introduce anything that will be copied, or
at least modify this script accordingly if we do.
"""
if sys.platform is 'win32':
raise NotImplementedError('Will not currently work on Windows.')
if folder_path is None:
folder_path = sys.argv[1]
if not os.path.exists(folder_path):
os.makedirs(folder_path)
else:
raise Exception('Directory already exists; %s' % folder_path)
try:
os.system("cp *.npy %s" % folder_path)
os.system("cp *.txt %s" % folder_path)
os.system("cp *.png %s" % folder_path)
os.system("cp *.dat %s" % folder_path)
except OSError('Something went wrong while copying.'), e:
print 'Got:', e.args
else:
print 'Results were copied into %s' % folder_path
if __name__ == '__main__':
save_na_results()
Save svg files, eps are not used anymore because they don't hand transparency.#!/usr/bin/python
import os
import sys
def save_na_results(folder_path=None):
"""Move the results of a Neighborhood Algorithm run to a folder with metadata.
This will copy all files with extensions of:
npy, txt, eps, png and dat
to the specified folder_path.
For now there is nothing stored in the folder that will be taken in by this
but we should be careful not to introduce anything that will be copied, or
at least modify this script accordingly if we do.
"""
if sys.platform is 'win32':
raise NotImplementedError('Will not currently work on Windows.')
if folder_path is None:
folder_path = sys.argv[1]
if not os.path.exists(folder_path):
os.makedirs(folder_path)
else:
raise Exception('Directory already exists; %s' % folder_path)
try:
os.system("cp *.npy %s" % folder_path)
os.system("cp *.txt %s" % folder_path)
os.system("cp *.png %s" % folder_path)
os.system("cp *.svg %s" % folder_path)
os.system("cp *.dat %s" % folder_path)
except OSError('Something went wrong while copying.'), e:
print 'Got:', e.args
else:
print 'Results were copied into %s' % folder_path
if __name__ == '__main__':
save_na_results()
| <commit_before>#!/usr/bin/python
import os
import sys
def save_na_results(folder_path=None):
"""Move the results of a Neighborhood Algorithm run to a folder with metadata.
This will copy all files with extensions of:
npy, txt, eps, png and dat
to the specified folder_path.
For now there is nothing stored in the folder that will be taken in by this
but we should be careful not to introduce anything that will be copied, or
at least modify this script accordingly if we do.
"""
if sys.platform is 'win32':
raise NotImplementedError('Will not currently work on Windows.')
if folder_path is None:
folder_path = sys.argv[1]
if not os.path.exists(folder_path):
os.makedirs(folder_path)
else:
raise Exception('Directory already exists; %s' % folder_path)
try:
os.system("cp *.npy %s" % folder_path)
os.system("cp *.txt %s" % folder_path)
os.system("cp *.png %s" % folder_path)
os.system("cp *.dat %s" % folder_path)
except OSError('Something went wrong while copying.'), e:
print 'Got:', e.args
else:
print 'Results were copied into %s' % folder_path
if __name__ == '__main__':
save_na_results()
<commit_msg>Save svg files, eps are not used anymore because they don't hand transparency.<commit_after>#!/usr/bin/python
import os
import sys
def save_na_results(folder_path=None):
"""Move the results of a Neighborhood Algorithm run to a folder with metadata.
This will copy all files with extensions of:
npy, txt, eps, png and dat
to the specified folder_path.
For now there is nothing stored in the folder that will be taken in by this
but we should be careful not to introduce anything that will be copied, or
at least modify this script accordingly if we do.
"""
if sys.platform is 'win32':
raise NotImplementedError('Will not currently work on Windows.')
if folder_path is None:
folder_path = sys.argv[1]
if not os.path.exists(folder_path):
os.makedirs(folder_path)
else:
raise Exception('Directory already exists; %s' % folder_path)
try:
os.system("cp *.npy %s" % folder_path)
os.system("cp *.txt %s" % folder_path)
os.system("cp *.png %s" % folder_path)
os.system("cp *.svg %s" % folder_path)
os.system("cp *.dat %s" % folder_path)
except OSError('Something went wrong while copying.'), e:
print 'Got:', e.args
else:
print 'Results were copied into %s' % folder_path
if __name__ == '__main__':
save_na_results()
|
a391b9d990c01cdf036bc92dd6bafc03bdd69b63 | instructions.py | instructions.py | class Instruction:
def __init__(self,prev):
self.prev = prev
if prev:
self.prev.next = self
self.partner = None
self.next = None
def execute(self, node):
return (self.next, node)
class LBracket(Instruction):
symbol = "["
def execute(self, node):
return (self.next, node)
class RBracket(Instruction):
symbol = "]"
def execute(self, node):
return (self.next, node) if node.value == 0 else (self.partner, node)
class Plus(Instruction):
symbol = "+"
def execute(self, node):
node.value += 1
return (self.next, node)
class Minus(Instruction):
symbol = "-"
def execute(self, node):
node.value -= 1
return (self.next, node)
class LShift(Instruction):
symbol = "<"
def execute(self, node):
return (self.next, node.prev())
class RShift(Instruction):
symbol = ">"
def execute(self, node):
return (self.next, node.next())
class Dot(Instruction):
symbol = "."
def execute(self, node):
print chr(node.value)
return (self.next, node)
instruction_types = [LBracket, RBracket, Plus, Minus, LShift, RShift, Dot]
instruction_regex = r'[^\+\-\[\]\<\>\.]'
| import sys
class Instruction:
def __init__(self,prev):
self.prev = prev
if prev:
self.prev.next = self
self.partner = None
self.next = None
def execute(self, node):
return (self.next, node)
class LBracket(Instruction):
symbol = "["
def execute(self, node):
return (self.next, node)
class RBracket(Instruction):
symbol = "]"
def execute(self, node):
return (self.next, node) if node.value == 0 else (self.partner, node)
class Plus(Instruction):
symbol = "+"
def execute(self, node):
node.value += 1
return (self.next, node)
class Minus(Instruction):
symbol = "-"
def execute(self, node):
node.value -= 1
return (self.next, node)
class LShift(Instruction):
symbol = "<"
def execute(self, node):
return (self.next, node.prev())
class RShift(Instruction):
symbol = ">"
def execute(self, node):
return (self.next, node.next())
class Dot(Instruction):
symbol = "."
def execute(self, node):
sys.stdout.write(chr(node.value))
return (self.next, node)
instruction_types = [LBracket, RBracket, Plus, Minus, LShift, RShift, Dot]
instruction_regex = r'[^\+\-\[\]\<\>\.]'
| Write directly to standard out instead of 'print' | Write directly to standard out instead of 'print'
| Python | mit | Detry322/brainfuck-interpreter | class Instruction:
def __init__(self,prev):
self.prev = prev
if prev:
self.prev.next = self
self.partner = None
self.next = None
def execute(self, node):
return (self.next, node)
class LBracket(Instruction):
symbol = "["
def execute(self, node):
return (self.next, node)
class RBracket(Instruction):
symbol = "]"
def execute(self, node):
return (self.next, node) if node.value == 0 else (self.partner, node)
class Plus(Instruction):
symbol = "+"
def execute(self, node):
node.value += 1
return (self.next, node)
class Minus(Instruction):
symbol = "-"
def execute(self, node):
node.value -= 1
return (self.next, node)
class LShift(Instruction):
symbol = "<"
def execute(self, node):
return (self.next, node.prev())
class RShift(Instruction):
symbol = ">"
def execute(self, node):
return (self.next, node.next())
class Dot(Instruction):
symbol = "."
def execute(self, node):
print chr(node.value)
return (self.next, node)
instruction_types = [LBracket, RBracket, Plus, Minus, LShift, RShift, Dot]
instruction_regex = r'[^\+\-\[\]\<\>\.]'
Write directly to standard out instead of 'print' | import sys
class Instruction:
def __init__(self,prev):
self.prev = prev
if prev:
self.prev.next = self
self.partner = None
self.next = None
def execute(self, node):
return (self.next, node)
class LBracket(Instruction):
symbol = "["
def execute(self, node):
return (self.next, node)
class RBracket(Instruction):
symbol = "]"
def execute(self, node):
return (self.next, node) if node.value == 0 else (self.partner, node)
class Plus(Instruction):
symbol = "+"
def execute(self, node):
node.value += 1
return (self.next, node)
class Minus(Instruction):
symbol = "-"
def execute(self, node):
node.value -= 1
return (self.next, node)
class LShift(Instruction):
symbol = "<"
def execute(self, node):
return (self.next, node.prev())
class RShift(Instruction):
symbol = ">"
def execute(self, node):
return (self.next, node.next())
class Dot(Instruction):
symbol = "."
def execute(self, node):
sys.stdout.write(chr(node.value))
return (self.next, node)
instruction_types = [LBracket, RBracket, Plus, Minus, LShift, RShift, Dot]
instruction_regex = r'[^\+\-\[\]\<\>\.]'
| <commit_before>class Instruction:
def __init__(self,prev):
self.prev = prev
if prev:
self.prev.next = self
self.partner = None
self.next = None
def execute(self, node):
return (self.next, node)
class LBracket(Instruction):
symbol = "["
def execute(self, node):
return (self.next, node)
class RBracket(Instruction):
symbol = "]"
def execute(self, node):
return (self.next, node) if node.value == 0 else (self.partner, node)
class Plus(Instruction):
symbol = "+"
def execute(self, node):
node.value += 1
return (self.next, node)
class Minus(Instruction):
symbol = "-"
def execute(self, node):
node.value -= 1
return (self.next, node)
class LShift(Instruction):
symbol = "<"
def execute(self, node):
return (self.next, node.prev())
class RShift(Instruction):
symbol = ">"
def execute(self, node):
return (self.next, node.next())
class Dot(Instruction):
symbol = "."
def execute(self, node):
print chr(node.value)
return (self.next, node)
instruction_types = [LBracket, RBracket, Plus, Minus, LShift, RShift, Dot]
instruction_regex = r'[^\+\-\[\]\<\>\.]'
<commit_msg>Write directly to standard out instead of 'print'<commit_after> | import sys
class Instruction:
def __init__(self,prev):
self.prev = prev
if prev:
self.prev.next = self
self.partner = None
self.next = None
def execute(self, node):
return (self.next, node)
class LBracket(Instruction):
symbol = "["
def execute(self, node):
return (self.next, node)
class RBracket(Instruction):
symbol = "]"
def execute(self, node):
return (self.next, node) if node.value == 0 else (self.partner, node)
class Plus(Instruction):
symbol = "+"
def execute(self, node):
node.value += 1
return (self.next, node)
class Minus(Instruction):
symbol = "-"
def execute(self, node):
node.value -= 1
return (self.next, node)
class LShift(Instruction):
symbol = "<"
def execute(self, node):
return (self.next, node.prev())
class RShift(Instruction):
symbol = ">"
def execute(self, node):
return (self.next, node.next())
class Dot(Instruction):
symbol = "."
def execute(self, node):
sys.stdout.write(chr(node.value))
return (self.next, node)
instruction_types = [LBracket, RBracket, Plus, Minus, LShift, RShift, Dot]
instruction_regex = r'[^\+\-\[\]\<\>\.]'
| class Instruction:
def __init__(self,prev):
self.prev = prev
if prev:
self.prev.next = self
self.partner = None
self.next = None
def execute(self, node):
return (self.next, node)
class LBracket(Instruction):
symbol = "["
def execute(self, node):
return (self.next, node)
class RBracket(Instruction):
symbol = "]"
def execute(self, node):
return (self.next, node) if node.value == 0 else (self.partner, node)
class Plus(Instruction):
symbol = "+"
def execute(self, node):
node.value += 1
return (self.next, node)
class Minus(Instruction):
symbol = "-"
def execute(self, node):
node.value -= 1
return (self.next, node)
class LShift(Instruction):
symbol = "<"
def execute(self, node):
return (self.next, node.prev())
class RShift(Instruction):
symbol = ">"
def execute(self, node):
return (self.next, node.next())
class Dot(Instruction):
symbol = "."
def execute(self, node):
print chr(node.value)
return (self.next, node)
instruction_types = [LBracket, RBracket, Plus, Minus, LShift, RShift, Dot]
instruction_regex = r'[^\+\-\[\]\<\>\.]'
Write directly to standard out instead of 'print'import sys
class Instruction:
def __init__(self,prev):
self.prev = prev
if prev:
self.prev.next = self
self.partner = None
self.next = None
def execute(self, node):
return (self.next, node)
class LBracket(Instruction):
symbol = "["
def execute(self, node):
return (self.next, node)
class RBracket(Instruction):
symbol = "]"
def execute(self, node):
return (self.next, node) if node.value == 0 else (self.partner, node)
class Plus(Instruction):
symbol = "+"
def execute(self, node):
node.value += 1
return (self.next, node)
class Minus(Instruction):
symbol = "-"
def execute(self, node):
node.value -= 1
return (self.next, node)
class LShift(Instruction):
symbol = "<"
def execute(self, node):
return (self.next, node.prev())
class RShift(Instruction):
symbol = ">"
def execute(self, node):
return (self.next, node.next())
class Dot(Instruction):
symbol = "."
def execute(self, node):
sys.stdout.write(chr(node.value))
return (self.next, node)
instruction_types = [LBracket, RBracket, Plus, Minus, LShift, RShift, Dot]
instruction_regex = r'[^\+\-\[\]\<\>\.]'
| <commit_before>class Instruction:
def __init__(self,prev):
self.prev = prev
if prev:
self.prev.next = self
self.partner = None
self.next = None
def execute(self, node):
return (self.next, node)
class LBracket(Instruction):
symbol = "["
def execute(self, node):
return (self.next, node)
class RBracket(Instruction):
symbol = "]"
def execute(self, node):
return (self.next, node) if node.value == 0 else (self.partner, node)
class Plus(Instruction):
symbol = "+"
def execute(self, node):
node.value += 1
return (self.next, node)
class Minus(Instruction):
symbol = "-"
def execute(self, node):
node.value -= 1
return (self.next, node)
class LShift(Instruction):
symbol = "<"
def execute(self, node):
return (self.next, node.prev())
class RShift(Instruction):
symbol = ">"
def execute(self, node):
return (self.next, node.next())
class Dot(Instruction):
symbol = "."
def execute(self, node):
print chr(node.value)
return (self.next, node)
instruction_types = [LBracket, RBracket, Plus, Minus, LShift, RShift, Dot]
instruction_regex = r'[^\+\-\[\]\<\>\.]'
<commit_msg>Write directly to standard out instead of 'print'<commit_after>import sys
class Instruction:
def __init__(self,prev):
self.prev = prev
if prev:
self.prev.next = self
self.partner = None
self.next = None
def execute(self, node):
return (self.next, node)
class LBracket(Instruction):
symbol = "["
def execute(self, node):
return (self.next, node)
class RBracket(Instruction):
symbol = "]"
def execute(self, node):
return (self.next, node) if node.value == 0 else (self.partner, node)
class Plus(Instruction):
symbol = "+"
def execute(self, node):
node.value += 1
return (self.next, node)
class Minus(Instruction):
symbol = "-"
def execute(self, node):
node.value -= 1
return (self.next, node)
class LShift(Instruction):
symbol = "<"
def execute(self, node):
return (self.next, node.prev())
class RShift(Instruction):
symbol = ">"
def execute(self, node):
return (self.next, node.next())
class Dot(Instruction):
symbol = "."
def execute(self, node):
sys.stdout.write(chr(node.value))
return (self.next, node)
instruction_types = [LBracket, RBracket, Plus, Minus, LShift, RShift, Dot]
instruction_regex = r'[^\+\-\[\]\<\>\.]'
|
5d63de144891c0672e67741ada93351f6aa8b20e | controllers/main.py | controllers/main.py | # -*- coding: utf-8 -*-
import openerp
from ..helpers.usbscale.scale import Scale
from ..helpers.usbscale.scale_manager import ScaleManager
from ..helpers.usbscale.tests import mocks
class ScaleController(openerp.addons.web.http.Controller):
_cp_path = '/scale_proxy'
def __init__(self, *args, **kwargs):
self.scale = Scale()
self.mock_manager = ScaleManager(
lookup=mocks.usb_ids.USB_IDS,
usb_lib=mocks.usb_lib.MockUSBLib()
)
self.mock_endpoint = mocks.usb_lib.MockEndpoint(0, 0)
super(ScaleController, self).__init__(*args, **kwargs)
@openerp.addons.web.http.jsonrequest
def weigh(self, request, max_attempts=10, test_weight=None):
'''Get a reading from the attached USB scale.'''
# Are we running an integration test...
if test_weight:
scale = Scale(device_manager=self.mock_manager)
scale.device.set_weight(test_weight)
weighing = scale.weigh(
endpoint=self.mock_endpoint, max_attempts=max_attempts
)
# ...or are we doing an actual weighing?
if not test_weight:
weighing = self.scale.weigh(max_attempts=max_attempts)
if weighing:
return {'success': True, 'weight': weighing.weight, 'unit': weighing.unit}
return {'success': False, 'error': "Could not read scale"} | # -*- coding: utf-8 -*-
import openerp
from ..helpers.usbscale.scale import Scale
from ..helpers.usbscale.scale_manager import ScaleManager
from ..helpers.usbscale.tests import mocks
class ScaleController(openerp.addons.web.http.Controller):
_cp_path = '/scale_proxy'
def __init__(self, *args, **kwargs):
self.scale = Scale()
self.mock_manager = ScaleManager(
lookup=mocks.usb_ids.USB_IDS,
usb_lib=mocks.usb_lib.MockUSBLib()
)
self.mock_endpoint = mocks.usb_lib.MockEndpoint(0, 0)
super(ScaleController, self).__init__(*args, **kwargs)
@openerp.addons.web.http.jsonrequest
def weigh(self, request, max_attempts=10, test_weight=None):
'''Get a reading from the attached USB scale.'''
# Are we running an integration test...
if test_weight:
scale = Scale(device_manager=self.mock_manager)
scale.device.set_weight(test_weight)
weighing = scale.weigh(
endpoint=self.mock_endpoint, max_attempts=float(max_attempts)
)
# ...or are we doing an actual weighing?
if not test_weight:
weighing = self.scale.weigh(max_attempts=float(max_attempts))
if weighing:
return {'success': True, 'weight': weighing.weight, 'unit': weighing.unit}
return {'success': False, 'error': "Could not read scale"} | Allow calls to 'weigh' to run forever when 'max_attempts' is set to 'inf'. | Allow calls to 'weigh' to run forever when 'max_attempts' is set to 'inf'.
| Python | agpl-3.0 | ryepdx/scale_proxy,ryepdx/scale_proxy | # -*- coding: utf-8 -*-
import openerp
from ..helpers.usbscale.scale import Scale
from ..helpers.usbscale.scale_manager import ScaleManager
from ..helpers.usbscale.tests import mocks
class ScaleController(openerp.addons.web.http.Controller):
_cp_path = '/scale_proxy'
def __init__(self, *args, **kwargs):
self.scale = Scale()
self.mock_manager = ScaleManager(
lookup=mocks.usb_ids.USB_IDS,
usb_lib=mocks.usb_lib.MockUSBLib()
)
self.mock_endpoint = mocks.usb_lib.MockEndpoint(0, 0)
super(ScaleController, self).__init__(*args, **kwargs)
@openerp.addons.web.http.jsonrequest
def weigh(self, request, max_attempts=10, test_weight=None):
'''Get a reading from the attached USB scale.'''
# Are we running an integration test...
if test_weight:
scale = Scale(device_manager=self.mock_manager)
scale.device.set_weight(test_weight)
weighing = scale.weigh(
endpoint=self.mock_endpoint, max_attempts=max_attempts
)
# ...or are we doing an actual weighing?
if not test_weight:
weighing = self.scale.weigh(max_attempts=max_attempts)
if weighing:
return {'success': True, 'weight': weighing.weight, 'unit': weighing.unit}
return {'success': False, 'error': "Could not read scale"}Allow calls to 'weigh' to run forever when 'max_attempts' is set to 'inf'. | # -*- coding: utf-8 -*-
import openerp
from ..helpers.usbscale.scale import Scale
from ..helpers.usbscale.scale_manager import ScaleManager
from ..helpers.usbscale.tests import mocks
class ScaleController(openerp.addons.web.http.Controller):
_cp_path = '/scale_proxy'
def __init__(self, *args, **kwargs):
self.scale = Scale()
self.mock_manager = ScaleManager(
lookup=mocks.usb_ids.USB_IDS,
usb_lib=mocks.usb_lib.MockUSBLib()
)
self.mock_endpoint = mocks.usb_lib.MockEndpoint(0, 0)
super(ScaleController, self).__init__(*args, **kwargs)
@openerp.addons.web.http.jsonrequest
def weigh(self, request, max_attempts=10, test_weight=None):
'''Get a reading from the attached USB scale.'''
# Are we running an integration test...
if test_weight:
scale = Scale(device_manager=self.mock_manager)
scale.device.set_weight(test_weight)
weighing = scale.weigh(
endpoint=self.mock_endpoint, max_attempts=float(max_attempts)
)
# ...or are we doing an actual weighing?
if not test_weight:
weighing = self.scale.weigh(max_attempts=float(max_attempts))
if weighing:
return {'success': True, 'weight': weighing.weight, 'unit': weighing.unit}
return {'success': False, 'error': "Could not read scale"} | <commit_before># -*- coding: utf-8 -*-
import openerp
from ..helpers.usbscale.scale import Scale
from ..helpers.usbscale.scale_manager import ScaleManager
from ..helpers.usbscale.tests import mocks
class ScaleController(openerp.addons.web.http.Controller):
_cp_path = '/scale_proxy'
def __init__(self, *args, **kwargs):
self.scale = Scale()
self.mock_manager = ScaleManager(
lookup=mocks.usb_ids.USB_IDS,
usb_lib=mocks.usb_lib.MockUSBLib()
)
self.mock_endpoint = mocks.usb_lib.MockEndpoint(0, 0)
super(ScaleController, self).__init__(*args, **kwargs)
@openerp.addons.web.http.jsonrequest
def weigh(self, request, max_attempts=10, test_weight=None):
'''Get a reading from the attached USB scale.'''
# Are we running an integration test...
if test_weight:
scale = Scale(device_manager=self.mock_manager)
scale.device.set_weight(test_weight)
weighing = scale.weigh(
endpoint=self.mock_endpoint, max_attempts=max_attempts
)
# ...or are we doing an actual weighing?
if not test_weight:
weighing = self.scale.weigh(max_attempts=max_attempts)
if weighing:
return {'success': True, 'weight': weighing.weight, 'unit': weighing.unit}
return {'success': False, 'error': "Could not read scale"}<commit_msg>Allow calls to 'weigh' to run forever when 'max_attempts' is set to 'inf'.<commit_after> | # -*- coding: utf-8 -*-
import openerp
from ..helpers.usbscale.scale import Scale
from ..helpers.usbscale.scale_manager import ScaleManager
from ..helpers.usbscale.tests import mocks
class ScaleController(openerp.addons.web.http.Controller):
_cp_path = '/scale_proxy'
def __init__(self, *args, **kwargs):
self.scale = Scale()
self.mock_manager = ScaleManager(
lookup=mocks.usb_ids.USB_IDS,
usb_lib=mocks.usb_lib.MockUSBLib()
)
self.mock_endpoint = mocks.usb_lib.MockEndpoint(0, 0)
super(ScaleController, self).__init__(*args, **kwargs)
@openerp.addons.web.http.jsonrequest
def weigh(self, request, max_attempts=10, test_weight=None):
'''Get a reading from the attached USB scale.'''
# Are we running an integration test...
if test_weight:
scale = Scale(device_manager=self.mock_manager)
scale.device.set_weight(test_weight)
weighing = scale.weigh(
endpoint=self.mock_endpoint, max_attempts=float(max_attempts)
)
# ...or are we doing an actual weighing?
if not test_weight:
weighing = self.scale.weigh(max_attempts=float(max_attempts))
if weighing:
return {'success': True, 'weight': weighing.weight, 'unit': weighing.unit}
return {'success': False, 'error': "Could not read scale"} | # -*- coding: utf-8 -*-
import openerp
from ..helpers.usbscale.scale import Scale
from ..helpers.usbscale.scale_manager import ScaleManager
from ..helpers.usbscale.tests import mocks
class ScaleController(openerp.addons.web.http.Controller):
_cp_path = '/scale_proxy'
def __init__(self, *args, **kwargs):
self.scale = Scale()
self.mock_manager = ScaleManager(
lookup=mocks.usb_ids.USB_IDS,
usb_lib=mocks.usb_lib.MockUSBLib()
)
self.mock_endpoint = mocks.usb_lib.MockEndpoint(0, 0)
super(ScaleController, self).__init__(*args, **kwargs)
@openerp.addons.web.http.jsonrequest
def weigh(self, request, max_attempts=10, test_weight=None):
'''Get a reading from the attached USB scale.'''
# Are we running an integration test...
if test_weight:
scale = Scale(device_manager=self.mock_manager)
scale.device.set_weight(test_weight)
weighing = scale.weigh(
endpoint=self.mock_endpoint, max_attempts=max_attempts
)
# ...or are we doing an actual weighing?
if not test_weight:
weighing = self.scale.weigh(max_attempts=max_attempts)
if weighing:
return {'success': True, 'weight': weighing.weight, 'unit': weighing.unit}
return {'success': False, 'error': "Could not read scale"}Allow calls to 'weigh' to run forever when 'max_attempts' is set to 'inf'.# -*- coding: utf-8 -*-
import openerp
from ..helpers.usbscale.scale import Scale
from ..helpers.usbscale.scale_manager import ScaleManager
from ..helpers.usbscale.tests import mocks
class ScaleController(openerp.addons.web.http.Controller):
_cp_path = '/scale_proxy'
def __init__(self, *args, **kwargs):
self.scale = Scale()
self.mock_manager = ScaleManager(
lookup=mocks.usb_ids.USB_IDS,
usb_lib=mocks.usb_lib.MockUSBLib()
)
self.mock_endpoint = mocks.usb_lib.MockEndpoint(0, 0)
super(ScaleController, self).__init__(*args, **kwargs)
@openerp.addons.web.http.jsonrequest
def weigh(self, request, max_attempts=10, test_weight=None):
'''Get a reading from the attached USB scale.'''
# Are we running an integration test...
if test_weight:
scale = Scale(device_manager=self.mock_manager)
scale.device.set_weight(test_weight)
weighing = scale.weigh(
endpoint=self.mock_endpoint, max_attempts=float(max_attempts)
)
# ...or are we doing an actual weighing?
if not test_weight:
weighing = self.scale.weigh(max_attempts=float(max_attempts))
if weighing:
return {'success': True, 'weight': weighing.weight, 'unit': weighing.unit}
return {'success': False, 'error': "Could not read scale"} | <commit_before># -*- coding: utf-8 -*-
import openerp
from ..helpers.usbscale.scale import Scale
from ..helpers.usbscale.scale_manager import ScaleManager
from ..helpers.usbscale.tests import mocks
class ScaleController(openerp.addons.web.http.Controller):
_cp_path = '/scale_proxy'
def __init__(self, *args, **kwargs):
self.scale = Scale()
self.mock_manager = ScaleManager(
lookup=mocks.usb_ids.USB_IDS,
usb_lib=mocks.usb_lib.MockUSBLib()
)
self.mock_endpoint = mocks.usb_lib.MockEndpoint(0, 0)
super(ScaleController, self).__init__(*args, **kwargs)
@openerp.addons.web.http.jsonrequest
def weigh(self, request, max_attempts=10, test_weight=None):
'''Get a reading from the attached USB scale.'''
# Are we running an integration test...
if test_weight:
scale = Scale(device_manager=self.mock_manager)
scale.device.set_weight(test_weight)
weighing = scale.weigh(
endpoint=self.mock_endpoint, max_attempts=max_attempts
)
# ...or are we doing an actual weighing?
if not test_weight:
weighing = self.scale.weigh(max_attempts=max_attempts)
if weighing:
return {'success': True, 'weight': weighing.weight, 'unit': weighing.unit}
return {'success': False, 'error': "Could not read scale"}<commit_msg>Allow calls to 'weigh' to run forever when 'max_attempts' is set to 'inf'.<commit_after># -*- coding: utf-8 -*-
import openerp
from ..helpers.usbscale.scale import Scale
from ..helpers.usbscale.scale_manager import ScaleManager
from ..helpers.usbscale.tests import mocks
class ScaleController(openerp.addons.web.http.Controller):
_cp_path = '/scale_proxy'
def __init__(self, *args, **kwargs):
self.scale = Scale()
self.mock_manager = ScaleManager(
lookup=mocks.usb_ids.USB_IDS,
usb_lib=mocks.usb_lib.MockUSBLib()
)
self.mock_endpoint = mocks.usb_lib.MockEndpoint(0, 0)
super(ScaleController, self).__init__(*args, **kwargs)
@openerp.addons.web.http.jsonrequest
def weigh(self, request, max_attempts=10, test_weight=None):
'''Get a reading from the attached USB scale.'''
# Are we running an integration test...
if test_weight:
scale = Scale(device_manager=self.mock_manager)
scale.device.set_weight(test_weight)
weighing = scale.weigh(
endpoint=self.mock_endpoint, max_attempts=float(max_attempts)
)
# ...or are we doing an actual weighing?
if not test_weight:
weighing = self.scale.weigh(max_attempts=float(max_attempts))
if weighing:
return {'success': True, 'weight': weighing.weight, 'unit': weighing.unit}
return {'success': False, 'error': "Could not read scale"} |
78eaa907ea986c12716b27fc6a4533d83242b97a | bci/__init__.py | bci/__init__.py | from fakebci import FakeBCI | import os
import sys
import platform
import shutil
import inspect
#
#def machine():
# """Return type of machine."""
# if os.name == 'nt' and sys.version_info[:2] < (2,7):
# return os.environ.get("PROCESSOR_ARCHITEW6432",
# os.environ.get('PROCESSOR_ARCHITECTURE', ''))
# else:
# return platform.machine()
#
#def arch(machine=machine()):
# """Return bitness of operating system, or None if unknown."""
# machine2bits = {'AMD64': 64, 'x86_64': 64, 'i386': 32, 'x86': 32}
# return machine2bits.get(machine, None)
#
#print (os_bits())
from fakebci import *
def create_so():
base_dir = os.path.dirname(inspect.getabsfile(FakeBCI))
boosted_bci = os.path.join(base_dir, 'boosted_bci.so')
if not os.path.exists(boosted_bci):
if sys.platform == 'darwin':
if platform.architecture()[0] == '64bit':
shutil.copyfile(os.path.join(base_dir, 'boosted_bci_darwin_x86_64.so'), boosted_bci)
else:
raise NotImplementedError("32 bit OS X is currently untested")
try:
from boosted_bci import greet
except:
print "Platform specific bci files have not been created"
| Make some changes to the bci package file. | Make some changes to the bci package file.
| Python | bsd-3-clause | NeuralProsthesisLab/unlock,NeuralProsthesisLab/unlock,NeuralProsthesisLab/unlock,NeuralProsthesisLab/unlock,NeuralProsthesisLab/unlock,NeuralProsthesisLab/unlock,NeuralProsthesisLab/unlock | from fakebci import FakeBCIMake some changes to the bci package file. | import os
import sys
import platform
import shutil
import inspect
#
#def machine():
# """Return type of machine."""
# if os.name == 'nt' and sys.version_info[:2] < (2,7):
# return os.environ.get("PROCESSOR_ARCHITEW6432",
# os.environ.get('PROCESSOR_ARCHITECTURE', ''))
# else:
# return platform.machine()
#
#def arch(machine=machine()):
# """Return bitness of operating system, or None if unknown."""
# machine2bits = {'AMD64': 64, 'x86_64': 64, 'i386': 32, 'x86': 32}
# return machine2bits.get(machine, None)
#
#print (os_bits())
from fakebci import *
def create_so():
base_dir = os.path.dirname(inspect.getabsfile(FakeBCI))
boosted_bci = os.path.join(base_dir, 'boosted_bci.so')
if not os.path.exists(boosted_bci):
if sys.platform == 'darwin':
if platform.architecture()[0] == '64bit':
shutil.copyfile(os.path.join(base_dir, 'boosted_bci_darwin_x86_64.so'), boosted_bci)
else:
raise NotImplementedError("32 bit OS X is currently untested")
try:
from boosted_bci import greet
except:
print "Platform specific bci files have not been created"
| <commit_before>from fakebci import FakeBCI<commit_msg>Make some changes to the bci package file.<commit_after> | import os
import sys
import platform
import shutil
import inspect
#
#def machine():
# """Return type of machine."""
# if os.name == 'nt' and sys.version_info[:2] < (2,7):
# return os.environ.get("PROCESSOR_ARCHITEW6432",
# os.environ.get('PROCESSOR_ARCHITECTURE', ''))
# else:
# return platform.machine()
#
#def arch(machine=machine()):
# """Return bitness of operating system, or None if unknown."""
# machine2bits = {'AMD64': 64, 'x86_64': 64, 'i386': 32, 'x86': 32}
# return machine2bits.get(machine, None)
#
#print (os_bits())
from fakebci import *
def create_so():
base_dir = os.path.dirname(inspect.getabsfile(FakeBCI))
boosted_bci = os.path.join(base_dir, 'boosted_bci.so')
if not os.path.exists(boosted_bci):
if sys.platform == 'darwin':
if platform.architecture()[0] == '64bit':
shutil.copyfile(os.path.join(base_dir, 'boosted_bci_darwin_x86_64.so'), boosted_bci)
else:
raise NotImplementedError("32 bit OS X is currently untested")
try:
from boosted_bci import greet
except:
print "Platform specific bci files have not been created"
| from fakebci import FakeBCIMake some changes to the bci package file.import os
import sys
import platform
import shutil
import inspect
#
#def machine():
# """Return type of machine."""
# if os.name == 'nt' and sys.version_info[:2] < (2,7):
# return os.environ.get("PROCESSOR_ARCHITEW6432",
# os.environ.get('PROCESSOR_ARCHITECTURE', ''))
# else:
# return platform.machine()
#
#def arch(machine=machine()):
# """Return bitness of operating system, or None if unknown."""
# machine2bits = {'AMD64': 64, 'x86_64': 64, 'i386': 32, 'x86': 32}
# return machine2bits.get(machine, None)
#
#print (os_bits())
from fakebci import *
def create_so():
base_dir = os.path.dirname(inspect.getabsfile(FakeBCI))
boosted_bci = os.path.join(base_dir, 'boosted_bci.so')
if not os.path.exists(boosted_bci):
if sys.platform == 'darwin':
if platform.architecture()[0] == '64bit':
shutil.copyfile(os.path.join(base_dir, 'boosted_bci_darwin_x86_64.so'), boosted_bci)
else:
raise NotImplementedError("32 bit OS X is currently untested")
try:
from boosted_bci import greet
except:
print "Platform specific bci files have not been created"
| <commit_before>from fakebci import FakeBCI<commit_msg>Make some changes to the bci package file.<commit_after>import os
import sys
import platform
import shutil
import inspect
#
#def machine():
# """Return type of machine."""
# if os.name == 'nt' and sys.version_info[:2] < (2,7):
# return os.environ.get("PROCESSOR_ARCHITEW6432",
# os.environ.get('PROCESSOR_ARCHITECTURE', ''))
# else:
# return platform.machine()
#
#def arch(machine=machine()):
# """Return bitness of operating system, or None if unknown."""
# machine2bits = {'AMD64': 64, 'x86_64': 64, 'i386': 32, 'x86': 32}
# return machine2bits.get(machine, None)
#
#print (os_bits())
from fakebci import *
def create_so():
base_dir = os.path.dirname(inspect.getabsfile(FakeBCI))
boosted_bci = os.path.join(base_dir, 'boosted_bci.so')
if not os.path.exists(boosted_bci):
if sys.platform == 'darwin':
if platform.architecture()[0] == '64bit':
shutil.copyfile(os.path.join(base_dir, 'boosted_bci_darwin_x86_64.so'), boosted_bci)
else:
raise NotImplementedError("32 bit OS X is currently untested")
try:
from boosted_bci import greet
except:
print "Platform specific bci files have not been created"
|
6c41a0529cac96e1057890a38456b396fcb0b7f2 | skcode/__init__.py | skcode/__init__.py | """
PySkCode, Python implementation of a full-featured BBCode syntax parser library.
"""
# Package information
__author__ = "Fabien Batteix (@skywodd)"
__copyright__ = "Copyright 2016, TamiaLab"
__credits__ = ["Fabien Batteix", "TamiaLab"]
__license__ = "GPLv3"
__version__ = "1.0.7"
__maintainer__ = "Fabien Batteix"
__email__ = "fabien.batteix@tamialab.fr"
__status__ = "Development" # "Production"
# User friendly imports
from .treebuilder import parse_skcode
from .render import (render_to_html,
render_to_skcode,
render_to_text)
| """
PySkCode, a Python implementation of a full-featured BBCode syntax parser library.
"""
# Package information
__author__ = "Fabien Batteix (@skywodd)"
__copyright__ = "Copyright 2016, TamiaLab"
__credits__ = ["Fabien Batteix", "TamiaLab"]
__license__ = "GPLv3"
__version__ = "2.0.0"
__maintainer__ = "Fabien Batteix"
__email__ = "fabien.batteix@tamialab.fr"
__status__ = "Development" # "Production"
# User friendly imports
from .treebuilder import parse_skcode
from .render import (render_to_html,
render_to_skcode,
render_to_text)
| Upgrade to 2.0.0 (big refactoring done, tests TODO) | Upgrade to 2.0.0 (big refactoring done, tests TODO)
| Python | agpl-3.0 | TamiaLab/PySkCode | """
PySkCode, Python implementation of a full-featured BBCode syntax parser library.
"""
# Package information
__author__ = "Fabien Batteix (@skywodd)"
__copyright__ = "Copyright 2016, TamiaLab"
__credits__ = ["Fabien Batteix", "TamiaLab"]
__license__ = "GPLv3"
__version__ = "1.0.7"
__maintainer__ = "Fabien Batteix"
__email__ = "fabien.batteix@tamialab.fr"
__status__ = "Development" # "Production"
# User friendly imports
from .treebuilder import parse_skcode
from .render import (render_to_html,
render_to_skcode,
render_to_text)
Upgrade to 2.0.0 (big refactoring done, tests TODO) | """
PySkCode, a Python implementation of a full-featured BBCode syntax parser library.
"""
# Package information
__author__ = "Fabien Batteix (@skywodd)"
__copyright__ = "Copyright 2016, TamiaLab"
__credits__ = ["Fabien Batteix", "TamiaLab"]
__license__ = "GPLv3"
__version__ = "2.0.0"
__maintainer__ = "Fabien Batteix"
__email__ = "fabien.batteix@tamialab.fr"
__status__ = "Development" # "Production"
# User friendly imports
from .treebuilder import parse_skcode
from .render import (render_to_html,
render_to_skcode,
render_to_text)
| <commit_before>"""
PySkCode, Python implementation of a full-featured BBCode syntax parser library.
"""
# Package information
__author__ = "Fabien Batteix (@skywodd)"
__copyright__ = "Copyright 2016, TamiaLab"
__credits__ = ["Fabien Batteix", "TamiaLab"]
__license__ = "GPLv3"
__version__ = "1.0.7"
__maintainer__ = "Fabien Batteix"
__email__ = "fabien.batteix@tamialab.fr"
__status__ = "Development" # "Production"
# User friendly imports
from .treebuilder import parse_skcode
from .render import (render_to_html,
render_to_skcode,
render_to_text)
<commit_msg>Upgrade to 2.0.0 (big refactoring done, tests TODO)<commit_after> | """
PySkCode, a Python implementation of a full-featured BBCode syntax parser library.
"""
# Package information
__author__ = "Fabien Batteix (@skywodd)"
__copyright__ = "Copyright 2016, TamiaLab"
__credits__ = ["Fabien Batteix", "TamiaLab"]
__license__ = "GPLv3"
__version__ = "2.0.0"
__maintainer__ = "Fabien Batteix"
__email__ = "fabien.batteix@tamialab.fr"
__status__ = "Development" # "Production"
# User friendly imports
from .treebuilder import parse_skcode
from .render import (render_to_html,
render_to_skcode,
render_to_text)
| """
PySkCode, Python implementation of a full-featured BBCode syntax parser library.
"""
# Package information
__author__ = "Fabien Batteix (@skywodd)"
__copyright__ = "Copyright 2016, TamiaLab"
__credits__ = ["Fabien Batteix", "TamiaLab"]
__license__ = "GPLv3"
__version__ = "1.0.7"
__maintainer__ = "Fabien Batteix"
__email__ = "fabien.batteix@tamialab.fr"
__status__ = "Development" # "Production"
# User friendly imports
from .treebuilder import parse_skcode
from .render import (render_to_html,
render_to_skcode,
render_to_text)
Upgrade to 2.0.0 (big refactoring done, tests TODO)"""
PySkCode, a Python implementation of a full-featured BBCode syntax parser library.
"""
# Package information
__author__ = "Fabien Batteix (@skywodd)"
__copyright__ = "Copyright 2016, TamiaLab"
__credits__ = ["Fabien Batteix", "TamiaLab"]
__license__ = "GPLv3"
__version__ = "2.0.0"
__maintainer__ = "Fabien Batteix"
__email__ = "fabien.batteix@tamialab.fr"
__status__ = "Development" # "Production"
# User friendly imports
from .treebuilder import parse_skcode
from .render import (render_to_html,
render_to_skcode,
render_to_text)
| <commit_before>"""
PySkCode, Python implementation of a full-featured BBCode syntax parser library.
"""
# Package information
__author__ = "Fabien Batteix (@skywodd)"
__copyright__ = "Copyright 2016, TamiaLab"
__credits__ = ["Fabien Batteix", "TamiaLab"]
__license__ = "GPLv3"
__version__ = "1.0.7"
__maintainer__ = "Fabien Batteix"
__email__ = "fabien.batteix@tamialab.fr"
__status__ = "Development" # "Production"
# User friendly imports
from .treebuilder import parse_skcode
from .render import (render_to_html,
render_to_skcode,
render_to_text)
<commit_msg>Upgrade to 2.0.0 (big refactoring done, tests TODO)<commit_after>"""
PySkCode, a Python implementation of a full-featured BBCode syntax parser library.
"""
# Package information
__author__ = "Fabien Batteix (@skywodd)"
__copyright__ = "Copyright 2016, TamiaLab"
__credits__ = ["Fabien Batteix", "TamiaLab"]
__license__ = "GPLv3"
__version__ = "2.0.0"
__maintainer__ = "Fabien Batteix"
__email__ = "fabien.batteix@tamialab.fr"
__status__ = "Development" # "Production"
# User friendly imports
from .treebuilder import parse_skcode
from .render import (render_to_html,
render_to_skcode,
render_to_text)
|
06959c1db979f401d852c37e4ea88a96c14ebcf7 | rnacentral/sequence_search/settings.py | rnacentral/sequence_search/settings.py | """
Copyright [2009-2019] EMBL-European Bioinformatics Institute
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.
"""
# SEQUENCE_SEARCH_ENDPOINT = 'http://193.62.55.45' # running remotely with a proxy
SEQUENCE_SEARCH_ENDPOINT = 'http://193.62.55.123:8002' # running remotely without a proxy
# SEQUENCE_SEARCH_ENDPOINT = 'http://193.62.55.44:8002' # running remotely without a proxy
# SEQUENCE_SEARCH_ENDPOINT = 'http://host.docker.internal:8002' # running locally
# SEQUENCE_SEARCH_ENDPOINT = 'https://search.rnacentral.org'
# minimum query sequence length
MIN_LENGTH = 10
# maximum query sequence length
MAX_LENGTH = 10000
| """
Copyright [2009-2019] EMBL-European Bioinformatics Institute
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.
"""
# SEQUENCE_SEARCH_ENDPOINT = 'http://193.62.55.45' # running remotely with a proxy
# SEQUENCE_SEARCH_ENDPOINT = 'http://193.62.55.123:8002' # running remotely without a proxy
# SEQUENCE_SEARCH_ENDPOINT = 'http://193.62.55.44:8002' # running remotely without a proxy
# SEQUENCE_SEARCH_ENDPOINT = 'http://host.docker.internal:8002' # running locally
SEQUENCE_SEARCH_ENDPOINT = 'https://search.rnacentral.org'
# minimum query sequence length
MIN_LENGTH = 10
# maximum query sequence length
MAX_LENGTH = 10000
| Use search.rnacentral.org as the sequence search endpoint | Use search.rnacentral.org as the sequence search endpoint | Python | apache-2.0 | RNAcentral/rnacentral-webcode,RNAcentral/rnacentral-webcode,RNAcentral/rnacentral-webcode,RNAcentral/rnacentral-webcode | """
Copyright [2009-2019] EMBL-European Bioinformatics Institute
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.
"""
# SEQUENCE_SEARCH_ENDPOINT = 'http://193.62.55.45' # running remotely with a proxy
SEQUENCE_SEARCH_ENDPOINT = 'http://193.62.55.123:8002' # running remotely without a proxy
# SEQUENCE_SEARCH_ENDPOINT = 'http://193.62.55.44:8002' # running remotely without a proxy
# SEQUENCE_SEARCH_ENDPOINT = 'http://host.docker.internal:8002' # running locally
# SEQUENCE_SEARCH_ENDPOINT = 'https://search.rnacentral.org'
# minimum query sequence length
MIN_LENGTH = 10
# maximum query sequence length
MAX_LENGTH = 10000
Use search.rnacentral.org as the sequence search endpoint | """
Copyright [2009-2019] EMBL-European Bioinformatics Institute
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.
"""
# SEQUENCE_SEARCH_ENDPOINT = 'http://193.62.55.45' # running remotely with a proxy
# SEQUENCE_SEARCH_ENDPOINT = 'http://193.62.55.123:8002' # running remotely without a proxy
# SEQUENCE_SEARCH_ENDPOINT = 'http://193.62.55.44:8002' # running remotely without a proxy
# SEQUENCE_SEARCH_ENDPOINT = 'http://host.docker.internal:8002' # running locally
SEQUENCE_SEARCH_ENDPOINT = 'https://search.rnacentral.org'
# minimum query sequence length
MIN_LENGTH = 10
# maximum query sequence length
MAX_LENGTH = 10000
| <commit_before>"""
Copyright [2009-2019] EMBL-European Bioinformatics Institute
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.
"""
# SEQUENCE_SEARCH_ENDPOINT = 'http://193.62.55.45' # running remotely with a proxy
SEQUENCE_SEARCH_ENDPOINT = 'http://193.62.55.123:8002' # running remotely without a proxy
# SEQUENCE_SEARCH_ENDPOINT = 'http://193.62.55.44:8002' # running remotely without a proxy
# SEQUENCE_SEARCH_ENDPOINT = 'http://host.docker.internal:8002' # running locally
# SEQUENCE_SEARCH_ENDPOINT = 'https://search.rnacentral.org'
# minimum query sequence length
MIN_LENGTH = 10
# maximum query sequence length
MAX_LENGTH = 10000
<commit_msg>Use search.rnacentral.org as the sequence search endpoint<commit_after> | """
Copyright [2009-2019] EMBL-European Bioinformatics Institute
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.
"""
# SEQUENCE_SEARCH_ENDPOINT = 'http://193.62.55.45' # running remotely with a proxy
# SEQUENCE_SEARCH_ENDPOINT = 'http://193.62.55.123:8002' # running remotely without a proxy
# SEQUENCE_SEARCH_ENDPOINT = 'http://193.62.55.44:8002' # running remotely without a proxy
# SEQUENCE_SEARCH_ENDPOINT = 'http://host.docker.internal:8002' # running locally
SEQUENCE_SEARCH_ENDPOINT = 'https://search.rnacentral.org'
# minimum query sequence length
MIN_LENGTH = 10
# maximum query sequence length
MAX_LENGTH = 10000
| """
Copyright [2009-2019] EMBL-European Bioinformatics Institute
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.
"""
# SEQUENCE_SEARCH_ENDPOINT = 'http://193.62.55.45' # running remotely with a proxy
SEQUENCE_SEARCH_ENDPOINT = 'http://193.62.55.123:8002' # running remotely without a proxy
# SEQUENCE_SEARCH_ENDPOINT = 'http://193.62.55.44:8002' # running remotely without a proxy
# SEQUENCE_SEARCH_ENDPOINT = 'http://host.docker.internal:8002' # running locally
# SEQUENCE_SEARCH_ENDPOINT = 'https://search.rnacentral.org'
# minimum query sequence length
MIN_LENGTH = 10
# maximum query sequence length
MAX_LENGTH = 10000
Use search.rnacentral.org as the sequence search endpoint"""
Copyright [2009-2019] EMBL-European Bioinformatics Institute
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.
"""
# SEQUENCE_SEARCH_ENDPOINT = 'http://193.62.55.45' # running remotely with a proxy
# SEQUENCE_SEARCH_ENDPOINT = 'http://193.62.55.123:8002' # running remotely without a proxy
# SEQUENCE_SEARCH_ENDPOINT = 'http://193.62.55.44:8002' # running remotely without a proxy
# SEQUENCE_SEARCH_ENDPOINT = 'http://host.docker.internal:8002' # running locally
SEQUENCE_SEARCH_ENDPOINT = 'https://search.rnacentral.org'
# minimum query sequence length
MIN_LENGTH = 10
# maximum query sequence length
MAX_LENGTH = 10000
| <commit_before>"""
Copyright [2009-2019] EMBL-European Bioinformatics Institute
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.
"""
# SEQUENCE_SEARCH_ENDPOINT = 'http://193.62.55.45' # running remotely with a proxy
SEQUENCE_SEARCH_ENDPOINT = 'http://193.62.55.123:8002' # running remotely without a proxy
# SEQUENCE_SEARCH_ENDPOINT = 'http://193.62.55.44:8002' # running remotely without a proxy
# SEQUENCE_SEARCH_ENDPOINT = 'http://host.docker.internal:8002' # running locally
# SEQUENCE_SEARCH_ENDPOINT = 'https://search.rnacentral.org'
# minimum query sequence length
MIN_LENGTH = 10
# maximum query sequence length
MAX_LENGTH = 10000
<commit_msg>Use search.rnacentral.org as the sequence search endpoint<commit_after>"""
Copyright [2009-2019] EMBL-European Bioinformatics Institute
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.
"""
# SEQUENCE_SEARCH_ENDPOINT = 'http://193.62.55.45' # running remotely with a proxy
# SEQUENCE_SEARCH_ENDPOINT = 'http://193.62.55.123:8002' # running remotely without a proxy
# SEQUENCE_SEARCH_ENDPOINT = 'http://193.62.55.44:8002' # running remotely without a proxy
# SEQUENCE_SEARCH_ENDPOINT = 'http://host.docker.internal:8002' # running locally
SEQUENCE_SEARCH_ENDPOINT = 'https://search.rnacentral.org'
# minimum query sequence length
MIN_LENGTH = 10
# maximum query sequence length
MAX_LENGTH = 10000
|
f2d8a622a492009eb3c44221dd322b1e12e62e6e | apps/groups/cron.py | apps/groups/cron.py | from django.db.models import Count
import commonware.log
import cronjobs
from groups.models import AUTO_COMPLETE_COUNT, Group
log = commonware.log.getLogger('m.cron')
@cronjobs.register
def assign_autocomplete_to_groups():
"""Hourly job to assign autocomplete status to popular Mozillian groups."""
# Only assign status to non-system groups.
# TODO: add stats.d timer here
for g in (Group.objects.filter(system=False)
.annotate(count=Count('userprofile'))):
g.auto_complete = True if g.count > AUTO_COMPLETE_COUNT else False
g.save()
| from django.db.models import Count
import commonware.log
import cronjobs
from groups.models import AUTO_COMPLETE_COUNT, Group
log = commonware.log.getLogger('m.cron')
@cronjobs.register
def assign_autocomplete_to_groups():
"""Hourly job to assign autocomplete status to popular Mozillian groups."""
# Only assign status to non-system groups.
# TODO: add stats.d timer here
for g in (Group.objects.filter(system=False)
.annotate(count=Count('userprofile'))):
g.auto_complete = g.count > AUTO_COMPLETE_COUNT
g.save()
| Fix @jsocol's nit; less verbose boolean assignment | Fix @jsocol's nit; less verbose boolean assignment
| Python | bsd-3-clause | akarki15/mozillians,mozilla/mozillians,justinpotts/mozillians,hoosteeno/mozillians,mozilla/mozillians,chirilo/mozillians,fxa90id/mozillians,akatsoulas/mozillians,johngian/mozillians,anistark/mozillians,safwanrahman/mozillians,glogiotatidis/mozillians-new,glogiotatidis/mozillians-new,anistark/mozillians,hoosteeno/mozillians,brian-yang/mozillians,safwanrahman/mozillians,johngian/mozillians,johngian/mozillians,fxa90id/mozillians,brian-yang/mozillians,satdav/mozillians,mozilla/mozillians,anistark/mozillians,akarki15/mozillians,justinpotts/mozillians,satdav/mozillians,justinpotts/mozillians,brian-yang/mozillians,glogiotatidis/mozillians-new,johngian/mozillians,justinpotts/mozillians,fxa90id/mozillians,ChristineLaMuse/mozillians,hoosteeno/mozillians,brian-yang/mozillians,akarki15/mozillians,safwanrahman/mozillians,ChristineLaMuse/mozillians,akatsoulas/mozillians,akarki15/mozillians,chirilo/mozillians,akatsoulas/mozillians,glogiotatidis/mozillians-new,safwanrahman/mozillians,satdav/mozillians,satdav/mozillians,akatsoulas/mozillians,anistark/mozillians,hoosteeno/mozillians,chirilo/mozillians,chirilo/mozillians,fxa90id/mozillians,ChristineLaMuse/mozillians,mozilla/mozillians | from django.db.models import Count
import commonware.log
import cronjobs
from groups.models import AUTO_COMPLETE_COUNT, Group
log = commonware.log.getLogger('m.cron')
@cronjobs.register
def assign_autocomplete_to_groups():
"""Hourly job to assign autocomplete status to popular Mozillian groups."""
# Only assign status to non-system groups.
# TODO: add stats.d timer here
for g in (Group.objects.filter(system=False)
.annotate(count=Count('userprofile'))):
g.auto_complete = True if g.count > AUTO_COMPLETE_COUNT else False
g.save()
Fix @jsocol's nit; less verbose boolean assignment | from django.db.models import Count
import commonware.log
import cronjobs
from groups.models import AUTO_COMPLETE_COUNT, Group
log = commonware.log.getLogger('m.cron')
@cronjobs.register
def assign_autocomplete_to_groups():
"""Hourly job to assign autocomplete status to popular Mozillian groups."""
# Only assign status to non-system groups.
# TODO: add stats.d timer here
for g in (Group.objects.filter(system=False)
.annotate(count=Count('userprofile'))):
g.auto_complete = g.count > AUTO_COMPLETE_COUNT
g.save()
| <commit_before>from django.db.models import Count
import commonware.log
import cronjobs
from groups.models import AUTO_COMPLETE_COUNT, Group
log = commonware.log.getLogger('m.cron')
@cronjobs.register
def assign_autocomplete_to_groups():
"""Hourly job to assign autocomplete status to popular Mozillian groups."""
# Only assign status to non-system groups.
# TODO: add stats.d timer here
for g in (Group.objects.filter(system=False)
.annotate(count=Count('userprofile'))):
g.auto_complete = True if g.count > AUTO_COMPLETE_COUNT else False
g.save()
<commit_msg>Fix @jsocol's nit; less verbose boolean assignment<commit_after> | from django.db.models import Count
import commonware.log
import cronjobs
from groups.models import AUTO_COMPLETE_COUNT, Group
log = commonware.log.getLogger('m.cron')
@cronjobs.register
def assign_autocomplete_to_groups():
"""Hourly job to assign autocomplete status to popular Mozillian groups."""
# Only assign status to non-system groups.
# TODO: add stats.d timer here
for g in (Group.objects.filter(system=False)
.annotate(count=Count('userprofile'))):
g.auto_complete = g.count > AUTO_COMPLETE_COUNT
g.save()
| from django.db.models import Count
import commonware.log
import cronjobs
from groups.models import AUTO_COMPLETE_COUNT, Group
log = commonware.log.getLogger('m.cron')
@cronjobs.register
def assign_autocomplete_to_groups():
"""Hourly job to assign autocomplete status to popular Mozillian groups."""
# Only assign status to non-system groups.
# TODO: add stats.d timer here
for g in (Group.objects.filter(system=False)
.annotate(count=Count('userprofile'))):
g.auto_complete = True if g.count > AUTO_COMPLETE_COUNT else False
g.save()
Fix @jsocol's nit; less verbose boolean assignmentfrom django.db.models import Count
import commonware.log
import cronjobs
from groups.models import AUTO_COMPLETE_COUNT, Group
log = commonware.log.getLogger('m.cron')
@cronjobs.register
def assign_autocomplete_to_groups():
"""Hourly job to assign autocomplete status to popular Mozillian groups."""
# Only assign status to non-system groups.
# TODO: add stats.d timer here
for g in (Group.objects.filter(system=False)
.annotate(count=Count('userprofile'))):
g.auto_complete = g.count > AUTO_COMPLETE_COUNT
g.save()
| <commit_before>from django.db.models import Count
import commonware.log
import cronjobs
from groups.models import AUTO_COMPLETE_COUNT, Group
log = commonware.log.getLogger('m.cron')
@cronjobs.register
def assign_autocomplete_to_groups():
"""Hourly job to assign autocomplete status to popular Mozillian groups."""
# Only assign status to non-system groups.
# TODO: add stats.d timer here
for g in (Group.objects.filter(system=False)
.annotate(count=Count('userprofile'))):
g.auto_complete = True if g.count > AUTO_COMPLETE_COUNT else False
g.save()
<commit_msg>Fix @jsocol's nit; less verbose boolean assignment<commit_after>from django.db.models import Count
import commonware.log
import cronjobs
from groups.models import AUTO_COMPLETE_COUNT, Group
log = commonware.log.getLogger('m.cron')
@cronjobs.register
def assign_autocomplete_to_groups():
"""Hourly job to assign autocomplete status to popular Mozillian groups."""
# Only assign status to non-system groups.
# TODO: add stats.d timer here
for g in (Group.objects.filter(system=False)
.annotate(count=Count('userprofile'))):
g.auto_complete = g.count > AUTO_COMPLETE_COUNT
g.save()
|
0e7939b0027cbc203505c636bc732d860b81e78d | sort/merge_sort/python/merge_sort.py | sort/merge_sort/python/merge_sort.py | def merge(left, right):
"""Merge sort merging function."""
left_index, right_index = 0, 0
result = []
while left_index < len(left) and right_index < len(right):
if left[left_index] < right[right_index]:
result.append(left[left_index])
left_index += 1
else:
result.append(right[right_index])
right_index += 1
result += left[left_index:]
result += right[right_index:]
return result
def merge_sort(array):
"""Merge sort algorithm implementation."""
if len(array) <= 1: # base case
return array
# divide array in half and merge sort recursively
half = len(array) // 2
left = merge_sort(array[:half])
right = merge_sort(array[half:])
return merge(left, right)
| def merge(left, right):
"""Merge sort merging function."""
left_index, right_index = 0, 0
result = []
while left_index < len(left) and right_index < len(right):
if left[left_index] < right[right_index]:
result.append(left[left_index])
left_index += 1
else:
result.append(right[right_index])
right_index += 1
result += left[left_index:]
result += right[right_index:]
return result
def merge_sort(array):
"""Merge sort algorithm implementation."""
if len(array) <= 1: # base case
return array
# divide array in half and merge sort recursively
half = len(array) // 2
left = merge_sort(array[:half])
right = merge_sort(array[half:])
return merge(left, right)
def test():
list = [5, 7, 6, 2, 1, 7, 3]
sorted_list = merge_sort(list)
print 'Sorted: ', sorted_list
if __name__ == '__main__':
test() | Add test for merge sort | Add test for merge sort
| Python | cc0-1.0 | manikTharaka/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,EUNIX-TRIX/al-go-rithms,ZoranPandovski/al-go-rithms,arijitkar98/al-go-rithms,Cnidarias/al-go-rithms,EUNIX-TRIX/al-go-rithms,arijitkar98/al-go-rithms,manikTharaka/al-go-rithms,manikTharaka/al-go-rithms,Cnidarias/al-go-rithms,ZoranPandovski/al-go-rithms,arijitkar98/al-go-rithms,ZoranPandovski/al-go-rithms,EUNIX-TRIX/al-go-rithms,ZoranPandovski/al-go-rithms,EUNIX-TRIX/al-go-rithms,arijitkar98/al-go-rithms,Cnidarias/al-go-rithms,Deepak345/al-go-rithms,arijitkar98/al-go-rithms,EUNIX-TRIX/al-go-rithms,manikTharaka/al-go-rithms,EUNIX-TRIX/al-go-rithms,Cnidarias/al-go-rithms,manikTharaka/al-go-rithms,Deepak345/al-go-rithms,Deepak345/al-go-rithms,Deepak345/al-go-rithms,ZoranPandovski/al-go-rithms,EUNIX-TRIX/al-go-rithms,Cnidarias/al-go-rithms,Deepak345/al-go-rithms,Deepak345/al-go-rithms,EUNIX-TRIX/al-go-rithms,manikTharaka/al-go-rithms,ZoranPandovski/al-go-rithms,Cnidarias/al-go-rithms,Cnidarias/al-go-rithms,Deepak345/al-go-rithms,ZoranPandovski/al-go-rithms,arijitkar98/al-go-rithms,arijitkar98/al-go-rithms,Deepak345/al-go-rithms,Cnidarias/al-go-rithms,manikTharaka/al-go-rithms,manikTharaka/al-go-rithms,manikTharaka/al-go-rithms,manikTharaka/al-go-rithms,Deepak345/al-go-rithms,Deepak345/al-go-rithms,manikTharaka/al-go-rithms,manikTharaka/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,Deepak345/al-go-rithms,Cnidarias/al-go-rithms,EUNIX-TRIX/al-go-rithms,manikTharaka/al-go-rithms,ZoranPandovski/al-go-rithms,arijitkar98/al-go-rithms,ZoranPandovski/al-go-rithms,Cnidarias/al-go-rithms,Deepak345/al-go-rithms,arijitkar98/al-go-rithms,ZoranPandovski/al-go-rithms,Deepak345/al-go-rithms,Cnidarias/al-go-rithms,Cnidarias/al-go-rithms,manikTharaka/al-go-rithms,Cnidarias/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,EUNIX-TRIX/al-go-rithms,EUNIX-TRIX/al-go-rithms,Deepak345/al-go-rithms,manikTharaka/al-go-rithms,ZoranPandovski/al-go-rithms,Deepak345/al-go-rithms,manikTharaka/al-go-rithms,EUNIX-TRIX/al-go-rithms,Deepak345/al-go-rithms,Cnidarias/al-go-rithms,arijitkar98/al-go-rithms,Cnidarias/al-go-rithms,EUNIX-TRIX/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms | def merge(left, right):
"""Merge sort merging function."""
left_index, right_index = 0, 0
result = []
while left_index < len(left) and right_index < len(right):
if left[left_index] < right[right_index]:
result.append(left[left_index])
left_index += 1
else:
result.append(right[right_index])
right_index += 1
result += left[left_index:]
result += right[right_index:]
return result
def merge_sort(array):
"""Merge sort algorithm implementation."""
if len(array) <= 1: # base case
return array
# divide array in half and merge sort recursively
half = len(array) // 2
left = merge_sort(array[:half])
right = merge_sort(array[half:])
return merge(left, right)
Add test for merge sort | def merge(left, right):
"""Merge sort merging function."""
left_index, right_index = 0, 0
result = []
while left_index < len(left) and right_index < len(right):
if left[left_index] < right[right_index]:
result.append(left[left_index])
left_index += 1
else:
result.append(right[right_index])
right_index += 1
result += left[left_index:]
result += right[right_index:]
return result
def merge_sort(array):
"""Merge sort algorithm implementation."""
if len(array) <= 1: # base case
return array
# divide array in half and merge sort recursively
half = len(array) // 2
left = merge_sort(array[:half])
right = merge_sort(array[half:])
return merge(left, right)
def test():
list = [5, 7, 6, 2, 1, 7, 3]
sorted_list = merge_sort(list)
print 'Sorted: ', sorted_list
if __name__ == '__main__':
test() | <commit_before>def merge(left, right):
"""Merge sort merging function."""
left_index, right_index = 0, 0
result = []
while left_index < len(left) and right_index < len(right):
if left[left_index] < right[right_index]:
result.append(left[left_index])
left_index += 1
else:
result.append(right[right_index])
right_index += 1
result += left[left_index:]
result += right[right_index:]
return result
def merge_sort(array):
"""Merge sort algorithm implementation."""
if len(array) <= 1: # base case
return array
# divide array in half and merge sort recursively
half = len(array) // 2
left = merge_sort(array[:half])
right = merge_sort(array[half:])
return merge(left, right)
<commit_msg>Add test for merge sort<commit_after> | def merge(left, right):
"""Merge sort merging function."""
left_index, right_index = 0, 0
result = []
while left_index < len(left) and right_index < len(right):
if left[left_index] < right[right_index]:
result.append(left[left_index])
left_index += 1
else:
result.append(right[right_index])
right_index += 1
result += left[left_index:]
result += right[right_index:]
return result
def merge_sort(array):
"""Merge sort algorithm implementation."""
if len(array) <= 1: # base case
return array
# divide array in half and merge sort recursively
half = len(array) // 2
left = merge_sort(array[:half])
right = merge_sort(array[half:])
return merge(left, right)
def test():
list = [5, 7, 6, 2, 1, 7, 3]
sorted_list = merge_sort(list)
print 'Sorted: ', sorted_list
if __name__ == '__main__':
test() | def merge(left, right):
"""Merge sort merging function."""
left_index, right_index = 0, 0
result = []
while left_index < len(left) and right_index < len(right):
if left[left_index] < right[right_index]:
result.append(left[left_index])
left_index += 1
else:
result.append(right[right_index])
right_index += 1
result += left[left_index:]
result += right[right_index:]
return result
def merge_sort(array):
"""Merge sort algorithm implementation."""
if len(array) <= 1: # base case
return array
# divide array in half and merge sort recursively
half = len(array) // 2
left = merge_sort(array[:half])
right = merge_sort(array[half:])
return merge(left, right)
Add test for merge sortdef merge(left, right):
"""Merge sort merging function."""
left_index, right_index = 0, 0
result = []
while left_index < len(left) and right_index < len(right):
if left[left_index] < right[right_index]:
result.append(left[left_index])
left_index += 1
else:
result.append(right[right_index])
right_index += 1
result += left[left_index:]
result += right[right_index:]
return result
def merge_sort(array):
"""Merge sort algorithm implementation."""
if len(array) <= 1: # base case
return array
# divide array in half and merge sort recursively
half = len(array) // 2
left = merge_sort(array[:half])
right = merge_sort(array[half:])
return merge(left, right)
def test():
list = [5, 7, 6, 2, 1, 7, 3]
sorted_list = merge_sort(list)
print 'Sorted: ', sorted_list
if __name__ == '__main__':
test() | <commit_before>def merge(left, right):
"""Merge sort merging function."""
left_index, right_index = 0, 0
result = []
while left_index < len(left) and right_index < len(right):
if left[left_index] < right[right_index]:
result.append(left[left_index])
left_index += 1
else:
result.append(right[right_index])
right_index += 1
result += left[left_index:]
result += right[right_index:]
return result
def merge_sort(array):
"""Merge sort algorithm implementation."""
if len(array) <= 1: # base case
return array
# divide array in half and merge sort recursively
half = len(array) // 2
left = merge_sort(array[:half])
right = merge_sort(array[half:])
return merge(left, right)
<commit_msg>Add test for merge sort<commit_after>def merge(left, right):
"""Merge sort merging function."""
left_index, right_index = 0, 0
result = []
while left_index < len(left) and right_index < len(right):
if left[left_index] < right[right_index]:
result.append(left[left_index])
left_index += 1
else:
result.append(right[right_index])
right_index += 1
result += left[left_index:]
result += right[right_index:]
return result
def merge_sort(array):
"""Merge sort algorithm implementation."""
if len(array) <= 1: # base case
return array
# divide array in half and merge sort recursively
half = len(array) // 2
left = merge_sort(array[:half])
right = merge_sort(array[half:])
return merge(left, right)
def test():
list = [5, 7, 6, 2, 1, 7, 3]
sorted_list = merge_sort(list)
print 'Sorted: ', sorted_list
if __name__ == '__main__':
test() |
33aa691298ed5c306c3b32965b38c287e65e174a | tests/functional/driver/test_driver_del.py | tests/functional/driver/test_driver_del.py | import pytest
from tests.utils.targetdriver import TargetDriver, if_feature
from tests.utils.testdriver import TestDriver
def get_services():
return TargetDriver('rep1'), TestDriver('rep2')
@pytest.fixture(autouse=True)
def _(module_launcher_launch):
pass
@if_feature.del_file_from_onitu
def test_driver_del_from_onitu(module_launcher):
d_target, d_test = module_launcher.get_services('rep1', 'rep2')
module_launcher.create_file('default', 'del1')
module_launcher.delete_file('default', 'del1', d_test, d_target)
@if_feature.del_file_to_onitu
def test_driver_del_to_onitu(module_launcher):
d_target, d_test = module_launcher.get_services('rep1', 'rep2')
module_launcher.create_file('default', 'del2')
module_launcher.delete_file('default', 'del2', d_target, d_test)
| import pytest
from tests.utils.targetdriver import TargetDriver, if_feature
from tests.utils.testdriver import TestDriver
from tests.utils.loop import CounterLoop
def get_services():
return TargetDriver('rep1'), TestDriver('rep2')
@pytest.fixture(autouse=True)
def _(module_launcher_launch):
pass
@if_feature.del_file_from_onitu
def test_driver_del_from_onitu(module_launcher):
d_target, d_test = module_launcher.get_services('rep1', 'rep2')
module_launcher.create_file('default', 'del1')
module_launcher.delete_file('default', 'del1', d_test, d_target)
@if_feature.del_file_to_onitu
def test_driver_del_to_onitu(module_launcher):
d_target, d_test = module_launcher.get_services('rep1', 'rep2')
module_launcher.create_file('default', 'del2')
module_launcher.delete_file('default', 'del2', d_target, d_test)
@if_feature.detect_del_file_on_launch
def test_driver_detect_del_on_launch(module_launcher):
d_target, d_test = module_launcher.get_services('rep1', 'rep2')
module_launcher.create_file('default', 'del3')
module_launcher.quit()
d_target.unlink(d_target.path('default', 'del3'))
loop = CounterLoop(2)
module_launcher.on_file_deleted(
loop.check, driver=d_target, filename='del3', folder='default'
)
module_launcher.on_deletion_completed(
loop.check, driver=d_test, filename='del3'
)
module_launcher()
loop.run(timeout=5)
assert not d_test.exists(d_test.path('default', 'del3'))
| Add test for detection of deleted files on launch | Add test for detection of deleted files on launch
| Python | mit | onitu/onitu,onitu/onitu,onitu/onitu | import pytest
from tests.utils.targetdriver import TargetDriver, if_feature
from tests.utils.testdriver import TestDriver
def get_services():
return TargetDriver('rep1'), TestDriver('rep2')
@pytest.fixture(autouse=True)
def _(module_launcher_launch):
pass
@if_feature.del_file_from_onitu
def test_driver_del_from_onitu(module_launcher):
d_target, d_test = module_launcher.get_services('rep1', 'rep2')
module_launcher.create_file('default', 'del1')
module_launcher.delete_file('default', 'del1', d_test, d_target)
@if_feature.del_file_to_onitu
def test_driver_del_to_onitu(module_launcher):
d_target, d_test = module_launcher.get_services('rep1', 'rep2')
module_launcher.create_file('default', 'del2')
module_launcher.delete_file('default', 'del2', d_target, d_test)
Add test for detection of deleted files on launch | import pytest
from tests.utils.targetdriver import TargetDriver, if_feature
from tests.utils.testdriver import TestDriver
from tests.utils.loop import CounterLoop
def get_services():
return TargetDriver('rep1'), TestDriver('rep2')
@pytest.fixture(autouse=True)
def _(module_launcher_launch):
pass
@if_feature.del_file_from_onitu
def test_driver_del_from_onitu(module_launcher):
d_target, d_test = module_launcher.get_services('rep1', 'rep2')
module_launcher.create_file('default', 'del1')
module_launcher.delete_file('default', 'del1', d_test, d_target)
@if_feature.del_file_to_onitu
def test_driver_del_to_onitu(module_launcher):
d_target, d_test = module_launcher.get_services('rep1', 'rep2')
module_launcher.create_file('default', 'del2')
module_launcher.delete_file('default', 'del2', d_target, d_test)
@if_feature.detect_del_file_on_launch
def test_driver_detect_del_on_launch(module_launcher):
d_target, d_test = module_launcher.get_services('rep1', 'rep2')
module_launcher.create_file('default', 'del3')
module_launcher.quit()
d_target.unlink(d_target.path('default', 'del3'))
loop = CounterLoop(2)
module_launcher.on_file_deleted(
loop.check, driver=d_target, filename='del3', folder='default'
)
module_launcher.on_deletion_completed(
loop.check, driver=d_test, filename='del3'
)
module_launcher()
loop.run(timeout=5)
assert not d_test.exists(d_test.path('default', 'del3'))
| <commit_before>import pytest
from tests.utils.targetdriver import TargetDriver, if_feature
from tests.utils.testdriver import TestDriver
def get_services():
return TargetDriver('rep1'), TestDriver('rep2')
@pytest.fixture(autouse=True)
def _(module_launcher_launch):
pass
@if_feature.del_file_from_onitu
def test_driver_del_from_onitu(module_launcher):
d_target, d_test = module_launcher.get_services('rep1', 'rep2')
module_launcher.create_file('default', 'del1')
module_launcher.delete_file('default', 'del1', d_test, d_target)
@if_feature.del_file_to_onitu
def test_driver_del_to_onitu(module_launcher):
d_target, d_test = module_launcher.get_services('rep1', 'rep2')
module_launcher.create_file('default', 'del2')
module_launcher.delete_file('default', 'del2', d_target, d_test)
<commit_msg>Add test for detection of deleted files on launch<commit_after> | import pytest
from tests.utils.targetdriver import TargetDriver, if_feature
from tests.utils.testdriver import TestDriver
from tests.utils.loop import CounterLoop
def get_services():
return TargetDriver('rep1'), TestDriver('rep2')
@pytest.fixture(autouse=True)
def _(module_launcher_launch):
pass
@if_feature.del_file_from_onitu
def test_driver_del_from_onitu(module_launcher):
d_target, d_test = module_launcher.get_services('rep1', 'rep2')
module_launcher.create_file('default', 'del1')
module_launcher.delete_file('default', 'del1', d_test, d_target)
@if_feature.del_file_to_onitu
def test_driver_del_to_onitu(module_launcher):
d_target, d_test = module_launcher.get_services('rep1', 'rep2')
module_launcher.create_file('default', 'del2')
module_launcher.delete_file('default', 'del2', d_target, d_test)
@if_feature.detect_del_file_on_launch
def test_driver_detect_del_on_launch(module_launcher):
d_target, d_test = module_launcher.get_services('rep1', 'rep2')
module_launcher.create_file('default', 'del3')
module_launcher.quit()
d_target.unlink(d_target.path('default', 'del3'))
loop = CounterLoop(2)
module_launcher.on_file_deleted(
loop.check, driver=d_target, filename='del3', folder='default'
)
module_launcher.on_deletion_completed(
loop.check, driver=d_test, filename='del3'
)
module_launcher()
loop.run(timeout=5)
assert not d_test.exists(d_test.path('default', 'del3'))
| import pytest
from tests.utils.targetdriver import TargetDriver, if_feature
from tests.utils.testdriver import TestDriver
def get_services():
return TargetDriver('rep1'), TestDriver('rep2')
@pytest.fixture(autouse=True)
def _(module_launcher_launch):
pass
@if_feature.del_file_from_onitu
def test_driver_del_from_onitu(module_launcher):
d_target, d_test = module_launcher.get_services('rep1', 'rep2')
module_launcher.create_file('default', 'del1')
module_launcher.delete_file('default', 'del1', d_test, d_target)
@if_feature.del_file_to_onitu
def test_driver_del_to_onitu(module_launcher):
d_target, d_test = module_launcher.get_services('rep1', 'rep2')
module_launcher.create_file('default', 'del2')
module_launcher.delete_file('default', 'del2', d_target, d_test)
Add test for detection of deleted files on launchimport pytest
from tests.utils.targetdriver import TargetDriver, if_feature
from tests.utils.testdriver import TestDriver
from tests.utils.loop import CounterLoop
def get_services():
return TargetDriver('rep1'), TestDriver('rep2')
@pytest.fixture(autouse=True)
def _(module_launcher_launch):
pass
@if_feature.del_file_from_onitu
def test_driver_del_from_onitu(module_launcher):
d_target, d_test = module_launcher.get_services('rep1', 'rep2')
module_launcher.create_file('default', 'del1')
module_launcher.delete_file('default', 'del1', d_test, d_target)
@if_feature.del_file_to_onitu
def test_driver_del_to_onitu(module_launcher):
d_target, d_test = module_launcher.get_services('rep1', 'rep2')
module_launcher.create_file('default', 'del2')
module_launcher.delete_file('default', 'del2', d_target, d_test)
@if_feature.detect_del_file_on_launch
def test_driver_detect_del_on_launch(module_launcher):
d_target, d_test = module_launcher.get_services('rep1', 'rep2')
module_launcher.create_file('default', 'del3')
module_launcher.quit()
d_target.unlink(d_target.path('default', 'del3'))
loop = CounterLoop(2)
module_launcher.on_file_deleted(
loop.check, driver=d_target, filename='del3', folder='default'
)
module_launcher.on_deletion_completed(
loop.check, driver=d_test, filename='del3'
)
module_launcher()
loop.run(timeout=5)
assert not d_test.exists(d_test.path('default', 'del3'))
| <commit_before>import pytest
from tests.utils.targetdriver import TargetDriver, if_feature
from tests.utils.testdriver import TestDriver
def get_services():
return TargetDriver('rep1'), TestDriver('rep2')
@pytest.fixture(autouse=True)
def _(module_launcher_launch):
pass
@if_feature.del_file_from_onitu
def test_driver_del_from_onitu(module_launcher):
d_target, d_test = module_launcher.get_services('rep1', 'rep2')
module_launcher.create_file('default', 'del1')
module_launcher.delete_file('default', 'del1', d_test, d_target)
@if_feature.del_file_to_onitu
def test_driver_del_to_onitu(module_launcher):
d_target, d_test = module_launcher.get_services('rep1', 'rep2')
module_launcher.create_file('default', 'del2')
module_launcher.delete_file('default', 'del2', d_target, d_test)
<commit_msg>Add test for detection of deleted files on launch<commit_after>import pytest
from tests.utils.targetdriver import TargetDriver, if_feature
from tests.utils.testdriver import TestDriver
from tests.utils.loop import CounterLoop
def get_services():
return TargetDriver('rep1'), TestDriver('rep2')
@pytest.fixture(autouse=True)
def _(module_launcher_launch):
pass
@if_feature.del_file_from_onitu
def test_driver_del_from_onitu(module_launcher):
d_target, d_test = module_launcher.get_services('rep1', 'rep2')
module_launcher.create_file('default', 'del1')
module_launcher.delete_file('default', 'del1', d_test, d_target)
@if_feature.del_file_to_onitu
def test_driver_del_to_onitu(module_launcher):
d_target, d_test = module_launcher.get_services('rep1', 'rep2')
module_launcher.create_file('default', 'del2')
module_launcher.delete_file('default', 'del2', d_target, d_test)
@if_feature.detect_del_file_on_launch
def test_driver_detect_del_on_launch(module_launcher):
d_target, d_test = module_launcher.get_services('rep1', 'rep2')
module_launcher.create_file('default', 'del3')
module_launcher.quit()
d_target.unlink(d_target.path('default', 'del3'))
loop = CounterLoop(2)
module_launcher.on_file_deleted(
loop.check, driver=d_target, filename='del3', folder='default'
)
module_launcher.on_deletion_completed(
loop.check, driver=d_test, filename='del3'
)
module_launcher()
loop.run(timeout=5)
assert not d_test.exists(d_test.path('default', 'del3'))
|
f5ad5a7cf1d33fdf0c709c0fece5bc712df6ec50 | avocado/__init__.py | avocado/__init__.py | __version_info__ = {
'major': 2,
'minor': 0,
'micro': 25,
'releaselevel': 'beta',
'serial': 1
}
def get_version(short=False):
assert __version_info__['releaselevel'] in ('alpha', 'beta', 'final')
vers = ["%(major)i.%(minor)i" % __version_info__, ]
if __version_info__['micro']:
vers.append(".%(micro)i" % __version_info__)
if __version_info__['releaselevel'] != 'final' and not short:
vers.append('%s%i' % (__version_info__['releaselevel'][0], __version_info__['serial']))
return ''.join(vers)
__version__ = get_version()
| __version_info__ = {
'major': 2,
'minor': 1,
'micro': 0,
'releaselevel': 'beta',
'serial': 1
}
def get_version(short=False):
assert __version_info__['releaselevel'] in ('alpha', 'beta', 'final')
vers = ["%(major)i.%(minor)i" % __version_info__, ]
if __version_info__['micro']:
vers.append(".%(micro)i" % __version_info__)
if __version_info__['releaselevel'] != 'final' and not short:
vers.append('%s%i' % (__version_info__['releaselevel'][0], __version_info__['serial']))
return ''.join(vers)
__version__ = get_version()
| Update branch to version 2.1.0 beta | Update branch to version 2.1.0 beta
| Python | bsd-2-clause | murphyke/avocado,murphyke/avocado,murphyke/avocado,murphyke/avocado | __version_info__ = {
'major': 2,
'minor': 0,
'micro': 25,
'releaselevel': 'beta',
'serial': 1
}
def get_version(short=False):
assert __version_info__['releaselevel'] in ('alpha', 'beta', 'final')
vers = ["%(major)i.%(minor)i" % __version_info__, ]
if __version_info__['micro']:
vers.append(".%(micro)i" % __version_info__)
if __version_info__['releaselevel'] != 'final' and not short:
vers.append('%s%i' % (__version_info__['releaselevel'][0], __version_info__['serial']))
return ''.join(vers)
__version__ = get_version()
Update branch to version 2.1.0 beta | __version_info__ = {
'major': 2,
'minor': 1,
'micro': 0,
'releaselevel': 'beta',
'serial': 1
}
def get_version(short=False):
assert __version_info__['releaselevel'] in ('alpha', 'beta', 'final')
vers = ["%(major)i.%(minor)i" % __version_info__, ]
if __version_info__['micro']:
vers.append(".%(micro)i" % __version_info__)
if __version_info__['releaselevel'] != 'final' and not short:
vers.append('%s%i' % (__version_info__['releaselevel'][0], __version_info__['serial']))
return ''.join(vers)
__version__ = get_version()
| <commit_before>__version_info__ = {
'major': 2,
'minor': 0,
'micro': 25,
'releaselevel': 'beta',
'serial': 1
}
def get_version(short=False):
assert __version_info__['releaselevel'] in ('alpha', 'beta', 'final')
vers = ["%(major)i.%(minor)i" % __version_info__, ]
if __version_info__['micro']:
vers.append(".%(micro)i" % __version_info__)
if __version_info__['releaselevel'] != 'final' and not short:
vers.append('%s%i' % (__version_info__['releaselevel'][0], __version_info__['serial']))
return ''.join(vers)
__version__ = get_version()
<commit_msg>Update branch to version 2.1.0 beta<commit_after> | __version_info__ = {
'major': 2,
'minor': 1,
'micro': 0,
'releaselevel': 'beta',
'serial': 1
}
def get_version(short=False):
assert __version_info__['releaselevel'] in ('alpha', 'beta', 'final')
vers = ["%(major)i.%(minor)i" % __version_info__, ]
if __version_info__['micro']:
vers.append(".%(micro)i" % __version_info__)
if __version_info__['releaselevel'] != 'final' and not short:
vers.append('%s%i' % (__version_info__['releaselevel'][0], __version_info__['serial']))
return ''.join(vers)
__version__ = get_version()
| __version_info__ = {
'major': 2,
'minor': 0,
'micro': 25,
'releaselevel': 'beta',
'serial': 1
}
def get_version(short=False):
assert __version_info__['releaselevel'] in ('alpha', 'beta', 'final')
vers = ["%(major)i.%(minor)i" % __version_info__, ]
if __version_info__['micro']:
vers.append(".%(micro)i" % __version_info__)
if __version_info__['releaselevel'] != 'final' and not short:
vers.append('%s%i' % (__version_info__['releaselevel'][0], __version_info__['serial']))
return ''.join(vers)
__version__ = get_version()
Update branch to version 2.1.0 beta__version_info__ = {
'major': 2,
'minor': 1,
'micro': 0,
'releaselevel': 'beta',
'serial': 1
}
def get_version(short=False):
assert __version_info__['releaselevel'] in ('alpha', 'beta', 'final')
vers = ["%(major)i.%(minor)i" % __version_info__, ]
if __version_info__['micro']:
vers.append(".%(micro)i" % __version_info__)
if __version_info__['releaselevel'] != 'final' and not short:
vers.append('%s%i' % (__version_info__['releaselevel'][0], __version_info__['serial']))
return ''.join(vers)
__version__ = get_version()
| <commit_before>__version_info__ = {
'major': 2,
'minor': 0,
'micro': 25,
'releaselevel': 'beta',
'serial': 1
}
def get_version(short=False):
assert __version_info__['releaselevel'] in ('alpha', 'beta', 'final')
vers = ["%(major)i.%(minor)i" % __version_info__, ]
if __version_info__['micro']:
vers.append(".%(micro)i" % __version_info__)
if __version_info__['releaselevel'] != 'final' and not short:
vers.append('%s%i' % (__version_info__['releaselevel'][0], __version_info__['serial']))
return ''.join(vers)
__version__ = get_version()
<commit_msg>Update branch to version 2.1.0 beta<commit_after>__version_info__ = {
'major': 2,
'minor': 1,
'micro': 0,
'releaselevel': 'beta',
'serial': 1
}
def get_version(short=False):
assert __version_info__['releaselevel'] in ('alpha', 'beta', 'final')
vers = ["%(major)i.%(minor)i" % __version_info__, ]
if __version_info__['micro']:
vers.append(".%(micro)i" % __version_info__)
if __version_info__['releaselevel'] != 'final' and not short:
vers.append('%s%i' % (__version_info__['releaselevel'][0], __version_info__['serial']))
return ''.join(vers)
__version__ = get_version()
|
b1f173fdbfb60e26a3923c7b024bc3e65e5abf80 | selvbetjening/scheckin/now/urls.py | selvbetjening/scheckin/now/urls.py | from django.conf.urls import *
import views
urlpatterns = patterns('',
url(r'^(?P<event_id>[0-9]+)/$', views.checkin),
)
| from django.conf.urls import *
from django.conf import settings
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _
from selvbetjening.sadmin.base.nav import RemoteSPage
import views
urlpatterns = patterns('',
url(r'^(?P<event_id>[0-9]+)/$', views.checkin, name='now_checkin'),
)
if 'selvbetjening.sadmin.events' in settings.INSTALLED_APPS:
import selvbetjening.sadmin.base.sadmin
now_url = lambda context, stack: reverse('now_checkin', kwargs={'event_id': stack[-1].pk})
now_page = RemoteSPage(_(u'Now Check-in'), now_url)
selvbetjening.sadmin.base.sadmin.site.get('events').attendee_admin.sadmin_action_menu.register(now_page) | Add links to easy check-in in sadmin | Add links to easy check-in in sadmin
| Python | mit | animekita/selvbetjening,animekita/selvbetjening,animekita/selvbetjening,animekita/selvbetjening | from django.conf.urls import *
import views
urlpatterns = patterns('',
url(r'^(?P<event_id>[0-9]+)/$', views.checkin),
)
Add links to easy check-in in sadmin | from django.conf.urls import *
from django.conf import settings
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _
from selvbetjening.sadmin.base.nav import RemoteSPage
import views
urlpatterns = patterns('',
url(r'^(?P<event_id>[0-9]+)/$', views.checkin, name='now_checkin'),
)
if 'selvbetjening.sadmin.events' in settings.INSTALLED_APPS:
import selvbetjening.sadmin.base.sadmin
now_url = lambda context, stack: reverse('now_checkin', kwargs={'event_id': stack[-1].pk})
now_page = RemoteSPage(_(u'Now Check-in'), now_url)
selvbetjening.sadmin.base.sadmin.site.get('events').attendee_admin.sadmin_action_menu.register(now_page) | <commit_before>from django.conf.urls import *
import views
urlpatterns = patterns('',
url(r'^(?P<event_id>[0-9]+)/$', views.checkin),
)
<commit_msg>Add links to easy check-in in sadmin<commit_after> | from django.conf.urls import *
from django.conf import settings
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _
from selvbetjening.sadmin.base.nav import RemoteSPage
import views
urlpatterns = patterns('',
url(r'^(?P<event_id>[0-9]+)/$', views.checkin, name='now_checkin'),
)
if 'selvbetjening.sadmin.events' in settings.INSTALLED_APPS:
import selvbetjening.sadmin.base.sadmin
now_url = lambda context, stack: reverse('now_checkin', kwargs={'event_id': stack[-1].pk})
now_page = RemoteSPage(_(u'Now Check-in'), now_url)
selvbetjening.sadmin.base.sadmin.site.get('events').attendee_admin.sadmin_action_menu.register(now_page) | from django.conf.urls import *
import views
urlpatterns = patterns('',
url(r'^(?P<event_id>[0-9]+)/$', views.checkin),
)
Add links to easy check-in in sadminfrom django.conf.urls import *
from django.conf import settings
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _
from selvbetjening.sadmin.base.nav import RemoteSPage
import views
urlpatterns = patterns('',
url(r'^(?P<event_id>[0-9]+)/$', views.checkin, name='now_checkin'),
)
if 'selvbetjening.sadmin.events' in settings.INSTALLED_APPS:
import selvbetjening.sadmin.base.sadmin
now_url = lambda context, stack: reverse('now_checkin', kwargs={'event_id': stack[-1].pk})
now_page = RemoteSPage(_(u'Now Check-in'), now_url)
selvbetjening.sadmin.base.sadmin.site.get('events').attendee_admin.sadmin_action_menu.register(now_page) | <commit_before>from django.conf.urls import *
import views
urlpatterns = patterns('',
url(r'^(?P<event_id>[0-9]+)/$', views.checkin),
)
<commit_msg>Add links to easy check-in in sadmin<commit_after>from django.conf.urls import *
from django.conf import settings
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _
from selvbetjening.sadmin.base.nav import RemoteSPage
import views
urlpatterns = patterns('',
url(r'^(?P<event_id>[0-9]+)/$', views.checkin, name='now_checkin'),
)
if 'selvbetjening.sadmin.events' in settings.INSTALLED_APPS:
import selvbetjening.sadmin.base.sadmin
now_url = lambda context, stack: reverse('now_checkin', kwargs={'event_id': stack[-1].pk})
now_page = RemoteSPage(_(u'Now Check-in'), now_url)
selvbetjening.sadmin.base.sadmin.site.get('events').attendee_admin.sadmin_action_menu.register(now_page) |
8ae5079a2963a356a6073a245305fff98fcc7461 | dbaas/logical/tasks.py | dbaas/logical/tasks.py | from logical.models import Database
from dbaas.celery import app
from util.decorators import only_one
@app.task
@only_one(key="purgequarantinekey", timeout=20)
def purge_quarantine():
Database.purge_quarantine()
return
| from logical.models import Database
from system.models import Configuration
from datetime import date, timedelta
from dbaas.celery import app
from util.decorators import only_one
from util.providers import destroy_infra
from simple_audit.models import AuditRequest
from notification.models import TaskHistory
from account.models import AccountUser
import logging
LOG = logging.getLogger(__name__)
@app.task(bind=True)
@only_one(key="purgequarantinekey", timeout=1000)
def purge_quarantine(self,):
user = AccountUser.objects.get(username='admin')
AuditRequest.new_request("purge_quarantine", user, "localhost")
try:
task_history = TaskHistory.register(request=self.request, user=user)
LOG.info("id: %s | task: %s | kwargs: %s | args: %s" % (
self.request.id, self.request.task, self.request.kwargs, str(self.request.args)))
quarantine_time = Configuration.get_by_name_as_int(
'quarantine_retention_days')
quarantine_time_dt = date.today() - timedelta(days=quarantine_time)
databases = Database.objects.filter(
is_in_quarantine=True, quarantine_dt__lte=quarantine_time_dt)
for database in databases:
if database.plan.provider == database.plan.CLOUDSTACK:
databaseinfra = database.databaseinfra
destroy_infra(databaseinfra=databaseinfra, task=task_history)
else:
database.delete()
LOG.info("The database %s was deleted, because it was set to quarentine %d days ago" % (
database.name, quarantine_time))
task_history.update_status_for(TaskHistory.STATUS_SUCCESS, details='Databases destroyed successfully')
return
except Exception:
task_history.update_status_for(TaskHistory.STATUS_ERROR, details="Error")
return
finally:
AuditRequest.cleanup_request()
| Change purge quarantine to deal with cloudstack databases | Change purge quarantine to deal with cloudstack databases
| Python | bsd-3-clause | globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service | from logical.models import Database
from dbaas.celery import app
from util.decorators import only_one
@app.task
@only_one(key="purgequarantinekey", timeout=20)
def purge_quarantine():
Database.purge_quarantine()
return
Change purge quarantine to deal with cloudstack databases | from logical.models import Database
from system.models import Configuration
from datetime import date, timedelta
from dbaas.celery import app
from util.decorators import only_one
from util.providers import destroy_infra
from simple_audit.models import AuditRequest
from notification.models import TaskHistory
from account.models import AccountUser
import logging
LOG = logging.getLogger(__name__)
@app.task(bind=True)
@only_one(key="purgequarantinekey", timeout=1000)
def purge_quarantine(self,):
user = AccountUser.objects.get(username='admin')
AuditRequest.new_request("purge_quarantine", user, "localhost")
try:
task_history = TaskHistory.register(request=self.request, user=user)
LOG.info("id: %s | task: %s | kwargs: %s | args: %s" % (
self.request.id, self.request.task, self.request.kwargs, str(self.request.args)))
quarantine_time = Configuration.get_by_name_as_int(
'quarantine_retention_days')
quarantine_time_dt = date.today() - timedelta(days=quarantine_time)
databases = Database.objects.filter(
is_in_quarantine=True, quarantine_dt__lte=quarantine_time_dt)
for database in databases:
if database.plan.provider == database.plan.CLOUDSTACK:
databaseinfra = database.databaseinfra
destroy_infra(databaseinfra=databaseinfra, task=task_history)
else:
database.delete()
LOG.info("The database %s was deleted, because it was set to quarentine %d days ago" % (
database.name, quarantine_time))
task_history.update_status_for(TaskHistory.STATUS_SUCCESS, details='Databases destroyed successfully')
return
except Exception:
task_history.update_status_for(TaskHistory.STATUS_ERROR, details="Error")
return
finally:
AuditRequest.cleanup_request()
| <commit_before>from logical.models import Database
from dbaas.celery import app
from util.decorators import only_one
@app.task
@only_one(key="purgequarantinekey", timeout=20)
def purge_quarantine():
Database.purge_quarantine()
return
<commit_msg>Change purge quarantine to deal with cloudstack databases<commit_after> | from logical.models import Database
from system.models import Configuration
from datetime import date, timedelta
from dbaas.celery import app
from util.decorators import only_one
from util.providers import destroy_infra
from simple_audit.models import AuditRequest
from notification.models import TaskHistory
from account.models import AccountUser
import logging
LOG = logging.getLogger(__name__)
@app.task(bind=True)
@only_one(key="purgequarantinekey", timeout=1000)
def purge_quarantine(self,):
user = AccountUser.objects.get(username='admin')
AuditRequest.new_request("purge_quarantine", user, "localhost")
try:
task_history = TaskHistory.register(request=self.request, user=user)
LOG.info("id: %s | task: %s | kwargs: %s | args: %s" % (
self.request.id, self.request.task, self.request.kwargs, str(self.request.args)))
quarantine_time = Configuration.get_by_name_as_int(
'quarantine_retention_days')
quarantine_time_dt = date.today() - timedelta(days=quarantine_time)
databases = Database.objects.filter(
is_in_quarantine=True, quarantine_dt__lte=quarantine_time_dt)
for database in databases:
if database.plan.provider == database.plan.CLOUDSTACK:
databaseinfra = database.databaseinfra
destroy_infra(databaseinfra=databaseinfra, task=task_history)
else:
database.delete()
LOG.info("The database %s was deleted, because it was set to quarentine %d days ago" % (
database.name, quarantine_time))
task_history.update_status_for(TaskHistory.STATUS_SUCCESS, details='Databases destroyed successfully')
return
except Exception:
task_history.update_status_for(TaskHistory.STATUS_ERROR, details="Error")
return
finally:
AuditRequest.cleanup_request()
| from logical.models import Database
from dbaas.celery import app
from util.decorators import only_one
@app.task
@only_one(key="purgequarantinekey", timeout=20)
def purge_quarantine():
Database.purge_quarantine()
return
Change purge quarantine to deal with cloudstack databasesfrom logical.models import Database
from system.models import Configuration
from datetime import date, timedelta
from dbaas.celery import app
from util.decorators import only_one
from util.providers import destroy_infra
from simple_audit.models import AuditRequest
from notification.models import TaskHistory
from account.models import AccountUser
import logging
LOG = logging.getLogger(__name__)
@app.task(bind=True)
@only_one(key="purgequarantinekey", timeout=1000)
def purge_quarantine(self,):
user = AccountUser.objects.get(username='admin')
AuditRequest.new_request("purge_quarantine", user, "localhost")
try:
task_history = TaskHistory.register(request=self.request, user=user)
LOG.info("id: %s | task: %s | kwargs: %s | args: %s" % (
self.request.id, self.request.task, self.request.kwargs, str(self.request.args)))
quarantine_time = Configuration.get_by_name_as_int(
'quarantine_retention_days')
quarantine_time_dt = date.today() - timedelta(days=quarantine_time)
databases = Database.objects.filter(
is_in_quarantine=True, quarantine_dt__lte=quarantine_time_dt)
for database in databases:
if database.plan.provider == database.plan.CLOUDSTACK:
databaseinfra = database.databaseinfra
destroy_infra(databaseinfra=databaseinfra, task=task_history)
else:
database.delete()
LOG.info("The database %s was deleted, because it was set to quarentine %d days ago" % (
database.name, quarantine_time))
task_history.update_status_for(TaskHistory.STATUS_SUCCESS, details='Databases destroyed successfully')
return
except Exception:
task_history.update_status_for(TaskHistory.STATUS_ERROR, details="Error")
return
finally:
AuditRequest.cleanup_request()
| <commit_before>from logical.models import Database
from dbaas.celery import app
from util.decorators import only_one
@app.task
@only_one(key="purgequarantinekey", timeout=20)
def purge_quarantine():
Database.purge_quarantine()
return
<commit_msg>Change purge quarantine to deal with cloudstack databases<commit_after>from logical.models import Database
from system.models import Configuration
from datetime import date, timedelta
from dbaas.celery import app
from util.decorators import only_one
from util.providers import destroy_infra
from simple_audit.models import AuditRequest
from notification.models import TaskHistory
from account.models import AccountUser
import logging
LOG = logging.getLogger(__name__)
@app.task(bind=True)
@only_one(key="purgequarantinekey", timeout=1000)
def purge_quarantine(self,):
user = AccountUser.objects.get(username='admin')
AuditRequest.new_request("purge_quarantine", user, "localhost")
try:
task_history = TaskHistory.register(request=self.request, user=user)
LOG.info("id: %s | task: %s | kwargs: %s | args: %s" % (
self.request.id, self.request.task, self.request.kwargs, str(self.request.args)))
quarantine_time = Configuration.get_by_name_as_int(
'quarantine_retention_days')
quarantine_time_dt = date.today() - timedelta(days=quarantine_time)
databases = Database.objects.filter(
is_in_quarantine=True, quarantine_dt__lte=quarantine_time_dt)
for database in databases:
if database.plan.provider == database.plan.CLOUDSTACK:
databaseinfra = database.databaseinfra
destroy_infra(databaseinfra=databaseinfra, task=task_history)
else:
database.delete()
LOG.info("The database %s was deleted, because it was set to quarentine %d days ago" % (
database.name, quarantine_time))
task_history.update_status_for(TaskHistory.STATUS_SUCCESS, details='Databases destroyed successfully')
return
except Exception:
task_history.update_status_for(TaskHistory.STATUS_ERROR, details="Error")
return
finally:
AuditRequest.cleanup_request()
|
10f7b7db3b7912c74ca0320ac70da425bd2718ed | scripts/fabfile.py | scripts/fabfile.py | from fabric import task
CODE_DIR = '~/django-projects/test-osale/foodbank-campaign/src'
# for FreeBSD compatibility
SHELL = '/bin/sh -c'
@task
def deploy(c):
c.shell = SHELL
with c.cd(CODE_DIR):
pull_changes(c)
with c.prefix('. ../venv/bin/activate'):
update_dependencies(c)
migrate_database(c)
update_static_files(c)
restart_app(c)
def update_dependencies(c):
c.run('pip install --requirement=requirements.txt')
def pull_changes(c):
c.run('git fetch')
c.run('git reset --hard origin/master')
def migrate_database(c):
c.run('python manage.py migrate --noinput')
def update_static_files(c):
c.run('python manage.py collectstatic --noinput')
def restart_app(c):
c.run('../scripts/restart-fcgi.sh')
# for WSGI:
# c.run('touch toidupank/wsgi.py')
| from fabric import task
CODE_DIR = '~/django-projects/test-osale/foodbank-campaign/src'
# for FreeBSD compatibility
SHELL = '/bin/sh -c'
@task
def deploy(c):
c.shell = SHELL
with c.cd(CODE_DIR):
pull_changes(c)
with c.prefix('. ../venv/bin/activate'):
update_dependencies(c)
migrate_database(c)
update_static_files(c)
restart_app(c)
def update_dependencies(c):
c.run('pip install --requirement=requirements.txt --upgrade')
def pull_changes(c):
c.run('git fetch')
c.run('git reset --hard origin/master')
def migrate_database(c):
c.run('python manage.py migrate --noinput')
def update_static_files(c):
c.run('python manage.py collectstatic --noinput')
def restart_app(c):
c.run('../scripts/restart-fcgi.sh')
# for WSGI:
# c.run('touch toidupank/wsgi.py')
| Add --upgrade to pip install in Fabfile | Add --upgrade to pip install in Fabfile
| Python | mit | mrts/foodbank-campaign,mrts/foodbank-campaign,mrts/foodbank-campaign,mrts/foodbank-campaign | from fabric import task
CODE_DIR = '~/django-projects/test-osale/foodbank-campaign/src'
# for FreeBSD compatibility
SHELL = '/bin/sh -c'
@task
def deploy(c):
c.shell = SHELL
with c.cd(CODE_DIR):
pull_changes(c)
with c.prefix('. ../venv/bin/activate'):
update_dependencies(c)
migrate_database(c)
update_static_files(c)
restart_app(c)
def update_dependencies(c):
c.run('pip install --requirement=requirements.txt')
def pull_changes(c):
c.run('git fetch')
c.run('git reset --hard origin/master')
def migrate_database(c):
c.run('python manage.py migrate --noinput')
def update_static_files(c):
c.run('python manage.py collectstatic --noinput')
def restart_app(c):
c.run('../scripts/restart-fcgi.sh')
# for WSGI:
# c.run('touch toidupank/wsgi.py')
Add --upgrade to pip install in Fabfile | from fabric import task
CODE_DIR = '~/django-projects/test-osale/foodbank-campaign/src'
# for FreeBSD compatibility
SHELL = '/bin/sh -c'
@task
def deploy(c):
c.shell = SHELL
with c.cd(CODE_DIR):
pull_changes(c)
with c.prefix('. ../venv/bin/activate'):
update_dependencies(c)
migrate_database(c)
update_static_files(c)
restart_app(c)
def update_dependencies(c):
c.run('pip install --requirement=requirements.txt --upgrade')
def pull_changes(c):
c.run('git fetch')
c.run('git reset --hard origin/master')
def migrate_database(c):
c.run('python manage.py migrate --noinput')
def update_static_files(c):
c.run('python manage.py collectstatic --noinput')
def restart_app(c):
c.run('../scripts/restart-fcgi.sh')
# for WSGI:
# c.run('touch toidupank/wsgi.py')
| <commit_before>from fabric import task
CODE_DIR = '~/django-projects/test-osale/foodbank-campaign/src'
# for FreeBSD compatibility
SHELL = '/bin/sh -c'
@task
def deploy(c):
c.shell = SHELL
with c.cd(CODE_DIR):
pull_changes(c)
with c.prefix('. ../venv/bin/activate'):
update_dependencies(c)
migrate_database(c)
update_static_files(c)
restart_app(c)
def update_dependencies(c):
c.run('pip install --requirement=requirements.txt')
def pull_changes(c):
c.run('git fetch')
c.run('git reset --hard origin/master')
def migrate_database(c):
c.run('python manage.py migrate --noinput')
def update_static_files(c):
c.run('python manage.py collectstatic --noinput')
def restart_app(c):
c.run('../scripts/restart-fcgi.sh')
# for WSGI:
# c.run('touch toidupank/wsgi.py')
<commit_msg>Add --upgrade to pip install in Fabfile<commit_after> | from fabric import task
CODE_DIR = '~/django-projects/test-osale/foodbank-campaign/src'
# for FreeBSD compatibility
SHELL = '/bin/sh -c'
@task
def deploy(c):
c.shell = SHELL
with c.cd(CODE_DIR):
pull_changes(c)
with c.prefix('. ../venv/bin/activate'):
update_dependencies(c)
migrate_database(c)
update_static_files(c)
restart_app(c)
def update_dependencies(c):
c.run('pip install --requirement=requirements.txt --upgrade')
def pull_changes(c):
c.run('git fetch')
c.run('git reset --hard origin/master')
def migrate_database(c):
c.run('python manage.py migrate --noinput')
def update_static_files(c):
c.run('python manage.py collectstatic --noinput')
def restart_app(c):
c.run('../scripts/restart-fcgi.sh')
# for WSGI:
# c.run('touch toidupank/wsgi.py')
| from fabric import task
CODE_DIR = '~/django-projects/test-osale/foodbank-campaign/src'
# for FreeBSD compatibility
SHELL = '/bin/sh -c'
@task
def deploy(c):
c.shell = SHELL
with c.cd(CODE_DIR):
pull_changes(c)
with c.prefix('. ../venv/bin/activate'):
update_dependencies(c)
migrate_database(c)
update_static_files(c)
restart_app(c)
def update_dependencies(c):
c.run('pip install --requirement=requirements.txt')
def pull_changes(c):
c.run('git fetch')
c.run('git reset --hard origin/master')
def migrate_database(c):
c.run('python manage.py migrate --noinput')
def update_static_files(c):
c.run('python manage.py collectstatic --noinput')
def restart_app(c):
c.run('../scripts/restart-fcgi.sh')
# for WSGI:
# c.run('touch toidupank/wsgi.py')
Add --upgrade to pip install in Fabfilefrom fabric import task
CODE_DIR = '~/django-projects/test-osale/foodbank-campaign/src'
# for FreeBSD compatibility
SHELL = '/bin/sh -c'
@task
def deploy(c):
c.shell = SHELL
with c.cd(CODE_DIR):
pull_changes(c)
with c.prefix('. ../venv/bin/activate'):
update_dependencies(c)
migrate_database(c)
update_static_files(c)
restart_app(c)
def update_dependencies(c):
c.run('pip install --requirement=requirements.txt --upgrade')
def pull_changes(c):
c.run('git fetch')
c.run('git reset --hard origin/master')
def migrate_database(c):
c.run('python manage.py migrate --noinput')
def update_static_files(c):
c.run('python manage.py collectstatic --noinput')
def restart_app(c):
c.run('../scripts/restart-fcgi.sh')
# for WSGI:
# c.run('touch toidupank/wsgi.py')
| <commit_before>from fabric import task
CODE_DIR = '~/django-projects/test-osale/foodbank-campaign/src'
# for FreeBSD compatibility
SHELL = '/bin/sh -c'
@task
def deploy(c):
c.shell = SHELL
with c.cd(CODE_DIR):
pull_changes(c)
with c.prefix('. ../venv/bin/activate'):
update_dependencies(c)
migrate_database(c)
update_static_files(c)
restart_app(c)
def update_dependencies(c):
c.run('pip install --requirement=requirements.txt')
def pull_changes(c):
c.run('git fetch')
c.run('git reset --hard origin/master')
def migrate_database(c):
c.run('python manage.py migrate --noinput')
def update_static_files(c):
c.run('python manage.py collectstatic --noinput')
def restart_app(c):
c.run('../scripts/restart-fcgi.sh')
# for WSGI:
# c.run('touch toidupank/wsgi.py')
<commit_msg>Add --upgrade to pip install in Fabfile<commit_after>from fabric import task
CODE_DIR = '~/django-projects/test-osale/foodbank-campaign/src'
# for FreeBSD compatibility
SHELL = '/bin/sh -c'
@task
def deploy(c):
c.shell = SHELL
with c.cd(CODE_DIR):
pull_changes(c)
with c.prefix('. ../venv/bin/activate'):
update_dependencies(c)
migrate_database(c)
update_static_files(c)
restart_app(c)
def update_dependencies(c):
c.run('pip install --requirement=requirements.txt --upgrade')
def pull_changes(c):
c.run('git fetch')
c.run('git reset --hard origin/master')
def migrate_database(c):
c.run('python manage.py migrate --noinput')
def update_static_files(c):
c.run('python manage.py collectstatic --noinput')
def restart_app(c):
c.run('../scripts/restart-fcgi.sh')
# for WSGI:
# c.run('touch toidupank/wsgi.py')
|
d40ba3bcceb1dcc7338b689194cd7214d7b2d5ff | syncano_cli/execute/commands.py | syncano_cli/execute/commands.py | # -*- coding: utf-8 -*-
from __future__ import print_function
import json
import sys
from ConfigParser import NoOptionError
import click
from syncano_cli import LOG
from .connection import create_connection
@click.group()
def top_execute():
pass
@top_execute.command()
@click.option('--config', help=u'Account configuration file.')
@click.argument('instance_name', envvar='SYNCANO_INSTANCE')
@click.argument('script_endpoint_name')
@click.option('--payload', help=u'Script payload in JSON format.')
def execute(config, instance_name, script_endpoint_name, payload):
"""
Execute script endpoint in given instance
"""
try:
connection = create_connection(config)
except NoOptionError:
LOG.error('Do a login first: syncano login.')
sys.exit(1)
instance = connection.Instance.please.get(instance_name)
se = instance.script_endpoints.get(instance_name, script_endpoint_name)
data = json.loads(payload.strip() or '{}')
response = se.run(**data)
print(json.dumps(response.result, indent=4, sort_keys=True))
| # -*- coding: utf-8 -*-
from __future__ import print_function
import json
import sys
from ConfigParser import NoOptionError
import click
from syncano.exceptions import SyncanoDoesNotExist
from syncano_cli import LOG
from .connection import create_connection
@click.group()
def top_execute():
pass
@top_execute.command()
@click.option('--config', help=u'Account configuration file.')
@click.argument('instance_name', envvar='SYNCANO_INSTANCE')
@click.argument('script_endpoint_name')
@click.option('--payload', help=u'Script payload in JSON format.')
def execute(config, instance_name, script_endpoint_name, payload):
"""
Execute script endpoint in given instance
"""
try:
connection = create_connection(config)
instance = connection.Instance.please.get(instance_name)
se = instance.script_endpoints.get(instance_name, script_endpoint_name)
data = json.loads((payload or '').strip() or '{}')
response = se.run(**data)
if response.status == 'success':
print(json.dumps(response.result['stdout'], indent=4, sort_keys=True))
else:
LOG.error(response.result['stderr'])
except NoOptionError:
LOG.error('Do a login first: syncano login.')
sys.exit(1)
except SyncanoDoesNotExist as e:
LOG.error(e)
sys.exit(1)
except ValueError as e:
LOG.error('Invalid payload format: {error}'.format(error=e))
sys.exit(1)
| Refactor the code: add error handling of invalid or empty parameters, improve output format. | Refactor the code: add error handling of invalid or empty parameters, improve output format.
| Python | mit | Syncano/syncano-cli,Syncano/syncano-cli,Syncano/syncano-cli | # -*- coding: utf-8 -*-
from __future__ import print_function
import json
import sys
from ConfigParser import NoOptionError
import click
from syncano_cli import LOG
from .connection import create_connection
@click.group()
def top_execute():
pass
@top_execute.command()
@click.option('--config', help=u'Account configuration file.')
@click.argument('instance_name', envvar='SYNCANO_INSTANCE')
@click.argument('script_endpoint_name')
@click.option('--payload', help=u'Script payload in JSON format.')
def execute(config, instance_name, script_endpoint_name, payload):
"""
Execute script endpoint in given instance
"""
try:
connection = create_connection(config)
except NoOptionError:
LOG.error('Do a login first: syncano login.')
sys.exit(1)
instance = connection.Instance.please.get(instance_name)
se = instance.script_endpoints.get(instance_name, script_endpoint_name)
data = json.loads(payload.strip() or '{}')
response = se.run(**data)
print(json.dumps(response.result, indent=4, sort_keys=True))
Refactor the code: add error handling of invalid or empty parameters, improve output format. | # -*- coding: utf-8 -*-
from __future__ import print_function
import json
import sys
from ConfigParser import NoOptionError
import click
from syncano.exceptions import SyncanoDoesNotExist
from syncano_cli import LOG
from .connection import create_connection
@click.group()
def top_execute():
pass
@top_execute.command()
@click.option('--config', help=u'Account configuration file.')
@click.argument('instance_name', envvar='SYNCANO_INSTANCE')
@click.argument('script_endpoint_name')
@click.option('--payload', help=u'Script payload in JSON format.')
def execute(config, instance_name, script_endpoint_name, payload):
"""
Execute script endpoint in given instance
"""
try:
connection = create_connection(config)
instance = connection.Instance.please.get(instance_name)
se = instance.script_endpoints.get(instance_name, script_endpoint_name)
data = json.loads((payload or '').strip() or '{}')
response = se.run(**data)
if response.status == 'success':
print(json.dumps(response.result['stdout'], indent=4, sort_keys=True))
else:
LOG.error(response.result['stderr'])
except NoOptionError:
LOG.error('Do a login first: syncano login.')
sys.exit(1)
except SyncanoDoesNotExist as e:
LOG.error(e)
sys.exit(1)
except ValueError as e:
LOG.error('Invalid payload format: {error}'.format(error=e))
sys.exit(1)
| <commit_before># -*- coding: utf-8 -*-
from __future__ import print_function
import json
import sys
from ConfigParser import NoOptionError
import click
from syncano_cli import LOG
from .connection import create_connection
@click.group()
def top_execute():
pass
@top_execute.command()
@click.option('--config', help=u'Account configuration file.')
@click.argument('instance_name', envvar='SYNCANO_INSTANCE')
@click.argument('script_endpoint_name')
@click.option('--payload', help=u'Script payload in JSON format.')
def execute(config, instance_name, script_endpoint_name, payload):
"""
Execute script endpoint in given instance
"""
try:
connection = create_connection(config)
except NoOptionError:
LOG.error('Do a login first: syncano login.')
sys.exit(1)
instance = connection.Instance.please.get(instance_name)
se = instance.script_endpoints.get(instance_name, script_endpoint_name)
data = json.loads(payload.strip() or '{}')
response = se.run(**data)
print(json.dumps(response.result, indent=4, sort_keys=True))
<commit_msg>Refactor the code: add error handling of invalid or empty parameters, improve output format.<commit_after> | # -*- coding: utf-8 -*-
from __future__ import print_function
import json
import sys
from ConfigParser import NoOptionError
import click
from syncano.exceptions import SyncanoDoesNotExist
from syncano_cli import LOG
from .connection import create_connection
@click.group()
def top_execute():
pass
@top_execute.command()
@click.option('--config', help=u'Account configuration file.')
@click.argument('instance_name', envvar='SYNCANO_INSTANCE')
@click.argument('script_endpoint_name')
@click.option('--payload', help=u'Script payload in JSON format.')
def execute(config, instance_name, script_endpoint_name, payload):
"""
Execute script endpoint in given instance
"""
try:
connection = create_connection(config)
instance = connection.Instance.please.get(instance_name)
se = instance.script_endpoints.get(instance_name, script_endpoint_name)
data = json.loads((payload or '').strip() or '{}')
response = se.run(**data)
if response.status == 'success':
print(json.dumps(response.result['stdout'], indent=4, sort_keys=True))
else:
LOG.error(response.result['stderr'])
except NoOptionError:
LOG.error('Do a login first: syncano login.')
sys.exit(1)
except SyncanoDoesNotExist as e:
LOG.error(e)
sys.exit(1)
except ValueError as e:
LOG.error('Invalid payload format: {error}'.format(error=e))
sys.exit(1)
| # -*- coding: utf-8 -*-
from __future__ import print_function
import json
import sys
from ConfigParser import NoOptionError
import click
from syncano_cli import LOG
from .connection import create_connection
@click.group()
def top_execute():
pass
@top_execute.command()
@click.option('--config', help=u'Account configuration file.')
@click.argument('instance_name', envvar='SYNCANO_INSTANCE')
@click.argument('script_endpoint_name')
@click.option('--payload', help=u'Script payload in JSON format.')
def execute(config, instance_name, script_endpoint_name, payload):
"""
Execute script endpoint in given instance
"""
try:
connection = create_connection(config)
except NoOptionError:
LOG.error('Do a login first: syncano login.')
sys.exit(1)
instance = connection.Instance.please.get(instance_name)
se = instance.script_endpoints.get(instance_name, script_endpoint_name)
data = json.loads(payload.strip() or '{}')
response = se.run(**data)
print(json.dumps(response.result, indent=4, sort_keys=True))
Refactor the code: add error handling of invalid or empty parameters, improve output format.# -*- coding: utf-8 -*-
from __future__ import print_function
import json
import sys
from ConfigParser import NoOptionError
import click
from syncano.exceptions import SyncanoDoesNotExist
from syncano_cli import LOG
from .connection import create_connection
@click.group()
def top_execute():
pass
@top_execute.command()
@click.option('--config', help=u'Account configuration file.')
@click.argument('instance_name', envvar='SYNCANO_INSTANCE')
@click.argument('script_endpoint_name')
@click.option('--payload', help=u'Script payload in JSON format.')
def execute(config, instance_name, script_endpoint_name, payload):
"""
Execute script endpoint in given instance
"""
try:
connection = create_connection(config)
instance = connection.Instance.please.get(instance_name)
se = instance.script_endpoints.get(instance_name, script_endpoint_name)
data = json.loads((payload or '').strip() or '{}')
response = se.run(**data)
if response.status == 'success':
print(json.dumps(response.result['stdout'], indent=4, sort_keys=True))
else:
LOG.error(response.result['stderr'])
except NoOptionError:
LOG.error('Do a login first: syncano login.')
sys.exit(1)
except SyncanoDoesNotExist as e:
LOG.error(e)
sys.exit(1)
except ValueError as e:
LOG.error('Invalid payload format: {error}'.format(error=e))
sys.exit(1)
| <commit_before># -*- coding: utf-8 -*-
from __future__ import print_function
import json
import sys
from ConfigParser import NoOptionError
import click
from syncano_cli import LOG
from .connection import create_connection
@click.group()
def top_execute():
pass
@top_execute.command()
@click.option('--config', help=u'Account configuration file.')
@click.argument('instance_name', envvar='SYNCANO_INSTANCE')
@click.argument('script_endpoint_name')
@click.option('--payload', help=u'Script payload in JSON format.')
def execute(config, instance_name, script_endpoint_name, payload):
"""
Execute script endpoint in given instance
"""
try:
connection = create_connection(config)
except NoOptionError:
LOG.error('Do a login first: syncano login.')
sys.exit(1)
instance = connection.Instance.please.get(instance_name)
se = instance.script_endpoints.get(instance_name, script_endpoint_name)
data = json.loads(payload.strip() or '{}')
response = se.run(**data)
print(json.dumps(response.result, indent=4, sort_keys=True))
<commit_msg>Refactor the code: add error handling of invalid or empty parameters, improve output format.<commit_after># -*- coding: utf-8 -*-
from __future__ import print_function
import json
import sys
from ConfigParser import NoOptionError
import click
from syncano.exceptions import SyncanoDoesNotExist
from syncano_cli import LOG
from .connection import create_connection
@click.group()
def top_execute():
pass
@top_execute.command()
@click.option('--config', help=u'Account configuration file.')
@click.argument('instance_name', envvar='SYNCANO_INSTANCE')
@click.argument('script_endpoint_name')
@click.option('--payload', help=u'Script payload in JSON format.')
def execute(config, instance_name, script_endpoint_name, payload):
"""
Execute script endpoint in given instance
"""
try:
connection = create_connection(config)
instance = connection.Instance.please.get(instance_name)
se = instance.script_endpoints.get(instance_name, script_endpoint_name)
data = json.loads((payload or '').strip() or '{}')
response = se.run(**data)
if response.status == 'success':
print(json.dumps(response.result['stdout'], indent=4, sort_keys=True))
else:
LOG.error(response.result['stderr'])
except NoOptionError:
LOG.error('Do a login first: syncano login.')
sys.exit(1)
except SyncanoDoesNotExist as e:
LOG.error(e)
sys.exit(1)
except ValueError as e:
LOG.error('Invalid payload format: {error}'.format(error=e))
sys.exit(1)
|
5f89ad72905947ac47c3246a15fae99c15571435 | django/signups/tests.py | django/signups/tests.py | """
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
from django.test.client import Client
from signups.models import User
from splinter_demo.test_runner import BROWSER
class TestSignup(TestCase):
def visit(self, path):
BROWSER.visit('http://localhost:65432' + path)
def test_sign_up(self):
Client().post('/', {'email': 'andrew@lorente.name'})
users = User.objects.all()
self.assertEqual(len(users), 1)
self.assertEqual(users[0].email, 'andrew@lorente.name')
self.visit('/')
BROWSER.fill('email', 'joe@lewis.name')
BROWSER.find_by_name('go').click()
assert BROWSER.is_text_present('Thanks'), 'rude!'
users = User.objects.all()
self.assertEqual(len(users), 2)
self.assertEqual(users[1].email, 'joe@lewis.name')
def test_valid_emails_get_validated(self):
self.visit('/')
BROWSER.fill('email', 'eric@holscher.name')
assert BROWSER.is_text_present('valid'), "didn't get validated"
def test_invalid_emails_get_yelled_about(self):
self.visit('/')
BROWSER.fill('email', 'aghlaghlaghl')
assert BROWSER.is_text_present('invalid'), "didn't get yelled at"
| from django.test import TestCase
from django.test.client import Client
from signups.models import User
from splinter_demo.test_runner import BROWSER
class TestSignup(TestCase):
def visit(self, path):
BROWSER.visit('http://localhost:65432' + path)
def test_sign_up(self):
Client().post('/', {'email': 'andrew@lorente.name'})
users = User.objects.all()
self.assertEqual(len(users), 1)
self.assertEqual(users[0].email, 'andrew@lorente.name')
self.visit('/')
BROWSER.fill('email', 'joe@lewis.name')
BROWSER.find_by_name('go').click()
assert BROWSER.is_text_present('Thanks'), 'rude!'
users = User.objects.all()
self.assertEqual(len(users), 2)
self.assertEqual(users[1].email, 'joe@lewis.name')
def test_valid_emails_get_validated(self):
self.visit('/')
BROWSER.fill('email', 'eric@holscher.name')
assert BROWSER.is_text_present('valid'), "didn't get validated"
def test_invalid_emails_get_yelled_about(self):
self.visit('/')
BROWSER.fill('email', 'aghlaghlaghl')
assert BROWSER.is_text_present('invalid'), "didn't get yelled at"
| Remove a bit of django boilerplate | Remove a bit of django boilerplate
| Python | mit | ErinCall/splinter_demo,ErinCall/splinter_demo | """
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
from django.test.client import Client
from signups.models import User
from splinter_demo.test_runner import BROWSER
class TestSignup(TestCase):
def visit(self, path):
BROWSER.visit('http://localhost:65432' + path)
def test_sign_up(self):
Client().post('/', {'email': 'andrew@lorente.name'})
users = User.objects.all()
self.assertEqual(len(users), 1)
self.assertEqual(users[0].email, 'andrew@lorente.name')
self.visit('/')
BROWSER.fill('email', 'joe@lewis.name')
BROWSER.find_by_name('go').click()
assert BROWSER.is_text_present('Thanks'), 'rude!'
users = User.objects.all()
self.assertEqual(len(users), 2)
self.assertEqual(users[1].email, 'joe@lewis.name')
def test_valid_emails_get_validated(self):
self.visit('/')
BROWSER.fill('email', 'eric@holscher.name')
assert BROWSER.is_text_present('valid'), "didn't get validated"
def test_invalid_emails_get_yelled_about(self):
self.visit('/')
BROWSER.fill('email', 'aghlaghlaghl')
assert BROWSER.is_text_present('invalid'), "didn't get yelled at"
Remove a bit of django boilerplate | from django.test import TestCase
from django.test.client import Client
from signups.models import User
from splinter_demo.test_runner import BROWSER
class TestSignup(TestCase):
def visit(self, path):
BROWSER.visit('http://localhost:65432' + path)
def test_sign_up(self):
Client().post('/', {'email': 'andrew@lorente.name'})
users = User.objects.all()
self.assertEqual(len(users), 1)
self.assertEqual(users[0].email, 'andrew@lorente.name')
self.visit('/')
BROWSER.fill('email', 'joe@lewis.name')
BROWSER.find_by_name('go').click()
assert BROWSER.is_text_present('Thanks'), 'rude!'
users = User.objects.all()
self.assertEqual(len(users), 2)
self.assertEqual(users[1].email, 'joe@lewis.name')
def test_valid_emails_get_validated(self):
self.visit('/')
BROWSER.fill('email', 'eric@holscher.name')
assert BROWSER.is_text_present('valid'), "didn't get validated"
def test_invalid_emails_get_yelled_about(self):
self.visit('/')
BROWSER.fill('email', 'aghlaghlaghl')
assert BROWSER.is_text_present('invalid'), "didn't get yelled at"
| <commit_before>"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
from django.test.client import Client
from signups.models import User
from splinter_demo.test_runner import BROWSER
class TestSignup(TestCase):
def visit(self, path):
BROWSER.visit('http://localhost:65432' + path)
def test_sign_up(self):
Client().post('/', {'email': 'andrew@lorente.name'})
users = User.objects.all()
self.assertEqual(len(users), 1)
self.assertEqual(users[0].email, 'andrew@lorente.name')
self.visit('/')
BROWSER.fill('email', 'joe@lewis.name')
BROWSER.find_by_name('go').click()
assert BROWSER.is_text_present('Thanks'), 'rude!'
users = User.objects.all()
self.assertEqual(len(users), 2)
self.assertEqual(users[1].email, 'joe@lewis.name')
def test_valid_emails_get_validated(self):
self.visit('/')
BROWSER.fill('email', 'eric@holscher.name')
assert BROWSER.is_text_present('valid'), "didn't get validated"
def test_invalid_emails_get_yelled_about(self):
self.visit('/')
BROWSER.fill('email', 'aghlaghlaghl')
assert BROWSER.is_text_present('invalid'), "didn't get yelled at"
<commit_msg>Remove a bit of django boilerplate<commit_after> | from django.test import TestCase
from django.test.client import Client
from signups.models import User
from splinter_demo.test_runner import BROWSER
class TestSignup(TestCase):
def visit(self, path):
BROWSER.visit('http://localhost:65432' + path)
def test_sign_up(self):
Client().post('/', {'email': 'andrew@lorente.name'})
users = User.objects.all()
self.assertEqual(len(users), 1)
self.assertEqual(users[0].email, 'andrew@lorente.name')
self.visit('/')
BROWSER.fill('email', 'joe@lewis.name')
BROWSER.find_by_name('go').click()
assert BROWSER.is_text_present('Thanks'), 'rude!'
users = User.objects.all()
self.assertEqual(len(users), 2)
self.assertEqual(users[1].email, 'joe@lewis.name')
def test_valid_emails_get_validated(self):
self.visit('/')
BROWSER.fill('email', 'eric@holscher.name')
assert BROWSER.is_text_present('valid'), "didn't get validated"
def test_invalid_emails_get_yelled_about(self):
self.visit('/')
BROWSER.fill('email', 'aghlaghlaghl')
assert BROWSER.is_text_present('invalid'), "didn't get yelled at"
| """
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
from django.test.client import Client
from signups.models import User
from splinter_demo.test_runner import BROWSER
class TestSignup(TestCase):
def visit(self, path):
BROWSER.visit('http://localhost:65432' + path)
def test_sign_up(self):
Client().post('/', {'email': 'andrew@lorente.name'})
users = User.objects.all()
self.assertEqual(len(users), 1)
self.assertEqual(users[0].email, 'andrew@lorente.name')
self.visit('/')
BROWSER.fill('email', 'joe@lewis.name')
BROWSER.find_by_name('go').click()
assert BROWSER.is_text_present('Thanks'), 'rude!'
users = User.objects.all()
self.assertEqual(len(users), 2)
self.assertEqual(users[1].email, 'joe@lewis.name')
def test_valid_emails_get_validated(self):
self.visit('/')
BROWSER.fill('email', 'eric@holscher.name')
assert BROWSER.is_text_present('valid'), "didn't get validated"
def test_invalid_emails_get_yelled_about(self):
self.visit('/')
BROWSER.fill('email', 'aghlaghlaghl')
assert BROWSER.is_text_present('invalid'), "didn't get yelled at"
Remove a bit of django boilerplatefrom django.test import TestCase
from django.test.client import Client
from signups.models import User
from splinter_demo.test_runner import BROWSER
class TestSignup(TestCase):
def visit(self, path):
BROWSER.visit('http://localhost:65432' + path)
def test_sign_up(self):
Client().post('/', {'email': 'andrew@lorente.name'})
users = User.objects.all()
self.assertEqual(len(users), 1)
self.assertEqual(users[0].email, 'andrew@lorente.name')
self.visit('/')
BROWSER.fill('email', 'joe@lewis.name')
BROWSER.find_by_name('go').click()
assert BROWSER.is_text_present('Thanks'), 'rude!'
users = User.objects.all()
self.assertEqual(len(users), 2)
self.assertEqual(users[1].email, 'joe@lewis.name')
def test_valid_emails_get_validated(self):
self.visit('/')
BROWSER.fill('email', 'eric@holscher.name')
assert BROWSER.is_text_present('valid'), "didn't get validated"
def test_invalid_emails_get_yelled_about(self):
self.visit('/')
BROWSER.fill('email', 'aghlaghlaghl')
assert BROWSER.is_text_present('invalid'), "didn't get yelled at"
| <commit_before>"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
from django.test.client import Client
from signups.models import User
from splinter_demo.test_runner import BROWSER
class TestSignup(TestCase):
def visit(self, path):
BROWSER.visit('http://localhost:65432' + path)
def test_sign_up(self):
Client().post('/', {'email': 'andrew@lorente.name'})
users = User.objects.all()
self.assertEqual(len(users), 1)
self.assertEqual(users[0].email, 'andrew@lorente.name')
self.visit('/')
BROWSER.fill('email', 'joe@lewis.name')
BROWSER.find_by_name('go').click()
assert BROWSER.is_text_present('Thanks'), 'rude!'
users = User.objects.all()
self.assertEqual(len(users), 2)
self.assertEqual(users[1].email, 'joe@lewis.name')
def test_valid_emails_get_validated(self):
self.visit('/')
BROWSER.fill('email', 'eric@holscher.name')
assert BROWSER.is_text_present('valid'), "didn't get validated"
def test_invalid_emails_get_yelled_about(self):
self.visit('/')
BROWSER.fill('email', 'aghlaghlaghl')
assert BROWSER.is_text_present('invalid'), "didn't get yelled at"
<commit_msg>Remove a bit of django boilerplate<commit_after>from django.test import TestCase
from django.test.client import Client
from signups.models import User
from splinter_demo.test_runner import BROWSER
class TestSignup(TestCase):
def visit(self, path):
BROWSER.visit('http://localhost:65432' + path)
def test_sign_up(self):
Client().post('/', {'email': 'andrew@lorente.name'})
users = User.objects.all()
self.assertEqual(len(users), 1)
self.assertEqual(users[0].email, 'andrew@lorente.name')
self.visit('/')
BROWSER.fill('email', 'joe@lewis.name')
BROWSER.find_by_name('go').click()
assert BROWSER.is_text_present('Thanks'), 'rude!'
users = User.objects.all()
self.assertEqual(len(users), 2)
self.assertEqual(users[1].email, 'joe@lewis.name')
def test_valid_emails_get_validated(self):
self.visit('/')
BROWSER.fill('email', 'eric@holscher.name')
assert BROWSER.is_text_present('valid'), "didn't get validated"
def test_invalid_emails_get_yelled_about(self):
self.visit('/')
BROWSER.fill('email', 'aghlaghlaghl')
assert BROWSER.is_text_present('invalid'), "didn't get yelled at"
|
bb85df8a9a8cecaf6f3db276347aa8f5f9b39d0c | bot/game/api/api_data.py | bot/game/api/api_data.py | import codecs
import json
from tools.cipher import salted_digest
DATA_ENCODING = "utf-8"
TRANSPORT_ENCODING = "base64"
DUMMY_ENCODING = "ascii"
DATA_DIGEST_SEPARATOR = "-"
def encode(data):
dumped_data = json.dumps(data)
encoded_dumped_data = dumped_data.encode(DATA_ENCODING)
encoded = codecs.encode(encoded_dumped_data, TRANSPORT_ENCODING)
digest = salted_digest(encoded)
return encoded.decode(DUMMY_ENCODING) + DATA_DIGEST_SEPARATOR + digest
def decode(data):
try:
encoded, digest = data.split(DATA_DIGEST_SEPARATOR, 1)
encoded = encoded.encode(DUMMY_ENCODING)
calculated_digest = salted_digest(encoded)
if calculated_digest == digest:
encoded_dumped_data = codecs.decode(encoded, TRANSPORT_ENCODING)
dumped_data = encoded_dumped_data.decode(DATA_ENCODING)
return json.loads(dumped_data)
except Exception:
pass
return {}
| import codecs
import json
from tools.cipher import salted_digest
DATA_ENCODING = "utf-8"
TRANSPORT_ENCODING = "base64"
DUMMY_ENCODING = "ascii"
DATA_DIGEST_SEPARATOR = "-"
def encode(data):
dumped_data = json.dumps(data)
encoded_dumped_data = dumped_data.encode(DATA_ENCODING)
encoded = _transport_encode(encoded_dumped_data)
digest = salted_digest(encoded)
return encoded.decode(DUMMY_ENCODING) + DATA_DIGEST_SEPARATOR + digest
def decode(data):
try:
encoded, digest = data.split(DATA_DIGEST_SEPARATOR, 1)
encoded = encoded.encode(DUMMY_ENCODING)
calculated_digest = salted_digest(encoded)
if calculated_digest == digest:
encoded_dumped_data = _transport_decode(encoded)
dumped_data = encoded_dumped_data.decode(DATA_ENCODING)
return json.loads(dumped_data)
except Exception:
pass
return {}
def _transport_encode(data):
return codecs.encode(data, TRANSPORT_ENCODING).replace(b"\n", b"")
def _transport_decode(data):
return codecs.decode(data, TRANSPORT_ENCODING)
| Remove newlines from exported url_data | Remove newlines from exported url_data
| Python | apache-2.0 | alvarogzp/telegram-games,alvarogzp/telegram-games,alvarogzp/telegram-games,alvarogzp/telegram-games | import codecs
import json
from tools.cipher import salted_digest
DATA_ENCODING = "utf-8"
TRANSPORT_ENCODING = "base64"
DUMMY_ENCODING = "ascii"
DATA_DIGEST_SEPARATOR = "-"
def encode(data):
dumped_data = json.dumps(data)
encoded_dumped_data = dumped_data.encode(DATA_ENCODING)
encoded = codecs.encode(encoded_dumped_data, TRANSPORT_ENCODING)
digest = salted_digest(encoded)
return encoded.decode(DUMMY_ENCODING) + DATA_DIGEST_SEPARATOR + digest
def decode(data):
try:
encoded, digest = data.split(DATA_DIGEST_SEPARATOR, 1)
encoded = encoded.encode(DUMMY_ENCODING)
calculated_digest = salted_digest(encoded)
if calculated_digest == digest:
encoded_dumped_data = codecs.decode(encoded, TRANSPORT_ENCODING)
dumped_data = encoded_dumped_data.decode(DATA_ENCODING)
return json.loads(dumped_data)
except Exception:
pass
return {}
Remove newlines from exported url_data | import codecs
import json
from tools.cipher import salted_digest
DATA_ENCODING = "utf-8"
TRANSPORT_ENCODING = "base64"
DUMMY_ENCODING = "ascii"
DATA_DIGEST_SEPARATOR = "-"
def encode(data):
dumped_data = json.dumps(data)
encoded_dumped_data = dumped_data.encode(DATA_ENCODING)
encoded = _transport_encode(encoded_dumped_data)
digest = salted_digest(encoded)
return encoded.decode(DUMMY_ENCODING) + DATA_DIGEST_SEPARATOR + digest
def decode(data):
try:
encoded, digest = data.split(DATA_DIGEST_SEPARATOR, 1)
encoded = encoded.encode(DUMMY_ENCODING)
calculated_digest = salted_digest(encoded)
if calculated_digest == digest:
encoded_dumped_data = _transport_decode(encoded)
dumped_data = encoded_dumped_data.decode(DATA_ENCODING)
return json.loads(dumped_data)
except Exception:
pass
return {}
def _transport_encode(data):
return codecs.encode(data, TRANSPORT_ENCODING).replace(b"\n", b"")
def _transport_decode(data):
return codecs.decode(data, TRANSPORT_ENCODING)
| <commit_before>import codecs
import json
from tools.cipher import salted_digest
DATA_ENCODING = "utf-8"
TRANSPORT_ENCODING = "base64"
DUMMY_ENCODING = "ascii"
DATA_DIGEST_SEPARATOR = "-"
def encode(data):
dumped_data = json.dumps(data)
encoded_dumped_data = dumped_data.encode(DATA_ENCODING)
encoded = codecs.encode(encoded_dumped_data, TRANSPORT_ENCODING)
digest = salted_digest(encoded)
return encoded.decode(DUMMY_ENCODING) + DATA_DIGEST_SEPARATOR + digest
def decode(data):
try:
encoded, digest = data.split(DATA_DIGEST_SEPARATOR, 1)
encoded = encoded.encode(DUMMY_ENCODING)
calculated_digest = salted_digest(encoded)
if calculated_digest == digest:
encoded_dumped_data = codecs.decode(encoded, TRANSPORT_ENCODING)
dumped_data = encoded_dumped_data.decode(DATA_ENCODING)
return json.loads(dumped_data)
except Exception:
pass
return {}
<commit_msg>Remove newlines from exported url_data<commit_after> | import codecs
import json
from tools.cipher import salted_digest
DATA_ENCODING = "utf-8"
TRANSPORT_ENCODING = "base64"
DUMMY_ENCODING = "ascii"
DATA_DIGEST_SEPARATOR = "-"
def encode(data):
dumped_data = json.dumps(data)
encoded_dumped_data = dumped_data.encode(DATA_ENCODING)
encoded = _transport_encode(encoded_dumped_data)
digest = salted_digest(encoded)
return encoded.decode(DUMMY_ENCODING) + DATA_DIGEST_SEPARATOR + digest
def decode(data):
try:
encoded, digest = data.split(DATA_DIGEST_SEPARATOR, 1)
encoded = encoded.encode(DUMMY_ENCODING)
calculated_digest = salted_digest(encoded)
if calculated_digest == digest:
encoded_dumped_data = _transport_decode(encoded)
dumped_data = encoded_dumped_data.decode(DATA_ENCODING)
return json.loads(dumped_data)
except Exception:
pass
return {}
def _transport_encode(data):
return codecs.encode(data, TRANSPORT_ENCODING).replace(b"\n", b"")
def _transport_decode(data):
return codecs.decode(data, TRANSPORT_ENCODING)
| import codecs
import json
from tools.cipher import salted_digest
DATA_ENCODING = "utf-8"
TRANSPORT_ENCODING = "base64"
DUMMY_ENCODING = "ascii"
DATA_DIGEST_SEPARATOR = "-"
def encode(data):
dumped_data = json.dumps(data)
encoded_dumped_data = dumped_data.encode(DATA_ENCODING)
encoded = codecs.encode(encoded_dumped_data, TRANSPORT_ENCODING)
digest = salted_digest(encoded)
return encoded.decode(DUMMY_ENCODING) + DATA_DIGEST_SEPARATOR + digest
def decode(data):
try:
encoded, digest = data.split(DATA_DIGEST_SEPARATOR, 1)
encoded = encoded.encode(DUMMY_ENCODING)
calculated_digest = salted_digest(encoded)
if calculated_digest == digest:
encoded_dumped_data = codecs.decode(encoded, TRANSPORT_ENCODING)
dumped_data = encoded_dumped_data.decode(DATA_ENCODING)
return json.loads(dumped_data)
except Exception:
pass
return {}
Remove newlines from exported url_dataimport codecs
import json
from tools.cipher import salted_digest
DATA_ENCODING = "utf-8"
TRANSPORT_ENCODING = "base64"
DUMMY_ENCODING = "ascii"
DATA_DIGEST_SEPARATOR = "-"
def encode(data):
dumped_data = json.dumps(data)
encoded_dumped_data = dumped_data.encode(DATA_ENCODING)
encoded = _transport_encode(encoded_dumped_data)
digest = salted_digest(encoded)
return encoded.decode(DUMMY_ENCODING) + DATA_DIGEST_SEPARATOR + digest
def decode(data):
try:
encoded, digest = data.split(DATA_DIGEST_SEPARATOR, 1)
encoded = encoded.encode(DUMMY_ENCODING)
calculated_digest = salted_digest(encoded)
if calculated_digest == digest:
encoded_dumped_data = _transport_decode(encoded)
dumped_data = encoded_dumped_data.decode(DATA_ENCODING)
return json.loads(dumped_data)
except Exception:
pass
return {}
def _transport_encode(data):
return codecs.encode(data, TRANSPORT_ENCODING).replace(b"\n", b"")
def _transport_decode(data):
return codecs.decode(data, TRANSPORT_ENCODING)
| <commit_before>import codecs
import json
from tools.cipher import salted_digest
DATA_ENCODING = "utf-8"
TRANSPORT_ENCODING = "base64"
DUMMY_ENCODING = "ascii"
DATA_DIGEST_SEPARATOR = "-"
def encode(data):
dumped_data = json.dumps(data)
encoded_dumped_data = dumped_data.encode(DATA_ENCODING)
encoded = codecs.encode(encoded_dumped_data, TRANSPORT_ENCODING)
digest = salted_digest(encoded)
return encoded.decode(DUMMY_ENCODING) + DATA_DIGEST_SEPARATOR + digest
def decode(data):
try:
encoded, digest = data.split(DATA_DIGEST_SEPARATOR, 1)
encoded = encoded.encode(DUMMY_ENCODING)
calculated_digest = salted_digest(encoded)
if calculated_digest == digest:
encoded_dumped_data = codecs.decode(encoded, TRANSPORT_ENCODING)
dumped_data = encoded_dumped_data.decode(DATA_ENCODING)
return json.loads(dumped_data)
except Exception:
pass
return {}
<commit_msg>Remove newlines from exported url_data<commit_after>import codecs
import json
from tools.cipher import salted_digest
DATA_ENCODING = "utf-8"
TRANSPORT_ENCODING = "base64"
DUMMY_ENCODING = "ascii"
DATA_DIGEST_SEPARATOR = "-"
def encode(data):
dumped_data = json.dumps(data)
encoded_dumped_data = dumped_data.encode(DATA_ENCODING)
encoded = _transport_encode(encoded_dumped_data)
digest = salted_digest(encoded)
return encoded.decode(DUMMY_ENCODING) + DATA_DIGEST_SEPARATOR + digest
def decode(data):
try:
encoded, digest = data.split(DATA_DIGEST_SEPARATOR, 1)
encoded = encoded.encode(DUMMY_ENCODING)
calculated_digest = salted_digest(encoded)
if calculated_digest == digest:
encoded_dumped_data = _transport_decode(encoded)
dumped_data = encoded_dumped_data.decode(DATA_ENCODING)
return json.loads(dumped_data)
except Exception:
pass
return {}
def _transport_encode(data):
return codecs.encode(data, TRANSPORT_ENCODING).replace(b"\n", b"")
def _transport_decode(data):
return codecs.decode(data, TRANSPORT_ENCODING)
|
4b6b5effc744583eb0227d14d0c5e324c50cf074 | tests/integration/test_proxy.py | tests/integration/test_proxy.py | # -*- coding: utf-8 -*-
'''Test using a proxy.'''
# External imports
import multiprocessing
import pytest
from six.moves import socketserver, SimpleHTTPServer
from six.moves.urllib.request import urlopen
# Internal imports
import vcr
# Conditional imports
requests = pytest.importorskip("requests")
class Proxy(SimpleHTTPServer.SimpleHTTPRequestHandler):
'''
Simple proxy server.
(from: http://effbot.org/librarybook/simplehttpserver.htm).
'''
def do_GET(self):
self.copyfile(urlopen(self.path), self.wfile)
@pytest.yield_fixture(scope='session')
def proxy_server():
httpd = socketserver.ThreadingTCPServer(('', 0), Proxy)
proxy_process = multiprocessing.Process(
target=httpd.serve_forever,
)
proxy_process.start()
yield 'http://{0}:{1}'.format(*httpd.server_address)
proxy_process.terminate()
def test_use_proxy(tmpdir, httpbin, proxy_server):
'''Ensure that it works with a proxy.'''
with vcr.use_cassette(str(tmpdir.join('proxy.yaml'))):
requests.get(httpbin.url, proxies={'http': proxy_server})
requests.get(httpbin.url, proxies={'http': proxy_server})
| # -*- coding: utf-8 -*-
'''Test using a proxy.'''
# External imports
import multiprocessing
import pytest
from six.moves import socketserver, SimpleHTTPServer
from six.moves.urllib.request import urlopen
# Internal imports
import vcr
# Conditional imports
requests = pytest.importorskip("requests")
class Proxy(SimpleHTTPServer.SimpleHTTPRequestHandler):
'''
Simple proxy server.
(Inspired by: http://effbot.org/librarybook/simplehttpserver.htm).
'''
def do_GET(self):
upstream_response = urlopen(self.path)
self.send_response(upstream_response.status, upstream_response.msg)
for header in upstream_response.headers.items():
self.send_header(*header)
self.end_headers()
self.copyfile(upstream_response, self.wfile)
@pytest.yield_fixture(scope='session')
def proxy_server():
httpd = socketserver.ThreadingTCPServer(('', 0), Proxy)
proxy_process = multiprocessing.Process(
target=httpd.serve_forever,
)
proxy_process.start()
yield 'http://{0}:{1}'.format(*httpd.server_address)
proxy_process.terminate()
def test_use_proxy(tmpdir, httpbin, proxy_server):
'''Ensure that it works with a proxy.'''
with vcr.use_cassette(str(tmpdir.join('proxy.yaml'))):
requests.get(httpbin.url, proxies={'http': proxy_server})
requests.get(httpbin.url, proxies={'http': proxy_server})
| Add headers in proxy server response | Add headers in proxy server response
| Python | mit | kevin1024/vcrpy,kevin1024/vcrpy,graingert/vcrpy,graingert/vcrpy | # -*- coding: utf-8 -*-
'''Test using a proxy.'''
# External imports
import multiprocessing
import pytest
from six.moves import socketserver, SimpleHTTPServer
from six.moves.urllib.request import urlopen
# Internal imports
import vcr
# Conditional imports
requests = pytest.importorskip("requests")
class Proxy(SimpleHTTPServer.SimpleHTTPRequestHandler):
'''
Simple proxy server.
(from: http://effbot.org/librarybook/simplehttpserver.htm).
'''
def do_GET(self):
self.copyfile(urlopen(self.path), self.wfile)
@pytest.yield_fixture(scope='session')
def proxy_server():
httpd = socketserver.ThreadingTCPServer(('', 0), Proxy)
proxy_process = multiprocessing.Process(
target=httpd.serve_forever,
)
proxy_process.start()
yield 'http://{0}:{1}'.format(*httpd.server_address)
proxy_process.terminate()
def test_use_proxy(tmpdir, httpbin, proxy_server):
'''Ensure that it works with a proxy.'''
with vcr.use_cassette(str(tmpdir.join('proxy.yaml'))):
requests.get(httpbin.url, proxies={'http': proxy_server})
requests.get(httpbin.url, proxies={'http': proxy_server})
Add headers in proxy server response | # -*- coding: utf-8 -*-
'''Test using a proxy.'''
# External imports
import multiprocessing
import pytest
from six.moves import socketserver, SimpleHTTPServer
from six.moves.urllib.request import urlopen
# Internal imports
import vcr
# Conditional imports
requests = pytest.importorskip("requests")
class Proxy(SimpleHTTPServer.SimpleHTTPRequestHandler):
'''
Simple proxy server.
(Inspired by: http://effbot.org/librarybook/simplehttpserver.htm).
'''
def do_GET(self):
upstream_response = urlopen(self.path)
self.send_response(upstream_response.status, upstream_response.msg)
for header in upstream_response.headers.items():
self.send_header(*header)
self.end_headers()
self.copyfile(upstream_response, self.wfile)
@pytest.yield_fixture(scope='session')
def proxy_server():
httpd = socketserver.ThreadingTCPServer(('', 0), Proxy)
proxy_process = multiprocessing.Process(
target=httpd.serve_forever,
)
proxy_process.start()
yield 'http://{0}:{1}'.format(*httpd.server_address)
proxy_process.terminate()
def test_use_proxy(tmpdir, httpbin, proxy_server):
'''Ensure that it works with a proxy.'''
with vcr.use_cassette(str(tmpdir.join('proxy.yaml'))):
requests.get(httpbin.url, proxies={'http': proxy_server})
requests.get(httpbin.url, proxies={'http': proxy_server})
| <commit_before># -*- coding: utf-8 -*-
'''Test using a proxy.'''
# External imports
import multiprocessing
import pytest
from six.moves import socketserver, SimpleHTTPServer
from six.moves.urllib.request import urlopen
# Internal imports
import vcr
# Conditional imports
requests = pytest.importorskip("requests")
class Proxy(SimpleHTTPServer.SimpleHTTPRequestHandler):
'''
Simple proxy server.
(from: http://effbot.org/librarybook/simplehttpserver.htm).
'''
def do_GET(self):
self.copyfile(urlopen(self.path), self.wfile)
@pytest.yield_fixture(scope='session')
def proxy_server():
httpd = socketserver.ThreadingTCPServer(('', 0), Proxy)
proxy_process = multiprocessing.Process(
target=httpd.serve_forever,
)
proxy_process.start()
yield 'http://{0}:{1}'.format(*httpd.server_address)
proxy_process.terminate()
def test_use_proxy(tmpdir, httpbin, proxy_server):
'''Ensure that it works with a proxy.'''
with vcr.use_cassette(str(tmpdir.join('proxy.yaml'))):
requests.get(httpbin.url, proxies={'http': proxy_server})
requests.get(httpbin.url, proxies={'http': proxy_server})
<commit_msg>Add headers in proxy server response<commit_after> | # -*- coding: utf-8 -*-
'''Test using a proxy.'''
# External imports
import multiprocessing
import pytest
from six.moves import socketserver, SimpleHTTPServer
from six.moves.urllib.request import urlopen
# Internal imports
import vcr
# Conditional imports
requests = pytest.importorskip("requests")
class Proxy(SimpleHTTPServer.SimpleHTTPRequestHandler):
'''
Simple proxy server.
(Inspired by: http://effbot.org/librarybook/simplehttpserver.htm).
'''
def do_GET(self):
upstream_response = urlopen(self.path)
self.send_response(upstream_response.status, upstream_response.msg)
for header in upstream_response.headers.items():
self.send_header(*header)
self.end_headers()
self.copyfile(upstream_response, self.wfile)
@pytest.yield_fixture(scope='session')
def proxy_server():
httpd = socketserver.ThreadingTCPServer(('', 0), Proxy)
proxy_process = multiprocessing.Process(
target=httpd.serve_forever,
)
proxy_process.start()
yield 'http://{0}:{1}'.format(*httpd.server_address)
proxy_process.terminate()
def test_use_proxy(tmpdir, httpbin, proxy_server):
'''Ensure that it works with a proxy.'''
with vcr.use_cassette(str(tmpdir.join('proxy.yaml'))):
requests.get(httpbin.url, proxies={'http': proxy_server})
requests.get(httpbin.url, proxies={'http': proxy_server})
| # -*- coding: utf-8 -*-
'''Test using a proxy.'''
# External imports
import multiprocessing
import pytest
from six.moves import socketserver, SimpleHTTPServer
from six.moves.urllib.request import urlopen
# Internal imports
import vcr
# Conditional imports
requests = pytest.importorskip("requests")
class Proxy(SimpleHTTPServer.SimpleHTTPRequestHandler):
'''
Simple proxy server.
(from: http://effbot.org/librarybook/simplehttpserver.htm).
'''
def do_GET(self):
self.copyfile(urlopen(self.path), self.wfile)
@pytest.yield_fixture(scope='session')
def proxy_server():
httpd = socketserver.ThreadingTCPServer(('', 0), Proxy)
proxy_process = multiprocessing.Process(
target=httpd.serve_forever,
)
proxy_process.start()
yield 'http://{0}:{1}'.format(*httpd.server_address)
proxy_process.terminate()
def test_use_proxy(tmpdir, httpbin, proxy_server):
'''Ensure that it works with a proxy.'''
with vcr.use_cassette(str(tmpdir.join('proxy.yaml'))):
requests.get(httpbin.url, proxies={'http': proxy_server})
requests.get(httpbin.url, proxies={'http': proxy_server})
Add headers in proxy server response# -*- coding: utf-8 -*-
'''Test using a proxy.'''
# External imports
import multiprocessing
import pytest
from six.moves import socketserver, SimpleHTTPServer
from six.moves.urllib.request import urlopen
# Internal imports
import vcr
# Conditional imports
requests = pytest.importorskip("requests")
class Proxy(SimpleHTTPServer.SimpleHTTPRequestHandler):
'''
Simple proxy server.
(Inspired by: http://effbot.org/librarybook/simplehttpserver.htm).
'''
def do_GET(self):
upstream_response = urlopen(self.path)
self.send_response(upstream_response.status, upstream_response.msg)
for header in upstream_response.headers.items():
self.send_header(*header)
self.end_headers()
self.copyfile(upstream_response, self.wfile)
@pytest.yield_fixture(scope='session')
def proxy_server():
httpd = socketserver.ThreadingTCPServer(('', 0), Proxy)
proxy_process = multiprocessing.Process(
target=httpd.serve_forever,
)
proxy_process.start()
yield 'http://{0}:{1}'.format(*httpd.server_address)
proxy_process.terminate()
def test_use_proxy(tmpdir, httpbin, proxy_server):
'''Ensure that it works with a proxy.'''
with vcr.use_cassette(str(tmpdir.join('proxy.yaml'))):
requests.get(httpbin.url, proxies={'http': proxy_server})
requests.get(httpbin.url, proxies={'http': proxy_server})
| <commit_before># -*- coding: utf-8 -*-
'''Test using a proxy.'''
# External imports
import multiprocessing
import pytest
from six.moves import socketserver, SimpleHTTPServer
from six.moves.urllib.request import urlopen
# Internal imports
import vcr
# Conditional imports
requests = pytest.importorskip("requests")
class Proxy(SimpleHTTPServer.SimpleHTTPRequestHandler):
'''
Simple proxy server.
(from: http://effbot.org/librarybook/simplehttpserver.htm).
'''
def do_GET(self):
self.copyfile(urlopen(self.path), self.wfile)
@pytest.yield_fixture(scope='session')
def proxy_server():
httpd = socketserver.ThreadingTCPServer(('', 0), Proxy)
proxy_process = multiprocessing.Process(
target=httpd.serve_forever,
)
proxy_process.start()
yield 'http://{0}:{1}'.format(*httpd.server_address)
proxy_process.terminate()
def test_use_proxy(tmpdir, httpbin, proxy_server):
'''Ensure that it works with a proxy.'''
with vcr.use_cassette(str(tmpdir.join('proxy.yaml'))):
requests.get(httpbin.url, proxies={'http': proxy_server})
requests.get(httpbin.url, proxies={'http': proxy_server})
<commit_msg>Add headers in proxy server response<commit_after># -*- coding: utf-8 -*-
'''Test using a proxy.'''
# External imports
import multiprocessing
import pytest
from six.moves import socketserver, SimpleHTTPServer
from six.moves.urllib.request import urlopen
# Internal imports
import vcr
# Conditional imports
requests = pytest.importorskip("requests")
class Proxy(SimpleHTTPServer.SimpleHTTPRequestHandler):
'''
Simple proxy server.
(Inspired by: http://effbot.org/librarybook/simplehttpserver.htm).
'''
def do_GET(self):
upstream_response = urlopen(self.path)
self.send_response(upstream_response.status, upstream_response.msg)
for header in upstream_response.headers.items():
self.send_header(*header)
self.end_headers()
self.copyfile(upstream_response, self.wfile)
@pytest.yield_fixture(scope='session')
def proxy_server():
httpd = socketserver.ThreadingTCPServer(('', 0), Proxy)
proxy_process = multiprocessing.Process(
target=httpd.serve_forever,
)
proxy_process.start()
yield 'http://{0}:{1}'.format(*httpd.server_address)
proxy_process.terminate()
def test_use_proxy(tmpdir, httpbin, proxy_server):
'''Ensure that it works with a proxy.'''
with vcr.use_cassette(str(tmpdir.join('proxy.yaml'))):
requests.get(httpbin.url, proxies={'http': proxy_server})
requests.get(httpbin.url, proxies={'http': proxy_server})
|
2cc26cd92bd2c2fc6300021bc4b7a0a219cf97cd | tests/mep/genetics/test_gene.py | tests/mep/genetics/test_gene.py | import unittest
from mep.genetics.gene import VariableGene
import numpy as np
class TestVariableGene(unittest.TestCase):
"""
Tests for the variable gene.
"""
def test_basic_constant(self):
"""
Simple check of a constant gene with just 1 gene in the chromosome.
"""
# construct
constant_index = 0
gene = VariableGene(constant_index, is_feature=False)
# simple eval matrix; 1 gene in a chromosome, 3 examples, 2 constants
num_examples = 2
num_genes = 1
num_features = 3
# create
constants = [1., 2.]
eval_matrix = np.zeros((num_genes, num_examples))
data_matrix = np.zeros((num_examples, num_features))
# expected; only one gene and it is going to be using the first constant;
gene_index = 0
expected_eval_matrix = np.matrix([[constants[constant_index], constants[constant_index]]])
# run the evaluate
gene.evaluate(gene_index, eval_matrix, data_matrix, constants)
self.assertTrue(np.array_equal(expected_eval_matrix, eval_matrix))
| Test of the constant variable. | Test of the constant variable.
| Python | mit | paulfjacobs/py-mep,paulfjacobs/py-mep | Test of the constant variable. | import unittest
from mep.genetics.gene import VariableGene
import numpy as np
class TestVariableGene(unittest.TestCase):
"""
Tests for the variable gene.
"""
def test_basic_constant(self):
"""
Simple check of a constant gene with just 1 gene in the chromosome.
"""
# construct
constant_index = 0
gene = VariableGene(constant_index, is_feature=False)
# simple eval matrix; 1 gene in a chromosome, 3 examples, 2 constants
num_examples = 2
num_genes = 1
num_features = 3
# create
constants = [1., 2.]
eval_matrix = np.zeros((num_genes, num_examples))
data_matrix = np.zeros((num_examples, num_features))
# expected; only one gene and it is going to be using the first constant;
gene_index = 0
expected_eval_matrix = np.matrix([[constants[constant_index], constants[constant_index]]])
# run the evaluate
gene.evaluate(gene_index, eval_matrix, data_matrix, constants)
self.assertTrue(np.array_equal(expected_eval_matrix, eval_matrix))
| <commit_before><commit_msg>Test of the constant variable.<commit_after> | import unittest
from mep.genetics.gene import VariableGene
import numpy as np
class TestVariableGene(unittest.TestCase):
"""
Tests for the variable gene.
"""
def test_basic_constant(self):
"""
Simple check of a constant gene with just 1 gene in the chromosome.
"""
# construct
constant_index = 0
gene = VariableGene(constant_index, is_feature=False)
# simple eval matrix; 1 gene in a chromosome, 3 examples, 2 constants
num_examples = 2
num_genes = 1
num_features = 3
# create
constants = [1., 2.]
eval_matrix = np.zeros((num_genes, num_examples))
data_matrix = np.zeros((num_examples, num_features))
# expected; only one gene and it is going to be using the first constant;
gene_index = 0
expected_eval_matrix = np.matrix([[constants[constant_index], constants[constant_index]]])
# run the evaluate
gene.evaluate(gene_index, eval_matrix, data_matrix, constants)
self.assertTrue(np.array_equal(expected_eval_matrix, eval_matrix))
| Test of the constant variable.import unittest
from mep.genetics.gene import VariableGene
import numpy as np
class TestVariableGene(unittest.TestCase):
"""
Tests for the variable gene.
"""
def test_basic_constant(self):
"""
Simple check of a constant gene with just 1 gene in the chromosome.
"""
# construct
constant_index = 0
gene = VariableGene(constant_index, is_feature=False)
# simple eval matrix; 1 gene in a chromosome, 3 examples, 2 constants
num_examples = 2
num_genes = 1
num_features = 3
# create
constants = [1., 2.]
eval_matrix = np.zeros((num_genes, num_examples))
data_matrix = np.zeros((num_examples, num_features))
# expected; only one gene and it is going to be using the first constant;
gene_index = 0
expected_eval_matrix = np.matrix([[constants[constant_index], constants[constant_index]]])
# run the evaluate
gene.evaluate(gene_index, eval_matrix, data_matrix, constants)
self.assertTrue(np.array_equal(expected_eval_matrix, eval_matrix))
| <commit_before><commit_msg>Test of the constant variable.<commit_after>import unittest
from mep.genetics.gene import VariableGene
import numpy as np
class TestVariableGene(unittest.TestCase):
"""
Tests for the variable gene.
"""
def test_basic_constant(self):
"""
Simple check of a constant gene with just 1 gene in the chromosome.
"""
# construct
constant_index = 0
gene = VariableGene(constant_index, is_feature=False)
# simple eval matrix; 1 gene in a chromosome, 3 examples, 2 constants
num_examples = 2
num_genes = 1
num_features = 3
# create
constants = [1., 2.]
eval_matrix = np.zeros((num_genes, num_examples))
data_matrix = np.zeros((num_examples, num_features))
# expected; only one gene and it is going to be using the first constant;
gene_index = 0
expected_eval_matrix = np.matrix([[constants[constant_index], constants[constant_index]]])
# run the evaluate
gene.evaluate(gene_index, eval_matrix, data_matrix, constants)
self.assertTrue(np.array_equal(expected_eval_matrix, eval_matrix))
| |
e9ad33a12dcb3f678c2aa7a8bcc0339dcb88bd5b | tests/unit/test_authenticate.py | tests/unit/test_authenticate.py | """Test the DigitalOcean backed ACME DNS Authentication Class."""
from acmednsauth.authenticate import Authenticate
from mock import call
import pytest
@pytest.fixture()
def create_environment(api_key, domain, fqdn, auth_token):
return {
'DO_API_KEY': api_key,
'DO_DOMAIN': domain,
'CERTBOT_DOMAIN': fqdn,
'CERTBOT_VALIDATION': auth_token,
}
def test_valid_data_calls_record_creation_after_initialization(
mocker, api_key, hostname, domain, auth_token, create_environment):
record = mocker.patch('acmednsauth.authenticate.Record')
Authenticate(environment=create_environment)
initialize_then_create = [
call(api_key, domain, hostname),
call().create(auth_token)]
record.assert_has_calls(initialize_then_create)
def test_valid_data_writes_to_printer_after_record_creation(
mocker, create_environment):
class FakeRecord(object):
def __init__(self, a, b, c): pass
def create(self, a): return 123456
mocker.patch('acmednsauth.authenticate.Record', new=FakeRecord)
stub_printer = mocker.patch('acmednsauth.authenticate.Printer')
Authenticate(environment=create_environment)
stub_printer.assert_has_calls([call(123456)])
| """Test the DigitalOcean backed ACME DNS Authentication Class."""
from acmednsauth.authenticate import Authenticate
from mock import call
import pytest
@pytest.fixture()
def create_environment(api_key, domain, fqdn, auth_token):
return {
'DO_API_KEY': api_key,
'DO_DOMAIN': domain,
'CERTBOT_DOMAIN': fqdn,
'CERTBOT_VALIDATION': auth_token,
}
def test_triggering_of_record_creation_after_initialization(
mocker, api_key, hostname, domain, auth_token, create_environment):
record = mocker.patch('acmednsauth.authenticate.Record')
Authenticate(environment=create_environment)
initialize_then_create = [
call(api_key, domain, hostname),
call().create(auth_token)]
record.assert_has_calls(initialize_then_create)
def test_passes_record_id_to_printer_after_record_creation(
mocker, create_environment):
class FakeRecord(object):
def __init__(self, a, b, c): pass
def create(self, a): return 123456
mocker.patch('acmednsauth.authenticate.Record', new=FakeRecord)
stub_printer = mocker.patch('acmednsauth.authenticate.Printer')
Authenticate(environment=create_environment)
stub_printer.assert_has_calls([call(123456)])
| Reword Test Names for Clarity | Reword Test Names for Clarity
I didn't like how the test names were sounding. Hopefully this is
better.
| Python | apache-2.0 | Jitsusama/lets-do-dns | """Test the DigitalOcean backed ACME DNS Authentication Class."""
from acmednsauth.authenticate import Authenticate
from mock import call
import pytest
@pytest.fixture()
def create_environment(api_key, domain, fqdn, auth_token):
return {
'DO_API_KEY': api_key,
'DO_DOMAIN': domain,
'CERTBOT_DOMAIN': fqdn,
'CERTBOT_VALIDATION': auth_token,
}
def test_valid_data_calls_record_creation_after_initialization(
mocker, api_key, hostname, domain, auth_token, create_environment):
record = mocker.patch('acmednsauth.authenticate.Record')
Authenticate(environment=create_environment)
initialize_then_create = [
call(api_key, domain, hostname),
call().create(auth_token)]
record.assert_has_calls(initialize_then_create)
def test_valid_data_writes_to_printer_after_record_creation(
mocker, create_environment):
class FakeRecord(object):
def __init__(self, a, b, c): pass
def create(self, a): return 123456
mocker.patch('acmednsauth.authenticate.Record', new=FakeRecord)
stub_printer = mocker.patch('acmednsauth.authenticate.Printer')
Authenticate(environment=create_environment)
stub_printer.assert_has_calls([call(123456)])
Reword Test Names for Clarity
I didn't like how the test names were sounding. Hopefully this is
better. | """Test the DigitalOcean backed ACME DNS Authentication Class."""
from acmednsauth.authenticate import Authenticate
from mock import call
import pytest
@pytest.fixture()
def create_environment(api_key, domain, fqdn, auth_token):
return {
'DO_API_KEY': api_key,
'DO_DOMAIN': domain,
'CERTBOT_DOMAIN': fqdn,
'CERTBOT_VALIDATION': auth_token,
}
def test_triggering_of_record_creation_after_initialization(
mocker, api_key, hostname, domain, auth_token, create_environment):
record = mocker.patch('acmednsauth.authenticate.Record')
Authenticate(environment=create_environment)
initialize_then_create = [
call(api_key, domain, hostname),
call().create(auth_token)]
record.assert_has_calls(initialize_then_create)
def test_passes_record_id_to_printer_after_record_creation(
mocker, create_environment):
class FakeRecord(object):
def __init__(self, a, b, c): pass
def create(self, a): return 123456
mocker.patch('acmednsauth.authenticate.Record', new=FakeRecord)
stub_printer = mocker.patch('acmednsauth.authenticate.Printer')
Authenticate(environment=create_environment)
stub_printer.assert_has_calls([call(123456)])
| <commit_before>"""Test the DigitalOcean backed ACME DNS Authentication Class."""
from acmednsauth.authenticate import Authenticate
from mock import call
import pytest
@pytest.fixture()
def create_environment(api_key, domain, fqdn, auth_token):
return {
'DO_API_KEY': api_key,
'DO_DOMAIN': domain,
'CERTBOT_DOMAIN': fqdn,
'CERTBOT_VALIDATION': auth_token,
}
def test_valid_data_calls_record_creation_after_initialization(
mocker, api_key, hostname, domain, auth_token, create_environment):
record = mocker.patch('acmednsauth.authenticate.Record')
Authenticate(environment=create_environment)
initialize_then_create = [
call(api_key, domain, hostname),
call().create(auth_token)]
record.assert_has_calls(initialize_then_create)
def test_valid_data_writes_to_printer_after_record_creation(
mocker, create_environment):
class FakeRecord(object):
def __init__(self, a, b, c): pass
def create(self, a): return 123456
mocker.patch('acmednsauth.authenticate.Record', new=FakeRecord)
stub_printer = mocker.patch('acmednsauth.authenticate.Printer')
Authenticate(environment=create_environment)
stub_printer.assert_has_calls([call(123456)])
<commit_msg>Reword Test Names for Clarity
I didn't like how the test names were sounding. Hopefully this is
better.<commit_after> | """Test the DigitalOcean backed ACME DNS Authentication Class."""
from acmednsauth.authenticate import Authenticate
from mock import call
import pytest
@pytest.fixture()
def create_environment(api_key, domain, fqdn, auth_token):
return {
'DO_API_KEY': api_key,
'DO_DOMAIN': domain,
'CERTBOT_DOMAIN': fqdn,
'CERTBOT_VALIDATION': auth_token,
}
def test_triggering_of_record_creation_after_initialization(
mocker, api_key, hostname, domain, auth_token, create_environment):
record = mocker.patch('acmednsauth.authenticate.Record')
Authenticate(environment=create_environment)
initialize_then_create = [
call(api_key, domain, hostname),
call().create(auth_token)]
record.assert_has_calls(initialize_then_create)
def test_passes_record_id_to_printer_after_record_creation(
mocker, create_environment):
class FakeRecord(object):
def __init__(self, a, b, c): pass
def create(self, a): return 123456
mocker.patch('acmednsauth.authenticate.Record', new=FakeRecord)
stub_printer = mocker.patch('acmednsauth.authenticate.Printer')
Authenticate(environment=create_environment)
stub_printer.assert_has_calls([call(123456)])
| """Test the DigitalOcean backed ACME DNS Authentication Class."""
from acmednsauth.authenticate import Authenticate
from mock import call
import pytest
@pytest.fixture()
def create_environment(api_key, domain, fqdn, auth_token):
return {
'DO_API_KEY': api_key,
'DO_DOMAIN': domain,
'CERTBOT_DOMAIN': fqdn,
'CERTBOT_VALIDATION': auth_token,
}
def test_valid_data_calls_record_creation_after_initialization(
mocker, api_key, hostname, domain, auth_token, create_environment):
record = mocker.patch('acmednsauth.authenticate.Record')
Authenticate(environment=create_environment)
initialize_then_create = [
call(api_key, domain, hostname),
call().create(auth_token)]
record.assert_has_calls(initialize_then_create)
def test_valid_data_writes_to_printer_after_record_creation(
mocker, create_environment):
class FakeRecord(object):
def __init__(self, a, b, c): pass
def create(self, a): return 123456
mocker.patch('acmednsauth.authenticate.Record', new=FakeRecord)
stub_printer = mocker.patch('acmednsauth.authenticate.Printer')
Authenticate(environment=create_environment)
stub_printer.assert_has_calls([call(123456)])
Reword Test Names for Clarity
I didn't like how the test names were sounding. Hopefully this is
better."""Test the DigitalOcean backed ACME DNS Authentication Class."""
from acmednsauth.authenticate import Authenticate
from mock import call
import pytest
@pytest.fixture()
def create_environment(api_key, domain, fqdn, auth_token):
return {
'DO_API_KEY': api_key,
'DO_DOMAIN': domain,
'CERTBOT_DOMAIN': fqdn,
'CERTBOT_VALIDATION': auth_token,
}
def test_triggering_of_record_creation_after_initialization(
mocker, api_key, hostname, domain, auth_token, create_environment):
record = mocker.patch('acmednsauth.authenticate.Record')
Authenticate(environment=create_environment)
initialize_then_create = [
call(api_key, domain, hostname),
call().create(auth_token)]
record.assert_has_calls(initialize_then_create)
def test_passes_record_id_to_printer_after_record_creation(
mocker, create_environment):
class FakeRecord(object):
def __init__(self, a, b, c): pass
def create(self, a): return 123456
mocker.patch('acmednsauth.authenticate.Record', new=FakeRecord)
stub_printer = mocker.patch('acmednsauth.authenticate.Printer')
Authenticate(environment=create_environment)
stub_printer.assert_has_calls([call(123456)])
| <commit_before>"""Test the DigitalOcean backed ACME DNS Authentication Class."""
from acmednsauth.authenticate import Authenticate
from mock import call
import pytest
@pytest.fixture()
def create_environment(api_key, domain, fqdn, auth_token):
return {
'DO_API_KEY': api_key,
'DO_DOMAIN': domain,
'CERTBOT_DOMAIN': fqdn,
'CERTBOT_VALIDATION': auth_token,
}
def test_valid_data_calls_record_creation_after_initialization(
mocker, api_key, hostname, domain, auth_token, create_environment):
record = mocker.patch('acmednsauth.authenticate.Record')
Authenticate(environment=create_environment)
initialize_then_create = [
call(api_key, domain, hostname),
call().create(auth_token)]
record.assert_has_calls(initialize_then_create)
def test_valid_data_writes_to_printer_after_record_creation(
mocker, create_environment):
class FakeRecord(object):
def __init__(self, a, b, c): pass
def create(self, a): return 123456
mocker.patch('acmednsauth.authenticate.Record', new=FakeRecord)
stub_printer = mocker.patch('acmednsauth.authenticate.Printer')
Authenticate(environment=create_environment)
stub_printer.assert_has_calls([call(123456)])
<commit_msg>Reword Test Names for Clarity
I didn't like how the test names were sounding. Hopefully this is
better.<commit_after>"""Test the DigitalOcean backed ACME DNS Authentication Class."""
from acmednsauth.authenticate import Authenticate
from mock import call
import pytest
@pytest.fixture()
def create_environment(api_key, domain, fqdn, auth_token):
return {
'DO_API_KEY': api_key,
'DO_DOMAIN': domain,
'CERTBOT_DOMAIN': fqdn,
'CERTBOT_VALIDATION': auth_token,
}
def test_triggering_of_record_creation_after_initialization(
mocker, api_key, hostname, domain, auth_token, create_environment):
record = mocker.patch('acmednsauth.authenticate.Record')
Authenticate(environment=create_environment)
initialize_then_create = [
call(api_key, domain, hostname),
call().create(auth_token)]
record.assert_has_calls(initialize_then_create)
def test_passes_record_id_to_printer_after_record_creation(
mocker, create_environment):
class FakeRecord(object):
def __init__(self, a, b, c): pass
def create(self, a): return 123456
mocker.patch('acmednsauth.authenticate.Record', new=FakeRecord)
stub_printer = mocker.patch('acmednsauth.authenticate.Printer')
Authenticate(environment=create_environment)
stub_printer.assert_has_calls([call(123456)])
|
e75b79fb5dd614d117289acdab758c5c86b89e35 | update-database/stackdoc/questionimport.py | update-database/stackdoc/questionimport.py |
def import_question(posts, namespaces, upsert, id, title, body, tags, last_activity_date, last_updated_date, score, answers, has_accepted_answer):
namespaces_for_post = {}
for name, n in namespaces.items():
namespace_tags = n.get_tags()
if not(namespace_tags) or any(map(lambda x: x in tags, namespace_tags)):
ids = n.get_ids(title, body, tags)
for a in answers:
ids = list(set(ids) | set(n.get_ids(title, a["body"], tags)))
if len(ids) > 0:
ids = map(lambda x: x.lower(), ids)
namespaces_for_post[name] = ids
if len(namespaces_for_post):
post = {
"question_id": id,
"url": "http://stackoverflow.com/questions/%s" % id,
"namespaces": namespaces_for_post,
"title": title,
"score": int(score),
"accepted_answer": has_accepted_answer,
"last_activity": last_activity_date,
"last_updated": last_updated_date
}
if upsert:
posts.update({"question_id": id}, post, True)
else:
posts.insert(post)
print "Processed %s question from %s (%s)" % (", ".join(namespaces_for_post.keys()), str(last_activity_date), id)
|
def import_question(posts, namespaces, upsert, id, title, body, tags, last_activity_date, last_updated_date, score, answers, has_accepted_answer):
namespaces_for_post = {}
for name, n in namespaces.items():
namespace_tags = n.get_tags()
if not(namespace_tags) or any(map(lambda x: x in tags, namespace_tags)):
ids = n.get_ids(title, body, tags)
for a in answers:
ids = list(set(ids) | set(n.get_ids(title, a["body"], tags)))
if len(ids) > 0:
ids = map(lambda x: x.lower(), ids)
namespaces_for_post[name] = ids
if len(namespaces_for_post):
post = {
"question_id": id,
"url": "http://stackoverflow.com/questions/%s" % id,
"namespaces": namespaces_for_post,
"title": title,
"score": int(score),
"answers": len(answers),
"accepted_answer": has_accepted_answer,
"last_activity": last_activity_date,
"last_updated": last_updated_date
}
if upsert:
posts.update({"question_id": id}, post, True)
else:
posts.insert(post)
print "Processed %s question from %s (%s)" % (", ".join(namespaces_for_post.keys()), str(last_activity_date), id)
| Include answer count in stored data. | Include answer count in stored data.
| Python | bsd-3-clause | alnorth/stackdoc,alnorth/stackdoc,alnorth/stackdoc |
def import_question(posts, namespaces, upsert, id, title, body, tags, last_activity_date, last_updated_date, score, answers, has_accepted_answer):
namespaces_for_post = {}
for name, n in namespaces.items():
namespace_tags = n.get_tags()
if not(namespace_tags) or any(map(lambda x: x in tags, namespace_tags)):
ids = n.get_ids(title, body, tags)
for a in answers:
ids = list(set(ids) | set(n.get_ids(title, a["body"], tags)))
if len(ids) > 0:
ids = map(lambda x: x.lower(), ids)
namespaces_for_post[name] = ids
if len(namespaces_for_post):
post = {
"question_id": id,
"url": "http://stackoverflow.com/questions/%s" % id,
"namespaces": namespaces_for_post,
"title": title,
"score": int(score),
"accepted_answer": has_accepted_answer,
"last_activity": last_activity_date,
"last_updated": last_updated_date
}
if upsert:
posts.update({"question_id": id}, post, True)
else:
posts.insert(post)
print "Processed %s question from %s (%s)" % (", ".join(namespaces_for_post.keys()), str(last_activity_date), id)
Include answer count in stored data. |
def import_question(posts, namespaces, upsert, id, title, body, tags, last_activity_date, last_updated_date, score, answers, has_accepted_answer):
namespaces_for_post = {}
for name, n in namespaces.items():
namespace_tags = n.get_tags()
if not(namespace_tags) or any(map(lambda x: x in tags, namespace_tags)):
ids = n.get_ids(title, body, tags)
for a in answers:
ids = list(set(ids) | set(n.get_ids(title, a["body"], tags)))
if len(ids) > 0:
ids = map(lambda x: x.lower(), ids)
namespaces_for_post[name] = ids
if len(namespaces_for_post):
post = {
"question_id": id,
"url": "http://stackoverflow.com/questions/%s" % id,
"namespaces": namespaces_for_post,
"title": title,
"score": int(score),
"answers": len(answers),
"accepted_answer": has_accepted_answer,
"last_activity": last_activity_date,
"last_updated": last_updated_date
}
if upsert:
posts.update({"question_id": id}, post, True)
else:
posts.insert(post)
print "Processed %s question from %s (%s)" % (", ".join(namespaces_for_post.keys()), str(last_activity_date), id)
| <commit_before>
def import_question(posts, namespaces, upsert, id, title, body, tags, last_activity_date, last_updated_date, score, answers, has_accepted_answer):
namespaces_for_post = {}
for name, n in namespaces.items():
namespace_tags = n.get_tags()
if not(namespace_tags) or any(map(lambda x: x in tags, namespace_tags)):
ids = n.get_ids(title, body, tags)
for a in answers:
ids = list(set(ids) | set(n.get_ids(title, a["body"], tags)))
if len(ids) > 0:
ids = map(lambda x: x.lower(), ids)
namespaces_for_post[name] = ids
if len(namespaces_for_post):
post = {
"question_id": id,
"url": "http://stackoverflow.com/questions/%s" % id,
"namespaces": namespaces_for_post,
"title": title,
"score": int(score),
"accepted_answer": has_accepted_answer,
"last_activity": last_activity_date,
"last_updated": last_updated_date
}
if upsert:
posts.update({"question_id": id}, post, True)
else:
posts.insert(post)
print "Processed %s question from %s (%s)" % (", ".join(namespaces_for_post.keys()), str(last_activity_date), id)
<commit_msg>Include answer count in stored data.<commit_after> |
def import_question(posts, namespaces, upsert, id, title, body, tags, last_activity_date, last_updated_date, score, answers, has_accepted_answer):
namespaces_for_post = {}
for name, n in namespaces.items():
namespace_tags = n.get_tags()
if not(namespace_tags) or any(map(lambda x: x in tags, namespace_tags)):
ids = n.get_ids(title, body, tags)
for a in answers:
ids = list(set(ids) | set(n.get_ids(title, a["body"], tags)))
if len(ids) > 0:
ids = map(lambda x: x.lower(), ids)
namespaces_for_post[name] = ids
if len(namespaces_for_post):
post = {
"question_id": id,
"url": "http://stackoverflow.com/questions/%s" % id,
"namespaces": namespaces_for_post,
"title": title,
"score": int(score),
"answers": len(answers),
"accepted_answer": has_accepted_answer,
"last_activity": last_activity_date,
"last_updated": last_updated_date
}
if upsert:
posts.update({"question_id": id}, post, True)
else:
posts.insert(post)
print "Processed %s question from %s (%s)" % (", ".join(namespaces_for_post.keys()), str(last_activity_date), id)
|
def import_question(posts, namespaces, upsert, id, title, body, tags, last_activity_date, last_updated_date, score, answers, has_accepted_answer):
namespaces_for_post = {}
for name, n in namespaces.items():
namespace_tags = n.get_tags()
if not(namespace_tags) or any(map(lambda x: x in tags, namespace_tags)):
ids = n.get_ids(title, body, tags)
for a in answers:
ids = list(set(ids) | set(n.get_ids(title, a["body"], tags)))
if len(ids) > 0:
ids = map(lambda x: x.lower(), ids)
namespaces_for_post[name] = ids
if len(namespaces_for_post):
post = {
"question_id": id,
"url": "http://stackoverflow.com/questions/%s" % id,
"namespaces": namespaces_for_post,
"title": title,
"score": int(score),
"accepted_answer": has_accepted_answer,
"last_activity": last_activity_date,
"last_updated": last_updated_date
}
if upsert:
posts.update({"question_id": id}, post, True)
else:
posts.insert(post)
print "Processed %s question from %s (%s)" % (", ".join(namespaces_for_post.keys()), str(last_activity_date), id)
Include answer count in stored data.
def import_question(posts, namespaces, upsert, id, title, body, tags, last_activity_date, last_updated_date, score, answers, has_accepted_answer):
namespaces_for_post = {}
for name, n in namespaces.items():
namespace_tags = n.get_tags()
if not(namespace_tags) or any(map(lambda x: x in tags, namespace_tags)):
ids = n.get_ids(title, body, tags)
for a in answers:
ids = list(set(ids) | set(n.get_ids(title, a["body"], tags)))
if len(ids) > 0:
ids = map(lambda x: x.lower(), ids)
namespaces_for_post[name] = ids
if len(namespaces_for_post):
post = {
"question_id": id,
"url": "http://stackoverflow.com/questions/%s" % id,
"namespaces": namespaces_for_post,
"title": title,
"score": int(score),
"answers": len(answers),
"accepted_answer": has_accepted_answer,
"last_activity": last_activity_date,
"last_updated": last_updated_date
}
if upsert:
posts.update({"question_id": id}, post, True)
else:
posts.insert(post)
print "Processed %s question from %s (%s)" % (", ".join(namespaces_for_post.keys()), str(last_activity_date), id)
| <commit_before>
def import_question(posts, namespaces, upsert, id, title, body, tags, last_activity_date, last_updated_date, score, answers, has_accepted_answer):
namespaces_for_post = {}
for name, n in namespaces.items():
namespace_tags = n.get_tags()
if not(namespace_tags) or any(map(lambda x: x in tags, namespace_tags)):
ids = n.get_ids(title, body, tags)
for a in answers:
ids = list(set(ids) | set(n.get_ids(title, a["body"], tags)))
if len(ids) > 0:
ids = map(lambda x: x.lower(), ids)
namespaces_for_post[name] = ids
if len(namespaces_for_post):
post = {
"question_id": id,
"url": "http://stackoverflow.com/questions/%s" % id,
"namespaces": namespaces_for_post,
"title": title,
"score": int(score),
"accepted_answer": has_accepted_answer,
"last_activity": last_activity_date,
"last_updated": last_updated_date
}
if upsert:
posts.update({"question_id": id}, post, True)
else:
posts.insert(post)
print "Processed %s question from %s (%s)" % (", ".join(namespaces_for_post.keys()), str(last_activity_date), id)
<commit_msg>Include answer count in stored data.<commit_after>
def import_question(posts, namespaces, upsert, id, title, body, tags, last_activity_date, last_updated_date, score, answers, has_accepted_answer):
namespaces_for_post = {}
for name, n in namespaces.items():
namespace_tags = n.get_tags()
if not(namespace_tags) or any(map(lambda x: x in tags, namespace_tags)):
ids = n.get_ids(title, body, tags)
for a in answers:
ids = list(set(ids) | set(n.get_ids(title, a["body"], tags)))
if len(ids) > 0:
ids = map(lambda x: x.lower(), ids)
namespaces_for_post[name] = ids
if len(namespaces_for_post):
post = {
"question_id": id,
"url": "http://stackoverflow.com/questions/%s" % id,
"namespaces": namespaces_for_post,
"title": title,
"score": int(score),
"answers": len(answers),
"accepted_answer": has_accepted_answer,
"last_activity": last_activity_date,
"last_updated": last_updated_date
}
if upsert:
posts.update({"question_id": id}, post, True)
else:
posts.insert(post)
print "Processed %s question from %s (%s)" % (", ".join(namespaces_for_post.keys()), str(last_activity_date), id)
|
bd4812a1ef93c51bedbc92e8064b3457b5d88992 | tests/test_slice.py | tests/test_slice.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# (c) 2015-2018, ETH Zurich, Institut fuer Theoretische Physik
# Author: Dominik Gresch <greschd@gmx.ch>
import pytest
import numpy as np
from parameters import T_VALUES, KPT
@pytest.mark.parametrize('slice_idx', [(0, 1), [1, 0], (0, ), (1, )])
@pytest.mark.parametrize('t', T_VALUES)
def test_slice(t, get_model, slice_idx):
m1 = get_model(*t)
m2 = m1.slice_orbitals(slice_idx)
assert np.isclose([m1.pos[i] for i in slice_idx], m2.pos).all()
for k in KPT:
assert np.isclose(m1.hamilton(k)[np.ix_(slice_idx, slice_idx)], m2.hamilton(k)).all()
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
# (c) 2015-2018, ETH Zurich, Institut fuer Theoretische Physik
# Author: Dominik Gresch <greschd@gmx.ch>
"""Tests for the model slicing functionality."""
import pytest
import numpy as np
from parameters import T_VALUES, KPT
@pytest.mark.parametrize('slice_idx', [(0, 1), [1, 0], (0, ), (1, )])
@pytest.mark.parametrize('t', T_VALUES)
def test_slice(t, get_model, slice_idx):
"""Check the slicing method."""
model = get_model(*t)
model_sliced = model.slice_orbitals(slice_idx)
assert np.isclose([model.pos[i] for i in slice_idx], model_sliced.pos).all()
for k in KPT:
assert np.isclose(model.hamilton(k)[np.ix_(slice_idx, slice_idx)], model_sliced.hamilton(k)).all()
| Fix pre-commit for slicing method. | Fix pre-commit for slicing method.
| Python | apache-2.0 | Z2PackDev/TBmodels,Z2PackDev/TBmodels | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# (c) 2015-2018, ETH Zurich, Institut fuer Theoretische Physik
# Author: Dominik Gresch <greschd@gmx.ch>
import pytest
import numpy as np
from parameters import T_VALUES, KPT
@pytest.mark.parametrize('slice_idx', [(0, 1), [1, 0], (0, ), (1, )])
@pytest.mark.parametrize('t', T_VALUES)
def test_slice(t, get_model, slice_idx):
m1 = get_model(*t)
m2 = m1.slice_orbitals(slice_idx)
assert np.isclose([m1.pos[i] for i in slice_idx], m2.pos).all()
for k in KPT:
assert np.isclose(m1.hamilton(k)[np.ix_(slice_idx, slice_idx)], m2.hamilton(k)).all()
Fix pre-commit for slicing method. | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# (c) 2015-2018, ETH Zurich, Institut fuer Theoretische Physik
# Author: Dominik Gresch <greschd@gmx.ch>
"""Tests for the model slicing functionality."""
import pytest
import numpy as np
from parameters import T_VALUES, KPT
@pytest.mark.parametrize('slice_idx', [(0, 1), [1, 0], (0, ), (1, )])
@pytest.mark.parametrize('t', T_VALUES)
def test_slice(t, get_model, slice_idx):
"""Check the slicing method."""
model = get_model(*t)
model_sliced = model.slice_orbitals(slice_idx)
assert np.isclose([model.pos[i] for i in slice_idx], model_sliced.pos).all()
for k in KPT:
assert np.isclose(model.hamilton(k)[np.ix_(slice_idx, slice_idx)], model_sliced.hamilton(k)).all()
| <commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# (c) 2015-2018, ETH Zurich, Institut fuer Theoretische Physik
# Author: Dominik Gresch <greschd@gmx.ch>
import pytest
import numpy as np
from parameters import T_VALUES, KPT
@pytest.mark.parametrize('slice_idx', [(0, 1), [1, 0], (0, ), (1, )])
@pytest.mark.parametrize('t', T_VALUES)
def test_slice(t, get_model, slice_idx):
m1 = get_model(*t)
m2 = m1.slice_orbitals(slice_idx)
assert np.isclose([m1.pos[i] for i in slice_idx], m2.pos).all()
for k in KPT:
assert np.isclose(m1.hamilton(k)[np.ix_(slice_idx, slice_idx)], m2.hamilton(k)).all()
<commit_msg>Fix pre-commit for slicing method.<commit_after> | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# (c) 2015-2018, ETH Zurich, Institut fuer Theoretische Physik
# Author: Dominik Gresch <greschd@gmx.ch>
"""Tests for the model slicing functionality."""
import pytest
import numpy as np
from parameters import T_VALUES, KPT
@pytest.mark.parametrize('slice_idx', [(0, 1), [1, 0], (0, ), (1, )])
@pytest.mark.parametrize('t', T_VALUES)
def test_slice(t, get_model, slice_idx):
"""Check the slicing method."""
model = get_model(*t)
model_sliced = model.slice_orbitals(slice_idx)
assert np.isclose([model.pos[i] for i in slice_idx], model_sliced.pos).all()
for k in KPT:
assert np.isclose(model.hamilton(k)[np.ix_(slice_idx, slice_idx)], model_sliced.hamilton(k)).all()
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
# (c) 2015-2018, ETH Zurich, Institut fuer Theoretische Physik
# Author: Dominik Gresch <greschd@gmx.ch>
import pytest
import numpy as np
from parameters import T_VALUES, KPT
@pytest.mark.parametrize('slice_idx', [(0, 1), [1, 0], (0, ), (1, )])
@pytest.mark.parametrize('t', T_VALUES)
def test_slice(t, get_model, slice_idx):
m1 = get_model(*t)
m2 = m1.slice_orbitals(slice_idx)
assert np.isclose([m1.pos[i] for i in slice_idx], m2.pos).all()
for k in KPT:
assert np.isclose(m1.hamilton(k)[np.ix_(slice_idx, slice_idx)], m2.hamilton(k)).all()
Fix pre-commit for slicing method.#!/usr/bin/env python
# -*- coding: utf-8 -*-
# (c) 2015-2018, ETH Zurich, Institut fuer Theoretische Physik
# Author: Dominik Gresch <greschd@gmx.ch>
"""Tests for the model slicing functionality."""
import pytest
import numpy as np
from parameters import T_VALUES, KPT
@pytest.mark.parametrize('slice_idx', [(0, 1), [1, 0], (0, ), (1, )])
@pytest.mark.parametrize('t', T_VALUES)
def test_slice(t, get_model, slice_idx):
"""Check the slicing method."""
model = get_model(*t)
model_sliced = model.slice_orbitals(slice_idx)
assert np.isclose([model.pos[i] for i in slice_idx], model_sliced.pos).all()
for k in KPT:
assert np.isclose(model.hamilton(k)[np.ix_(slice_idx, slice_idx)], model_sliced.hamilton(k)).all()
| <commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# (c) 2015-2018, ETH Zurich, Institut fuer Theoretische Physik
# Author: Dominik Gresch <greschd@gmx.ch>
import pytest
import numpy as np
from parameters import T_VALUES, KPT
@pytest.mark.parametrize('slice_idx', [(0, 1), [1, 0], (0, ), (1, )])
@pytest.mark.parametrize('t', T_VALUES)
def test_slice(t, get_model, slice_idx):
m1 = get_model(*t)
m2 = m1.slice_orbitals(slice_idx)
assert np.isclose([m1.pos[i] for i in slice_idx], m2.pos).all()
for k in KPT:
assert np.isclose(m1.hamilton(k)[np.ix_(slice_idx, slice_idx)], m2.hamilton(k)).all()
<commit_msg>Fix pre-commit for slicing method.<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# (c) 2015-2018, ETH Zurich, Institut fuer Theoretische Physik
# Author: Dominik Gresch <greschd@gmx.ch>
"""Tests for the model slicing functionality."""
import pytest
import numpy as np
from parameters import T_VALUES, KPT
@pytest.mark.parametrize('slice_idx', [(0, 1), [1, 0], (0, ), (1, )])
@pytest.mark.parametrize('t', T_VALUES)
def test_slice(t, get_model, slice_idx):
"""Check the slicing method."""
model = get_model(*t)
model_sliced = model.slice_orbitals(slice_idx)
assert np.isclose([model.pos[i] for i in slice_idx], model_sliced.pos).all()
for k in KPT:
assert np.isclose(model.hamilton(k)[np.ix_(slice_idx, slice_idx)], model_sliced.hamilton(k)).all()
|
d07e1c020185fb118b628674234c4a1ebcc11836 | binder/config.py | binder/config.py | c.ServerProxy.servers = {
'lab-dev': {
'command': [
'jupyter',
'lab',
'--no-browser',
'--dev-mode',
'--port={port}',
'--NotebookApp.token=""',
]
}
}
c.NotebookApp.default_url = '/lab-dev'
| c.ServerProxy.servers = {
'lab-dev': {
'command': [
'jupyter',
'lab',
'--no-browser',
'--dev-mode',
'--port={port}',
'--NotebookApp.token=""',
'--NotebookApp.base_url={base_url}/lab-dev'
]
}
}
c.NotebookApp.default_url = '/lab-dev'
| Set base_url for dev version of lab | Set base_url for dev version of lab | Python | bsd-3-clause | jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab | c.ServerProxy.servers = {
'lab-dev': {
'command': [
'jupyter',
'lab',
'--no-browser',
'--dev-mode',
'--port={port}',
'--NotebookApp.token=""',
]
}
}
c.NotebookApp.default_url = '/lab-dev'
Set base_url for dev version of lab | c.ServerProxy.servers = {
'lab-dev': {
'command': [
'jupyter',
'lab',
'--no-browser',
'--dev-mode',
'--port={port}',
'--NotebookApp.token=""',
'--NotebookApp.base_url={base_url}/lab-dev'
]
}
}
c.NotebookApp.default_url = '/lab-dev'
| <commit_before>c.ServerProxy.servers = {
'lab-dev': {
'command': [
'jupyter',
'lab',
'--no-browser',
'--dev-mode',
'--port={port}',
'--NotebookApp.token=""',
]
}
}
c.NotebookApp.default_url = '/lab-dev'
<commit_msg>Set base_url for dev version of lab<commit_after> | c.ServerProxy.servers = {
'lab-dev': {
'command': [
'jupyter',
'lab',
'--no-browser',
'--dev-mode',
'--port={port}',
'--NotebookApp.token=""',
'--NotebookApp.base_url={base_url}/lab-dev'
]
}
}
c.NotebookApp.default_url = '/lab-dev'
| c.ServerProxy.servers = {
'lab-dev': {
'command': [
'jupyter',
'lab',
'--no-browser',
'--dev-mode',
'--port={port}',
'--NotebookApp.token=""',
]
}
}
c.NotebookApp.default_url = '/lab-dev'
Set base_url for dev version of labc.ServerProxy.servers = {
'lab-dev': {
'command': [
'jupyter',
'lab',
'--no-browser',
'--dev-mode',
'--port={port}',
'--NotebookApp.token=""',
'--NotebookApp.base_url={base_url}/lab-dev'
]
}
}
c.NotebookApp.default_url = '/lab-dev'
| <commit_before>c.ServerProxy.servers = {
'lab-dev': {
'command': [
'jupyter',
'lab',
'--no-browser',
'--dev-mode',
'--port={port}',
'--NotebookApp.token=""',
]
}
}
c.NotebookApp.default_url = '/lab-dev'
<commit_msg>Set base_url for dev version of lab<commit_after>c.ServerProxy.servers = {
'lab-dev': {
'command': [
'jupyter',
'lab',
'--no-browser',
'--dev-mode',
'--port={port}',
'--NotebookApp.token=""',
'--NotebookApp.base_url={base_url}/lab-dev'
]
}
}
c.NotebookApp.default_url = '/lab-dev'
|
ffc4d6db188b9ad8ece655c8221f2e5a34e7c66b | main.py | main.py | """
pyMonitor first Version
Written By :Ahmed Alkabir
"""
#!/usr/bin/python3
import main_ui as Ui
import sys
# Main Thread of Program
def main():
app = Ui.QtWidgets.QApplication(sys.argv)
main_window = Ui.QtWidgets.QMainWindow()
ui = Ui.Ui_window(main_window)
main_window.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main() | """
pyMonitor first Version
Written By :Ahmed Alkabir
"""
#!/usr/bin/python3
import main_ui as Ui
import sys
# Main Thread of Program
def main():
if float(sys.version[:3]) >= 3.3:
app = Ui.QtWidgets.QApplication(sys.argv)
main_window = Ui.QtWidgets.QMainWindow()
ui = Ui.Ui_window(main_window)
main_window.show()
sys.exit(app.exec_())
else:
print('Sorry Bro minimum requirement is 3.3')
if __name__ == "__main__":
main() | Check Verison of Python Interpreter | Check Verison of Python Interpreter
| Python | mit | ahmedalkabir/pyMonitor | """
pyMonitor first Version
Written By :Ahmed Alkabir
"""
#!/usr/bin/python3
import main_ui as Ui
import sys
# Main Thread of Program
def main():
app = Ui.QtWidgets.QApplication(sys.argv)
main_window = Ui.QtWidgets.QMainWindow()
ui = Ui.Ui_window(main_window)
main_window.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()Check Verison of Python Interpreter | """
pyMonitor first Version
Written By :Ahmed Alkabir
"""
#!/usr/bin/python3
import main_ui as Ui
import sys
# Main Thread of Program
def main():
if float(sys.version[:3]) >= 3.3:
app = Ui.QtWidgets.QApplication(sys.argv)
main_window = Ui.QtWidgets.QMainWindow()
ui = Ui.Ui_window(main_window)
main_window.show()
sys.exit(app.exec_())
else:
print('Sorry Bro minimum requirement is 3.3')
if __name__ == "__main__":
main() | <commit_before>"""
pyMonitor first Version
Written By :Ahmed Alkabir
"""
#!/usr/bin/python3
import main_ui as Ui
import sys
# Main Thread of Program
def main():
app = Ui.QtWidgets.QApplication(sys.argv)
main_window = Ui.QtWidgets.QMainWindow()
ui = Ui.Ui_window(main_window)
main_window.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()<commit_msg>Check Verison of Python Interpreter<commit_after> | """
pyMonitor first Version
Written By :Ahmed Alkabir
"""
#!/usr/bin/python3
import main_ui as Ui
import sys
# Main Thread of Program
def main():
if float(sys.version[:3]) >= 3.3:
app = Ui.QtWidgets.QApplication(sys.argv)
main_window = Ui.QtWidgets.QMainWindow()
ui = Ui.Ui_window(main_window)
main_window.show()
sys.exit(app.exec_())
else:
print('Sorry Bro minimum requirement is 3.3')
if __name__ == "__main__":
main() | """
pyMonitor first Version
Written By :Ahmed Alkabir
"""
#!/usr/bin/python3
import main_ui as Ui
import sys
# Main Thread of Program
def main():
app = Ui.QtWidgets.QApplication(sys.argv)
main_window = Ui.QtWidgets.QMainWindow()
ui = Ui.Ui_window(main_window)
main_window.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()Check Verison of Python Interpreter"""
pyMonitor first Version
Written By :Ahmed Alkabir
"""
#!/usr/bin/python3
import main_ui as Ui
import sys
# Main Thread of Program
def main():
if float(sys.version[:3]) >= 3.3:
app = Ui.QtWidgets.QApplication(sys.argv)
main_window = Ui.QtWidgets.QMainWindow()
ui = Ui.Ui_window(main_window)
main_window.show()
sys.exit(app.exec_())
else:
print('Sorry Bro minimum requirement is 3.3')
if __name__ == "__main__":
main() | <commit_before>"""
pyMonitor first Version
Written By :Ahmed Alkabir
"""
#!/usr/bin/python3
import main_ui as Ui
import sys
# Main Thread of Program
def main():
app = Ui.QtWidgets.QApplication(sys.argv)
main_window = Ui.QtWidgets.QMainWindow()
ui = Ui.Ui_window(main_window)
main_window.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()<commit_msg>Check Verison of Python Interpreter<commit_after>"""
pyMonitor first Version
Written By :Ahmed Alkabir
"""
#!/usr/bin/python3
import main_ui as Ui
import sys
# Main Thread of Program
def main():
if float(sys.version[:3]) >= 3.3:
app = Ui.QtWidgets.QApplication(sys.argv)
main_window = Ui.QtWidgets.QMainWindow()
ui = Ui.Ui_window(main_window)
main_window.show()
sys.exit(app.exec_())
else:
print('Sorry Bro minimum requirement is 3.3')
if __name__ == "__main__":
main() |
2abb0ff8d8f57ca1ae05e0abfc17bdcbbc758e19 | main.py | main.py | #!/usr/bin/env python
import phiface
sc = phiface.Context()
yloc = 30
for weight in [1, 3, 6, 10]:
xloc = 30
A = phiface.AGlyph(x=xloc, y=yloc)
xloc += A.width() + 40
E = phiface.EGlyph(x=xloc, y=yloc)
xloc += E.width() + 20
I = phiface.IGlyph(x=xloc, y=yloc)
xloc += I.width() + 20
T = phiface.TGlyph(x=xloc, y=yloc)
A.w = E.w = I.w = T.w = weight
sc.draw([A, E, I, T])
yloc += A.capHeight() + 20
sc.write("output.png") | #!/usr/bin/env python
import phiface
sc = phiface.Context()
yloc = 30
for weight in [1, 3, 6, 10]:
xloc = 30
A = phiface.AGlyph(x=xloc, y=yloc)
xloc += A.width() + 40
E = phiface.EGlyph(x=xloc, y=yloc)
xloc += E.width() + 20
I = phiface.IGlyph(x=xloc, y=yloc)
xloc += I.width() + 20
T = phiface.TGlyph(x=xloc, y=yloc)
A.w = E.w = I.w = T.w = (weight * (A.capHeight() / 150.0))
sc.draw([A, E, I, T])
yloc += A.capHeight() + 20
sc.write("output.png") | Change weight rendering based on capHeight | Change weight rendering based on capHeight
| Python | bsd-2-clause | hortont424/phiface | #!/usr/bin/env python
import phiface
sc = phiface.Context()
yloc = 30
for weight in [1, 3, 6, 10]:
xloc = 30
A = phiface.AGlyph(x=xloc, y=yloc)
xloc += A.width() + 40
E = phiface.EGlyph(x=xloc, y=yloc)
xloc += E.width() + 20
I = phiface.IGlyph(x=xloc, y=yloc)
xloc += I.width() + 20
T = phiface.TGlyph(x=xloc, y=yloc)
A.w = E.w = I.w = T.w = weight
sc.draw([A, E, I, T])
yloc += A.capHeight() + 20
sc.write("output.png")Change weight rendering based on capHeight | #!/usr/bin/env python
import phiface
sc = phiface.Context()
yloc = 30
for weight in [1, 3, 6, 10]:
xloc = 30
A = phiface.AGlyph(x=xloc, y=yloc)
xloc += A.width() + 40
E = phiface.EGlyph(x=xloc, y=yloc)
xloc += E.width() + 20
I = phiface.IGlyph(x=xloc, y=yloc)
xloc += I.width() + 20
T = phiface.TGlyph(x=xloc, y=yloc)
A.w = E.w = I.w = T.w = (weight * (A.capHeight() / 150.0))
sc.draw([A, E, I, T])
yloc += A.capHeight() + 20
sc.write("output.png") | <commit_before>#!/usr/bin/env python
import phiface
sc = phiface.Context()
yloc = 30
for weight in [1, 3, 6, 10]:
xloc = 30
A = phiface.AGlyph(x=xloc, y=yloc)
xloc += A.width() + 40
E = phiface.EGlyph(x=xloc, y=yloc)
xloc += E.width() + 20
I = phiface.IGlyph(x=xloc, y=yloc)
xloc += I.width() + 20
T = phiface.TGlyph(x=xloc, y=yloc)
A.w = E.w = I.w = T.w = weight
sc.draw([A, E, I, T])
yloc += A.capHeight() + 20
sc.write("output.png")<commit_msg>Change weight rendering based on capHeight<commit_after> | #!/usr/bin/env python
import phiface
sc = phiface.Context()
yloc = 30
for weight in [1, 3, 6, 10]:
xloc = 30
A = phiface.AGlyph(x=xloc, y=yloc)
xloc += A.width() + 40
E = phiface.EGlyph(x=xloc, y=yloc)
xloc += E.width() + 20
I = phiface.IGlyph(x=xloc, y=yloc)
xloc += I.width() + 20
T = phiface.TGlyph(x=xloc, y=yloc)
A.w = E.w = I.w = T.w = (weight * (A.capHeight() / 150.0))
sc.draw([A, E, I, T])
yloc += A.capHeight() + 20
sc.write("output.png") | #!/usr/bin/env python
import phiface
sc = phiface.Context()
yloc = 30
for weight in [1, 3, 6, 10]:
xloc = 30
A = phiface.AGlyph(x=xloc, y=yloc)
xloc += A.width() + 40
E = phiface.EGlyph(x=xloc, y=yloc)
xloc += E.width() + 20
I = phiface.IGlyph(x=xloc, y=yloc)
xloc += I.width() + 20
T = phiface.TGlyph(x=xloc, y=yloc)
A.w = E.w = I.w = T.w = weight
sc.draw([A, E, I, T])
yloc += A.capHeight() + 20
sc.write("output.png")Change weight rendering based on capHeight#!/usr/bin/env python
import phiface
sc = phiface.Context()
yloc = 30
for weight in [1, 3, 6, 10]:
xloc = 30
A = phiface.AGlyph(x=xloc, y=yloc)
xloc += A.width() + 40
E = phiface.EGlyph(x=xloc, y=yloc)
xloc += E.width() + 20
I = phiface.IGlyph(x=xloc, y=yloc)
xloc += I.width() + 20
T = phiface.TGlyph(x=xloc, y=yloc)
A.w = E.w = I.w = T.w = (weight * (A.capHeight() / 150.0))
sc.draw([A, E, I, T])
yloc += A.capHeight() + 20
sc.write("output.png") | <commit_before>#!/usr/bin/env python
import phiface
sc = phiface.Context()
yloc = 30
for weight in [1, 3, 6, 10]:
xloc = 30
A = phiface.AGlyph(x=xloc, y=yloc)
xloc += A.width() + 40
E = phiface.EGlyph(x=xloc, y=yloc)
xloc += E.width() + 20
I = phiface.IGlyph(x=xloc, y=yloc)
xloc += I.width() + 20
T = phiface.TGlyph(x=xloc, y=yloc)
A.w = E.w = I.w = T.w = weight
sc.draw([A, E, I, T])
yloc += A.capHeight() + 20
sc.write("output.png")<commit_msg>Change weight rendering based on capHeight<commit_after>#!/usr/bin/env python
import phiface
sc = phiface.Context()
yloc = 30
for weight in [1, 3, 6, 10]:
xloc = 30
A = phiface.AGlyph(x=xloc, y=yloc)
xloc += A.width() + 40
E = phiface.EGlyph(x=xloc, y=yloc)
xloc += E.width() + 20
I = phiface.IGlyph(x=xloc, y=yloc)
xloc += I.width() + 20
T = phiface.TGlyph(x=xloc, y=yloc)
A.w = E.w = I.w = T.w = (weight * (A.capHeight() / 150.0))
sc.draw([A, E, I, T])
yloc += A.capHeight() + 20
sc.write("output.png") |
36c4e01f5bfb6ba00bd018f5bca4e8652a63ca8d | main.py | main.py | #!/usr/bin/env python3
"""TODO:
* more flexible sorting options
* use -o to specify output file
* check more explicitly for errors in JSON files
"""
import json, sys
if len(sys.argv) > 1:
inFn = sys.argv[1]
with open(inFn, 'r') as f:
try:
defs = json.load(f)
except:
sys.exit('{} has a syntax error'.format(inFn))
sort = sorted(defs, key=str.lower)
print('# My Dictionary')
print('\n## Definitions')
curLetter = None
for k in sort:
l = k[0].upper()
if curLetter != l:
curLetter = l
print('\n### {}'.format(curLetter))
word = k[0].upper() + k[1:]
print('* *{}* - {}'.format(word, defs[k]))
| #!/usr/bin/env python3
"""TODO:
* more flexible sorting options
* use -o to specify output file
"""
import json, sys
if len(sys.argv) > 1:
inFn = sys.argv[1]
with open(inFn, 'r') as f:
try:
defs = json.load(f)
except ValueError as e:
sys.exit('ValueError in {}: {}'.format(inFn, e))
sort = sorted(defs, key=str.lower)
print('# My Dictionary')
print('\n## Definitions')
curLetter = None
for k in sort:
l = k[0].upper()
if curLetter != l:
curLetter = l
print('\n### {}'.format(curLetter))
word = k[0].upper() + k[1:]
print('* *{}* - {}'.format(word, defs[k]))
| Print more explicit error reports for input file parsing | Print more explicit error reports for input file parsing
| Python | mit | JoshuaBrockschmidt/dictbuilder | #!/usr/bin/env python3
"""TODO:
* more flexible sorting options
* use -o to specify output file
* check more explicitly for errors in JSON files
"""
import json, sys
if len(sys.argv) > 1:
inFn = sys.argv[1]
with open(inFn, 'r') as f:
try:
defs = json.load(f)
except:
sys.exit('{} has a syntax error'.format(inFn))
sort = sorted(defs, key=str.lower)
print('# My Dictionary')
print('\n## Definitions')
curLetter = None
for k in sort:
l = k[0].upper()
if curLetter != l:
curLetter = l
print('\n### {}'.format(curLetter))
word = k[0].upper() + k[1:]
print('* *{}* - {}'.format(word, defs[k]))
Print more explicit error reports for input file parsing | #!/usr/bin/env python3
"""TODO:
* more flexible sorting options
* use -o to specify output file
"""
import json, sys
if len(sys.argv) > 1:
inFn = sys.argv[1]
with open(inFn, 'r') as f:
try:
defs = json.load(f)
except ValueError as e:
sys.exit('ValueError in {}: {}'.format(inFn, e))
sort = sorted(defs, key=str.lower)
print('# My Dictionary')
print('\n## Definitions')
curLetter = None
for k in sort:
l = k[0].upper()
if curLetter != l:
curLetter = l
print('\n### {}'.format(curLetter))
word = k[0].upper() + k[1:]
print('* *{}* - {}'.format(word, defs[k]))
| <commit_before>#!/usr/bin/env python3
"""TODO:
* more flexible sorting options
* use -o to specify output file
* check more explicitly for errors in JSON files
"""
import json, sys
if len(sys.argv) > 1:
inFn = sys.argv[1]
with open(inFn, 'r') as f:
try:
defs = json.load(f)
except:
sys.exit('{} has a syntax error'.format(inFn))
sort = sorted(defs, key=str.lower)
print('# My Dictionary')
print('\n## Definitions')
curLetter = None
for k in sort:
l = k[0].upper()
if curLetter != l:
curLetter = l
print('\n### {}'.format(curLetter))
word = k[0].upper() + k[1:]
print('* *{}* - {}'.format(word, defs[k]))
<commit_msg>Print more explicit error reports for input file parsing<commit_after> | #!/usr/bin/env python3
"""TODO:
* more flexible sorting options
* use -o to specify output file
"""
import json, sys
if len(sys.argv) > 1:
inFn = sys.argv[1]
with open(inFn, 'r') as f:
try:
defs = json.load(f)
except ValueError as e:
sys.exit('ValueError in {}: {}'.format(inFn, e))
sort = sorted(defs, key=str.lower)
print('# My Dictionary')
print('\n## Definitions')
curLetter = None
for k in sort:
l = k[0].upper()
if curLetter != l:
curLetter = l
print('\n### {}'.format(curLetter))
word = k[0].upper() + k[1:]
print('* *{}* - {}'.format(word, defs[k]))
| #!/usr/bin/env python3
"""TODO:
* more flexible sorting options
* use -o to specify output file
* check more explicitly for errors in JSON files
"""
import json, sys
if len(sys.argv) > 1:
inFn = sys.argv[1]
with open(inFn, 'r') as f:
try:
defs = json.load(f)
except:
sys.exit('{} has a syntax error'.format(inFn))
sort = sorted(defs, key=str.lower)
print('# My Dictionary')
print('\n## Definitions')
curLetter = None
for k in sort:
l = k[0].upper()
if curLetter != l:
curLetter = l
print('\n### {}'.format(curLetter))
word = k[0].upper() + k[1:]
print('* *{}* - {}'.format(word, defs[k]))
Print more explicit error reports for input file parsing#!/usr/bin/env python3
"""TODO:
* more flexible sorting options
* use -o to specify output file
"""
import json, sys
if len(sys.argv) > 1:
inFn = sys.argv[1]
with open(inFn, 'r') as f:
try:
defs = json.load(f)
except ValueError as e:
sys.exit('ValueError in {}: {}'.format(inFn, e))
sort = sorted(defs, key=str.lower)
print('# My Dictionary')
print('\n## Definitions')
curLetter = None
for k in sort:
l = k[0].upper()
if curLetter != l:
curLetter = l
print('\n### {}'.format(curLetter))
word = k[0].upper() + k[1:]
print('* *{}* - {}'.format(word, defs[k]))
| <commit_before>#!/usr/bin/env python3
"""TODO:
* more flexible sorting options
* use -o to specify output file
* check more explicitly for errors in JSON files
"""
import json, sys
if len(sys.argv) > 1:
inFn = sys.argv[1]
with open(inFn, 'r') as f:
try:
defs = json.load(f)
except:
sys.exit('{} has a syntax error'.format(inFn))
sort = sorted(defs, key=str.lower)
print('# My Dictionary')
print('\n## Definitions')
curLetter = None
for k in sort:
l = k[0].upper()
if curLetter != l:
curLetter = l
print('\n### {}'.format(curLetter))
word = k[0].upper() + k[1:]
print('* *{}* - {}'.format(word, defs[k]))
<commit_msg>Print more explicit error reports for input file parsing<commit_after>#!/usr/bin/env python3
"""TODO:
* more flexible sorting options
* use -o to specify output file
"""
import json, sys
if len(sys.argv) > 1:
inFn = sys.argv[1]
with open(inFn, 'r') as f:
try:
defs = json.load(f)
except ValueError as e:
sys.exit('ValueError in {}: {}'.format(inFn, e))
sort = sorted(defs, key=str.lower)
print('# My Dictionary')
print('\n## Definitions')
curLetter = None
for k in sort:
l = k[0].upper()
if curLetter != l:
curLetter = l
print('\n### {}'.format(curLetter))
word = k[0].upper() + k[1:]
print('* *{}* - {}'.format(word, defs[k]))
|
82bfc3ad8c39ffe51677eecbdc5c6904ae1ade41 | main.py | main.py | from common.bounty import *
from common.peers import *
from common import settings
def main():
settings.setup()
print "settings are:"
print settings.config
if __name__ == "__main__":
main()
| from common.bounty import *
from common.peers import *
from common import settings
def main():
settings.setup()
print "settings are:"
print settings.config
if settings.config.get('server') is not True:
initializePeerConnections()
else:
listen()
if __name__ == "__main__":
main()
| Add primitive server option for easier debugging | Add primitive server option for easier debugging | Python | mit | gappleto97/Senior-Project | from common.bounty import *
from common.peers import *
from common import settings
def main():
settings.setup()
print "settings are:"
print settings.config
if __name__ == "__main__":
main()
Add primitive server option for easier debugging | from common.bounty import *
from common.peers import *
from common import settings
def main():
settings.setup()
print "settings are:"
print settings.config
if settings.config.get('server') is not True:
initializePeerConnections()
else:
listen()
if __name__ == "__main__":
main()
| <commit_before>from common.bounty import *
from common.peers import *
from common import settings
def main():
settings.setup()
print "settings are:"
print settings.config
if __name__ == "__main__":
main()
<commit_msg>Add primitive server option for easier debugging<commit_after> | from common.bounty import *
from common.peers import *
from common import settings
def main():
settings.setup()
print "settings are:"
print settings.config
if settings.config.get('server') is not True:
initializePeerConnections()
else:
listen()
if __name__ == "__main__":
main()
| from common.bounty import *
from common.peers import *
from common import settings
def main():
settings.setup()
print "settings are:"
print settings.config
if __name__ == "__main__":
main()
Add primitive server option for easier debuggingfrom common.bounty import *
from common.peers import *
from common import settings
def main():
settings.setup()
print "settings are:"
print settings.config
if settings.config.get('server') is not True:
initializePeerConnections()
else:
listen()
if __name__ == "__main__":
main()
| <commit_before>from common.bounty import *
from common.peers import *
from common import settings
def main():
settings.setup()
print "settings are:"
print settings.config
if __name__ == "__main__":
main()
<commit_msg>Add primitive server option for easier debugging<commit_after>from common.bounty import *
from common.peers import *
from common import settings
def main():
settings.setup()
print "settings are:"
print settings.config
if settings.config.get('server') is not True:
initializePeerConnections()
else:
listen()
if __name__ == "__main__":
main()
|
2aae7b1718bfc21267922f7fe09dcf47be69582b | blueprints/aws_rds_instance/delete_aws_rds_instance.py | blueprints/aws_rds_instance/delete_aws_rds_instance.py | import json
import boto3
from infrastructure.models import Environment
def run(job, logger=None, **kwargs):
service = job.service_set.first()
env_id = service.attributes.get(field__name__startswith='aws_environment').value
env = Environment.objects.get(id=env_id)
rh = env.resource_handler.cast()
job.set_progress('Connecting to AWS...')
client = boto3.client(
'rds',
region_name=env.aws_region,
aws_access_key_id=rh.serviceaccount,
aws_secret_access_key=rh.servicepasswd)
instance_cfv = service.attributes.get(field__name='rds_instance')
instance = json.loads(instance_cfv.value)
identifier = instance['identifier']
job.set_progress('Deleting RDS instance {}...'.format(identifier))
response = client.delete_db_instance(
DBInstanceIdentifier=identifier,
# AWS strongly recommends taking a final snapshot before deleting a DB.
# To do so, either set this to False or let the user choose by making it
# a runtime action input (in that case be sure to set the param type to
# Boolean so users get a dropdown).
SkipFinalSnapshot=True,
)
job.set_progress('RDS instance {0} deleted.'.format(identifier))
return 'SUCCESS', '', ''
| import json
import boto3
from infrastructure.models import Environment
def run(job, logger=None, **kwargs):
service = job.service_set.first()
# The Environment ID and RDS Instance data dict were stored as attributes on
# this service by a build action.
env_id_cfv = service.attributes.get(field__name__startswith='aws_environment')
instance_cfv = service.attributes.get(field__name='rds_instance')
env = Environment.objects.get(id=env_id_cfv.value)
client = connect_to_rds(env)
instance = json.loads(instance_cfv.value)
identifier = instance['identifier']
job.set_progress('Deleting RDS instance {0}...'.format(identifier))
response = client.delete_db_instance(
DBInstanceIdentifier=identifier,
# AWS strongly recommends taking a final snapshot before deleting a DB.
# To do so, either set this to False or let the user choose by making it
# a runtime action input (in that case be sure to set the param type to
# Boolean so users get a dropdown).
SkipFinalSnapshot=True,
)
job.set_progress('RDS instance {0} deleted.'.format(identifier))
return 'SUCCESS', '', ''
def connect_to_rds(env):
"""
Return boto connection to the RDS in the specified environment's region.
"""
job.set_progress('Connecting to AWS RDS in region {0}.'.format(env.aws_region))
rh = env.resource_handler.cast()
return boto3.client(
'rds',
region_name=env.aws_region,
aws_access_key_id=rh.serviceaccount,
aws_secret_access_key=rh.servicepasswd)
| Use code consistent with other RDS actions | Use code consistent with other RDS actions
[#144244831]
| Python | apache-2.0 | CloudBoltSoftware/cloudbolt-forge,CloudBoltSoftware/cloudbolt-forge,CloudBoltSoftware/cloudbolt-forge,CloudBoltSoftware/cloudbolt-forge | import json
import boto3
from infrastructure.models import Environment
def run(job, logger=None, **kwargs):
service = job.service_set.first()
env_id = service.attributes.get(field__name__startswith='aws_environment').value
env = Environment.objects.get(id=env_id)
rh = env.resource_handler.cast()
job.set_progress('Connecting to AWS...')
client = boto3.client(
'rds',
region_name=env.aws_region,
aws_access_key_id=rh.serviceaccount,
aws_secret_access_key=rh.servicepasswd)
instance_cfv = service.attributes.get(field__name='rds_instance')
instance = json.loads(instance_cfv.value)
identifier = instance['identifier']
job.set_progress('Deleting RDS instance {}...'.format(identifier))
response = client.delete_db_instance(
DBInstanceIdentifier=identifier,
# AWS strongly recommends taking a final snapshot before deleting a DB.
# To do so, either set this to False or let the user choose by making it
# a runtime action input (in that case be sure to set the param type to
# Boolean so users get a dropdown).
SkipFinalSnapshot=True,
)
job.set_progress('RDS instance {0} deleted.'.format(identifier))
return 'SUCCESS', '', ''
Use code consistent with other RDS actions
[#144244831] | import json
import boto3
from infrastructure.models import Environment
def run(job, logger=None, **kwargs):
service = job.service_set.first()
# The Environment ID and RDS Instance data dict were stored as attributes on
# this service by a build action.
env_id_cfv = service.attributes.get(field__name__startswith='aws_environment')
instance_cfv = service.attributes.get(field__name='rds_instance')
env = Environment.objects.get(id=env_id_cfv.value)
client = connect_to_rds(env)
instance = json.loads(instance_cfv.value)
identifier = instance['identifier']
job.set_progress('Deleting RDS instance {0}...'.format(identifier))
response = client.delete_db_instance(
DBInstanceIdentifier=identifier,
# AWS strongly recommends taking a final snapshot before deleting a DB.
# To do so, either set this to False or let the user choose by making it
# a runtime action input (in that case be sure to set the param type to
# Boolean so users get a dropdown).
SkipFinalSnapshot=True,
)
job.set_progress('RDS instance {0} deleted.'.format(identifier))
return 'SUCCESS', '', ''
def connect_to_rds(env):
"""
Return boto connection to the RDS in the specified environment's region.
"""
job.set_progress('Connecting to AWS RDS in region {0}.'.format(env.aws_region))
rh = env.resource_handler.cast()
return boto3.client(
'rds',
region_name=env.aws_region,
aws_access_key_id=rh.serviceaccount,
aws_secret_access_key=rh.servicepasswd)
| <commit_before>import json
import boto3
from infrastructure.models import Environment
def run(job, logger=None, **kwargs):
service = job.service_set.first()
env_id = service.attributes.get(field__name__startswith='aws_environment').value
env = Environment.objects.get(id=env_id)
rh = env.resource_handler.cast()
job.set_progress('Connecting to AWS...')
client = boto3.client(
'rds',
region_name=env.aws_region,
aws_access_key_id=rh.serviceaccount,
aws_secret_access_key=rh.servicepasswd)
instance_cfv = service.attributes.get(field__name='rds_instance')
instance = json.loads(instance_cfv.value)
identifier = instance['identifier']
job.set_progress('Deleting RDS instance {}...'.format(identifier))
response = client.delete_db_instance(
DBInstanceIdentifier=identifier,
# AWS strongly recommends taking a final snapshot before deleting a DB.
# To do so, either set this to False or let the user choose by making it
# a runtime action input (in that case be sure to set the param type to
# Boolean so users get a dropdown).
SkipFinalSnapshot=True,
)
job.set_progress('RDS instance {0} deleted.'.format(identifier))
return 'SUCCESS', '', ''
<commit_msg>Use code consistent with other RDS actions
[#144244831]<commit_after> | import json
import boto3
from infrastructure.models import Environment
def run(job, logger=None, **kwargs):
service = job.service_set.first()
# The Environment ID and RDS Instance data dict were stored as attributes on
# this service by a build action.
env_id_cfv = service.attributes.get(field__name__startswith='aws_environment')
instance_cfv = service.attributes.get(field__name='rds_instance')
env = Environment.objects.get(id=env_id_cfv.value)
client = connect_to_rds(env)
instance = json.loads(instance_cfv.value)
identifier = instance['identifier']
job.set_progress('Deleting RDS instance {0}...'.format(identifier))
response = client.delete_db_instance(
DBInstanceIdentifier=identifier,
# AWS strongly recommends taking a final snapshot before deleting a DB.
# To do so, either set this to False or let the user choose by making it
# a runtime action input (in that case be sure to set the param type to
# Boolean so users get a dropdown).
SkipFinalSnapshot=True,
)
job.set_progress('RDS instance {0} deleted.'.format(identifier))
return 'SUCCESS', '', ''
def connect_to_rds(env):
"""
Return boto connection to the RDS in the specified environment's region.
"""
job.set_progress('Connecting to AWS RDS in region {0}.'.format(env.aws_region))
rh = env.resource_handler.cast()
return boto3.client(
'rds',
region_name=env.aws_region,
aws_access_key_id=rh.serviceaccount,
aws_secret_access_key=rh.servicepasswd)
| import json
import boto3
from infrastructure.models import Environment
def run(job, logger=None, **kwargs):
service = job.service_set.first()
env_id = service.attributes.get(field__name__startswith='aws_environment').value
env = Environment.objects.get(id=env_id)
rh = env.resource_handler.cast()
job.set_progress('Connecting to AWS...')
client = boto3.client(
'rds',
region_name=env.aws_region,
aws_access_key_id=rh.serviceaccount,
aws_secret_access_key=rh.servicepasswd)
instance_cfv = service.attributes.get(field__name='rds_instance')
instance = json.loads(instance_cfv.value)
identifier = instance['identifier']
job.set_progress('Deleting RDS instance {}...'.format(identifier))
response = client.delete_db_instance(
DBInstanceIdentifier=identifier,
# AWS strongly recommends taking a final snapshot before deleting a DB.
# To do so, either set this to False or let the user choose by making it
# a runtime action input (in that case be sure to set the param type to
# Boolean so users get a dropdown).
SkipFinalSnapshot=True,
)
job.set_progress('RDS instance {0} deleted.'.format(identifier))
return 'SUCCESS', '', ''
Use code consistent with other RDS actions
[#144244831]import json
import boto3
from infrastructure.models import Environment
def run(job, logger=None, **kwargs):
service = job.service_set.first()
# The Environment ID and RDS Instance data dict were stored as attributes on
# this service by a build action.
env_id_cfv = service.attributes.get(field__name__startswith='aws_environment')
instance_cfv = service.attributes.get(field__name='rds_instance')
env = Environment.objects.get(id=env_id_cfv.value)
client = connect_to_rds(env)
instance = json.loads(instance_cfv.value)
identifier = instance['identifier']
job.set_progress('Deleting RDS instance {0}...'.format(identifier))
response = client.delete_db_instance(
DBInstanceIdentifier=identifier,
# AWS strongly recommends taking a final snapshot before deleting a DB.
# To do so, either set this to False or let the user choose by making it
# a runtime action input (in that case be sure to set the param type to
# Boolean so users get a dropdown).
SkipFinalSnapshot=True,
)
job.set_progress('RDS instance {0} deleted.'.format(identifier))
return 'SUCCESS', '', ''
def connect_to_rds(env):
"""
Return boto connection to the RDS in the specified environment's region.
"""
job.set_progress('Connecting to AWS RDS in region {0}.'.format(env.aws_region))
rh = env.resource_handler.cast()
return boto3.client(
'rds',
region_name=env.aws_region,
aws_access_key_id=rh.serviceaccount,
aws_secret_access_key=rh.servicepasswd)
| <commit_before>import json
import boto3
from infrastructure.models import Environment
def run(job, logger=None, **kwargs):
service = job.service_set.first()
env_id = service.attributes.get(field__name__startswith='aws_environment').value
env = Environment.objects.get(id=env_id)
rh = env.resource_handler.cast()
job.set_progress('Connecting to AWS...')
client = boto3.client(
'rds',
region_name=env.aws_region,
aws_access_key_id=rh.serviceaccount,
aws_secret_access_key=rh.servicepasswd)
instance_cfv = service.attributes.get(field__name='rds_instance')
instance = json.loads(instance_cfv.value)
identifier = instance['identifier']
job.set_progress('Deleting RDS instance {}...'.format(identifier))
response = client.delete_db_instance(
DBInstanceIdentifier=identifier,
# AWS strongly recommends taking a final snapshot before deleting a DB.
# To do so, either set this to False or let the user choose by making it
# a runtime action input (in that case be sure to set the param type to
# Boolean so users get a dropdown).
SkipFinalSnapshot=True,
)
job.set_progress('RDS instance {0} deleted.'.format(identifier))
return 'SUCCESS', '', ''
<commit_msg>Use code consistent with other RDS actions
[#144244831]<commit_after>import json
import boto3
from infrastructure.models import Environment
def run(job, logger=None, **kwargs):
service = job.service_set.first()
# The Environment ID and RDS Instance data dict were stored as attributes on
# this service by a build action.
env_id_cfv = service.attributes.get(field__name__startswith='aws_environment')
instance_cfv = service.attributes.get(field__name='rds_instance')
env = Environment.objects.get(id=env_id_cfv.value)
client = connect_to_rds(env)
instance = json.loads(instance_cfv.value)
identifier = instance['identifier']
job.set_progress('Deleting RDS instance {0}...'.format(identifier))
response = client.delete_db_instance(
DBInstanceIdentifier=identifier,
# AWS strongly recommends taking a final snapshot before deleting a DB.
# To do so, either set this to False or let the user choose by making it
# a runtime action input (in that case be sure to set the param type to
# Boolean so users get a dropdown).
SkipFinalSnapshot=True,
)
job.set_progress('RDS instance {0} deleted.'.format(identifier))
return 'SUCCESS', '', ''
def connect_to_rds(env):
"""
Return boto connection to the RDS in the specified environment's region.
"""
job.set_progress('Connecting to AWS RDS in region {0}.'.format(env.aws_region))
rh = env.resource_handler.cast()
return boto3.client(
'rds',
region_name=env.aws_region,
aws_access_key_id=rh.serviceaccount,
aws_secret_access_key=rh.servicepasswd)
|
1c0ea1a102ed91342ce0d609733426b8a07cd67d | easy_thumbnails/tests/apps.py | easy_thumbnails/tests/apps.py | from django.apps import AppConfig
class EasyThumbnailsTestConfig(AppConfig):
name = 'easy_thumbnails.tests'
label = 'easy_thumbnails_tests'
| try:
from django.apps import AppConfig
except ImportError:
# Early Django versions import everything in test, avoid the failure due to
# AppConfig only existing in 1.7+
AppConfig = object
class EasyThumbnailsTestConfig(AppConfig):
name = 'easy_thumbnails.tests'
label = 'easy_thumbnails_tests'
| Fix an import error for old django versions | Fix an import error for old django versions
Fixes #371
| Python | bsd-3-clause | SmileyChris/easy-thumbnails | from django.apps import AppConfig
class EasyThumbnailsTestConfig(AppConfig):
name = 'easy_thumbnails.tests'
label = 'easy_thumbnails_tests'
Fix an import error for old django versions
Fixes #371 | try:
from django.apps import AppConfig
except ImportError:
# Early Django versions import everything in test, avoid the failure due to
# AppConfig only existing in 1.7+
AppConfig = object
class EasyThumbnailsTestConfig(AppConfig):
name = 'easy_thumbnails.tests'
label = 'easy_thumbnails_tests'
| <commit_before>from django.apps import AppConfig
class EasyThumbnailsTestConfig(AppConfig):
name = 'easy_thumbnails.tests'
label = 'easy_thumbnails_tests'
<commit_msg>Fix an import error for old django versions
Fixes #371<commit_after> | try:
from django.apps import AppConfig
except ImportError:
# Early Django versions import everything in test, avoid the failure due to
# AppConfig only existing in 1.7+
AppConfig = object
class EasyThumbnailsTestConfig(AppConfig):
name = 'easy_thumbnails.tests'
label = 'easy_thumbnails_tests'
| from django.apps import AppConfig
class EasyThumbnailsTestConfig(AppConfig):
name = 'easy_thumbnails.tests'
label = 'easy_thumbnails_tests'
Fix an import error for old django versions
Fixes #371try:
from django.apps import AppConfig
except ImportError:
# Early Django versions import everything in test, avoid the failure due to
# AppConfig only existing in 1.7+
AppConfig = object
class EasyThumbnailsTestConfig(AppConfig):
name = 'easy_thumbnails.tests'
label = 'easy_thumbnails_tests'
| <commit_before>from django.apps import AppConfig
class EasyThumbnailsTestConfig(AppConfig):
name = 'easy_thumbnails.tests'
label = 'easy_thumbnails_tests'
<commit_msg>Fix an import error for old django versions
Fixes #371<commit_after>try:
from django.apps import AppConfig
except ImportError:
# Early Django versions import everything in test, avoid the failure due to
# AppConfig only existing in 1.7+
AppConfig = object
class EasyThumbnailsTestConfig(AppConfig):
name = 'easy_thumbnails.tests'
label = 'easy_thumbnails_tests'
|
6e7923413bb0729a288c36f10e22ad7a777bf538 | supercell/testing.py | supercell/testing.py | # vim: set fileencoding=utf-8 :
#
# Copyright (c) 2014 Daniel Truemper <truemped at googlemail.com>
#
# 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 __future__ import (absolute_import, division, print_function,
with_statement)
import sys
from tornado.ioloop import IOLoop
from tornado.testing import AsyncHTTPTestCase as TornadoAsyncHTTPTestCase
import pytest
class AsyncHTTPTestCase(TornadoAsyncHTTPTestCase):
ARGV = []
SERVICE = None
@pytest.fixture(autouse=True)
def set_commandline(self, monkeypatch):
monkeypatch.setattr(sys, 'argv', self.ARGV)
def get_new_ioloop(self):
return IOLoop.instance()
def get_app(self):
service = self.SERVICE()
service.initialize_logging()
return service.get_app()
| # vim: set fileencoding=utf-8 :
#
# Copyright (c) 2014 Daniel Truemper <truemped at googlemail.com>
#
# 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 __future__ import (absolute_import, division, print_function,
with_statement)
import sys
from tornado.ioloop import IOLoop
from tornado.testing import AsyncHTTPTestCase as TornadoAsyncHTTPTestCase
import pytest
class AsyncHTTPTestCase(TornadoAsyncHTTPTestCase):
ARGV = []
SERVICE = None
@pytest.fixture(autouse=True)
def set_commandline(self, monkeypatch):
monkeypatch.setattr(sys, 'argv', ['pytest'] + self.ARGV)
def get_new_ioloop(self):
return IOLoop.instance()
def get_app(self):
service = self.SERVICE()
service.initialize_logging()
return service.get_app()
| Add pytest to mocked sys.argv | Add pytest to mocked sys.argv
If you want to use this for integration tests, the ARGV variable only
has to contain the arguments. The first argument usually is the script
name and is not read by tornado at all.
| Python | apache-2.0 | truemped/supercell,truemped/supercell | # vim: set fileencoding=utf-8 :
#
# Copyright (c) 2014 Daniel Truemper <truemped at googlemail.com>
#
# 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 __future__ import (absolute_import, division, print_function,
with_statement)
import sys
from tornado.ioloop import IOLoop
from tornado.testing import AsyncHTTPTestCase as TornadoAsyncHTTPTestCase
import pytest
class AsyncHTTPTestCase(TornadoAsyncHTTPTestCase):
ARGV = []
SERVICE = None
@pytest.fixture(autouse=True)
def set_commandline(self, monkeypatch):
monkeypatch.setattr(sys, 'argv', self.ARGV)
def get_new_ioloop(self):
return IOLoop.instance()
def get_app(self):
service = self.SERVICE()
service.initialize_logging()
return service.get_app()
Add pytest to mocked sys.argv
If you want to use this for integration tests, the ARGV variable only
has to contain the arguments. The first argument usually is the script
name and is not read by tornado at all. | # vim: set fileencoding=utf-8 :
#
# Copyright (c) 2014 Daniel Truemper <truemped at googlemail.com>
#
# 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 __future__ import (absolute_import, division, print_function,
with_statement)
import sys
from tornado.ioloop import IOLoop
from tornado.testing import AsyncHTTPTestCase as TornadoAsyncHTTPTestCase
import pytest
class AsyncHTTPTestCase(TornadoAsyncHTTPTestCase):
ARGV = []
SERVICE = None
@pytest.fixture(autouse=True)
def set_commandline(self, monkeypatch):
monkeypatch.setattr(sys, 'argv', ['pytest'] + self.ARGV)
def get_new_ioloop(self):
return IOLoop.instance()
def get_app(self):
service = self.SERVICE()
service.initialize_logging()
return service.get_app()
| <commit_before># vim: set fileencoding=utf-8 :
#
# Copyright (c) 2014 Daniel Truemper <truemped at googlemail.com>
#
# 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 __future__ import (absolute_import, division, print_function,
with_statement)
import sys
from tornado.ioloop import IOLoop
from tornado.testing import AsyncHTTPTestCase as TornadoAsyncHTTPTestCase
import pytest
class AsyncHTTPTestCase(TornadoAsyncHTTPTestCase):
ARGV = []
SERVICE = None
@pytest.fixture(autouse=True)
def set_commandline(self, monkeypatch):
monkeypatch.setattr(sys, 'argv', self.ARGV)
def get_new_ioloop(self):
return IOLoop.instance()
def get_app(self):
service = self.SERVICE()
service.initialize_logging()
return service.get_app()
<commit_msg>Add pytest to mocked sys.argv
If you want to use this for integration tests, the ARGV variable only
has to contain the arguments. The first argument usually is the script
name and is not read by tornado at all.<commit_after> | # vim: set fileencoding=utf-8 :
#
# Copyright (c) 2014 Daniel Truemper <truemped at googlemail.com>
#
# 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 __future__ import (absolute_import, division, print_function,
with_statement)
import sys
from tornado.ioloop import IOLoop
from tornado.testing import AsyncHTTPTestCase as TornadoAsyncHTTPTestCase
import pytest
class AsyncHTTPTestCase(TornadoAsyncHTTPTestCase):
ARGV = []
SERVICE = None
@pytest.fixture(autouse=True)
def set_commandline(self, monkeypatch):
monkeypatch.setattr(sys, 'argv', ['pytest'] + self.ARGV)
def get_new_ioloop(self):
return IOLoop.instance()
def get_app(self):
service = self.SERVICE()
service.initialize_logging()
return service.get_app()
| # vim: set fileencoding=utf-8 :
#
# Copyright (c) 2014 Daniel Truemper <truemped at googlemail.com>
#
# 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 __future__ import (absolute_import, division, print_function,
with_statement)
import sys
from tornado.ioloop import IOLoop
from tornado.testing import AsyncHTTPTestCase as TornadoAsyncHTTPTestCase
import pytest
class AsyncHTTPTestCase(TornadoAsyncHTTPTestCase):
ARGV = []
SERVICE = None
@pytest.fixture(autouse=True)
def set_commandline(self, monkeypatch):
monkeypatch.setattr(sys, 'argv', self.ARGV)
def get_new_ioloop(self):
return IOLoop.instance()
def get_app(self):
service = self.SERVICE()
service.initialize_logging()
return service.get_app()
Add pytest to mocked sys.argv
If you want to use this for integration tests, the ARGV variable only
has to contain the arguments. The first argument usually is the script
name and is not read by tornado at all.# vim: set fileencoding=utf-8 :
#
# Copyright (c) 2014 Daniel Truemper <truemped at googlemail.com>
#
# 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 __future__ import (absolute_import, division, print_function,
with_statement)
import sys
from tornado.ioloop import IOLoop
from tornado.testing import AsyncHTTPTestCase as TornadoAsyncHTTPTestCase
import pytest
class AsyncHTTPTestCase(TornadoAsyncHTTPTestCase):
ARGV = []
SERVICE = None
@pytest.fixture(autouse=True)
def set_commandline(self, monkeypatch):
monkeypatch.setattr(sys, 'argv', ['pytest'] + self.ARGV)
def get_new_ioloop(self):
return IOLoop.instance()
def get_app(self):
service = self.SERVICE()
service.initialize_logging()
return service.get_app()
| <commit_before># vim: set fileencoding=utf-8 :
#
# Copyright (c) 2014 Daniel Truemper <truemped at googlemail.com>
#
# 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 __future__ import (absolute_import, division, print_function,
with_statement)
import sys
from tornado.ioloop import IOLoop
from tornado.testing import AsyncHTTPTestCase as TornadoAsyncHTTPTestCase
import pytest
class AsyncHTTPTestCase(TornadoAsyncHTTPTestCase):
ARGV = []
SERVICE = None
@pytest.fixture(autouse=True)
def set_commandline(self, monkeypatch):
monkeypatch.setattr(sys, 'argv', self.ARGV)
def get_new_ioloop(self):
return IOLoop.instance()
def get_app(self):
service = self.SERVICE()
service.initialize_logging()
return service.get_app()
<commit_msg>Add pytest to mocked sys.argv
If you want to use this for integration tests, the ARGV variable only
has to contain the arguments. The first argument usually is the script
name and is not read by tornado at all.<commit_after># vim: set fileencoding=utf-8 :
#
# Copyright (c) 2014 Daniel Truemper <truemped at googlemail.com>
#
# 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 __future__ import (absolute_import, division, print_function,
with_statement)
import sys
from tornado.ioloop import IOLoop
from tornado.testing import AsyncHTTPTestCase as TornadoAsyncHTTPTestCase
import pytest
class AsyncHTTPTestCase(TornadoAsyncHTTPTestCase):
ARGV = []
SERVICE = None
@pytest.fixture(autouse=True)
def set_commandline(self, monkeypatch):
monkeypatch.setattr(sys, 'argv', ['pytest'] + self.ARGV)
def get_new_ioloop(self):
return IOLoop.instance()
def get_app(self):
service = self.SERVICE()
service.initialize_logging()
return service.get_app()
|
a6dc99096870b186aafe85e9777b7c29de488a51 | forum/models.py | forum/models.py | from django.db import models
class Thread(models.Model):
"""Model for representing threads."""
title = models.TextField()
views = models.PositiveIntegerField(default=0)
sticky = models.BooleanField()
closed = models.BooleanField()
| from django.db import models
import django.contrib.auth.models as auth
class User(auth.User):
"""Model for representing users.
It has few fields that aren't in the standard authentication user
table, and are needed for the forum to work, like footers.
"""
display_name = models.CharField(max_length=30, null=True)
class Thread(models.Model):
"""Model for representing threads."""
title = models.TextField()
views = models.PositiveIntegerField(default=0)
sticky = models.BooleanField()
closed = models.BooleanField()
| Create user class for forums. | Create user class for forums.
Forums need to store information users that is usually not stored.
This currently stores only display name, althrough it can store more
in the future.
| Python | mit | xfix/NextBoard | from django.db import models
class Thread(models.Model):
"""Model for representing threads."""
title = models.TextField()
views = models.PositiveIntegerField(default=0)
sticky = models.BooleanField()
closed = models.BooleanField()
Create user class for forums.
Forums need to store information users that is usually not stored.
This currently stores only display name, althrough it can store more
in the future. | from django.db import models
import django.contrib.auth.models as auth
class User(auth.User):
"""Model for representing users.
It has few fields that aren't in the standard authentication user
table, and are needed for the forum to work, like footers.
"""
display_name = models.CharField(max_length=30, null=True)
class Thread(models.Model):
"""Model for representing threads."""
title = models.TextField()
views = models.PositiveIntegerField(default=0)
sticky = models.BooleanField()
closed = models.BooleanField()
| <commit_before>from django.db import models
class Thread(models.Model):
"""Model for representing threads."""
title = models.TextField()
views = models.PositiveIntegerField(default=0)
sticky = models.BooleanField()
closed = models.BooleanField()
<commit_msg>Create user class for forums.
Forums need to store information users that is usually not stored.
This currently stores only display name, althrough it can store more
in the future.<commit_after> | from django.db import models
import django.contrib.auth.models as auth
class User(auth.User):
"""Model for representing users.
It has few fields that aren't in the standard authentication user
table, and are needed for the forum to work, like footers.
"""
display_name = models.CharField(max_length=30, null=True)
class Thread(models.Model):
"""Model for representing threads."""
title = models.TextField()
views = models.PositiveIntegerField(default=0)
sticky = models.BooleanField()
closed = models.BooleanField()
| from django.db import models
class Thread(models.Model):
"""Model for representing threads."""
title = models.TextField()
views = models.PositiveIntegerField(default=0)
sticky = models.BooleanField()
closed = models.BooleanField()
Create user class for forums.
Forums need to store information users that is usually not stored.
This currently stores only display name, althrough it can store more
in the future.from django.db import models
import django.contrib.auth.models as auth
class User(auth.User):
"""Model for representing users.
It has few fields that aren't in the standard authentication user
table, and are needed for the forum to work, like footers.
"""
display_name = models.CharField(max_length=30, null=True)
class Thread(models.Model):
"""Model for representing threads."""
title = models.TextField()
views = models.PositiveIntegerField(default=0)
sticky = models.BooleanField()
closed = models.BooleanField()
| <commit_before>from django.db import models
class Thread(models.Model):
"""Model for representing threads."""
title = models.TextField()
views = models.PositiveIntegerField(default=0)
sticky = models.BooleanField()
closed = models.BooleanField()
<commit_msg>Create user class for forums.
Forums need to store information users that is usually not stored.
This currently stores only display name, althrough it can store more
in the future.<commit_after>from django.db import models
import django.contrib.auth.models as auth
class User(auth.User):
"""Model for representing users.
It has few fields that aren't in the standard authentication user
table, and are needed for the forum to work, like footers.
"""
display_name = models.CharField(max_length=30, null=True)
class Thread(models.Model):
"""Model for representing threads."""
title = models.TextField()
views = models.PositiveIntegerField(default=0)
sticky = models.BooleanField()
closed = models.BooleanField()
|
8ce6aa788573aa10758375d58881f03ff438db16 | machete/base.py | machete/base.py | from datetime import datetime
from thunderdome.connection import setup
import thunderdome
setup(["localhost"], "machete")
class BaseVertex(thunderdome.Vertex):
created_at = thunderdome.DateTime(default=datetime.now)
class BaseEdge(thunderdome.Edge):
created_at = thunderdome.DateTime(default=datetime.now)
class CreatedBy(BaseEdge):
pass
| from datetime import datetime
from thunderdome.connection import setup
import thunderdome
setup(["localhost"], "machete")
class BaseVertex(thunderdome.Vertex):
created_at = thunderdome.DateTime(default=datetime.now)
def __repr__(self):
return "<{}:{}>".format(self.__class__.__name__, self.vid)
class BaseEdge(thunderdome.Edge):
created_at = thunderdome.DateTime(default=datetime.now)
def __repr__(self):
return "<{}:{}>".format(self.__class__.__name__, self.eid)
class CreatedBy(BaseEdge):
pass
| Add __repr__ To BaseVertex and BaseEdge | Add __repr__ To BaseVertex and BaseEdge
| Python | bsd-3-clause | rustyrazorblade/machete,rustyrazorblade/machete,rustyrazorblade/machete | from datetime import datetime
from thunderdome.connection import setup
import thunderdome
setup(["localhost"], "machete")
class BaseVertex(thunderdome.Vertex):
created_at = thunderdome.DateTime(default=datetime.now)
class BaseEdge(thunderdome.Edge):
created_at = thunderdome.DateTime(default=datetime.now)
class CreatedBy(BaseEdge):
pass
Add __repr__ To BaseVertex and BaseEdge | from datetime import datetime
from thunderdome.connection import setup
import thunderdome
setup(["localhost"], "machete")
class BaseVertex(thunderdome.Vertex):
created_at = thunderdome.DateTime(default=datetime.now)
def __repr__(self):
return "<{}:{}>".format(self.__class__.__name__, self.vid)
class BaseEdge(thunderdome.Edge):
created_at = thunderdome.DateTime(default=datetime.now)
def __repr__(self):
return "<{}:{}>".format(self.__class__.__name__, self.eid)
class CreatedBy(BaseEdge):
pass
| <commit_before>from datetime import datetime
from thunderdome.connection import setup
import thunderdome
setup(["localhost"], "machete")
class BaseVertex(thunderdome.Vertex):
created_at = thunderdome.DateTime(default=datetime.now)
class BaseEdge(thunderdome.Edge):
created_at = thunderdome.DateTime(default=datetime.now)
class CreatedBy(BaseEdge):
pass
<commit_msg>Add __repr__ To BaseVertex and BaseEdge<commit_after> | from datetime import datetime
from thunderdome.connection import setup
import thunderdome
setup(["localhost"], "machete")
class BaseVertex(thunderdome.Vertex):
created_at = thunderdome.DateTime(default=datetime.now)
def __repr__(self):
return "<{}:{}>".format(self.__class__.__name__, self.vid)
class BaseEdge(thunderdome.Edge):
created_at = thunderdome.DateTime(default=datetime.now)
def __repr__(self):
return "<{}:{}>".format(self.__class__.__name__, self.eid)
class CreatedBy(BaseEdge):
pass
| from datetime import datetime
from thunderdome.connection import setup
import thunderdome
setup(["localhost"], "machete")
class BaseVertex(thunderdome.Vertex):
created_at = thunderdome.DateTime(default=datetime.now)
class BaseEdge(thunderdome.Edge):
created_at = thunderdome.DateTime(default=datetime.now)
class CreatedBy(BaseEdge):
pass
Add __repr__ To BaseVertex and BaseEdgefrom datetime import datetime
from thunderdome.connection import setup
import thunderdome
setup(["localhost"], "machete")
class BaseVertex(thunderdome.Vertex):
created_at = thunderdome.DateTime(default=datetime.now)
def __repr__(self):
return "<{}:{}>".format(self.__class__.__name__, self.vid)
class BaseEdge(thunderdome.Edge):
created_at = thunderdome.DateTime(default=datetime.now)
def __repr__(self):
return "<{}:{}>".format(self.__class__.__name__, self.eid)
class CreatedBy(BaseEdge):
pass
| <commit_before>from datetime import datetime
from thunderdome.connection import setup
import thunderdome
setup(["localhost"], "machete")
class BaseVertex(thunderdome.Vertex):
created_at = thunderdome.DateTime(default=datetime.now)
class BaseEdge(thunderdome.Edge):
created_at = thunderdome.DateTime(default=datetime.now)
class CreatedBy(BaseEdge):
pass
<commit_msg>Add __repr__ To BaseVertex and BaseEdge<commit_after>from datetime import datetime
from thunderdome.connection import setup
import thunderdome
setup(["localhost"], "machete")
class BaseVertex(thunderdome.Vertex):
created_at = thunderdome.DateTime(default=datetime.now)
def __repr__(self):
return "<{}:{}>".format(self.__class__.__name__, self.vid)
class BaseEdge(thunderdome.Edge):
created_at = thunderdome.DateTime(default=datetime.now)
def __repr__(self):
return "<{}:{}>".format(self.__class__.__name__, self.eid)
class CreatedBy(BaseEdge):
pass
|
384c4ebb1712837b0610f90b6973520e7bbedca1 | studies/helpers.py | studies/helpers.py | from django.core.mail.message import EmailMultiAlternatives
from django.template.loader import get_template
from project.settings import EMAIL_FROM_ADDRESS, BASE_URL
# TODO: celery taskify
def send_mail(template_name, subject, to_addresses, cc=None, bcc=None, **context):
"""
Helper for sending templated email
:param str template_name: Name of the template to send. There should exist a txt and html version
:param str subject: Subject line of the email
:param str from_address: From address for email
:param list to_addresses: List of addresses to email. If str is provided, wrapped in list
:param list cc: List of addresses to carbon copy
:param list bcc: List of addresses to blind carbon copy
:kwargs: Context vars for the email template
"""
context['base_url'] = BASE_URL
plain = get_template('emails/{}.txt'.format(template_name))
html = get_template('emails/{}.html'.format(template_name))
if not isinstance(to_addresses, list):
to_addresses = [to_addresses]
text_content = plain.render(context)
html_content = html.render(context)
email = EmailMultiAlternatives(subject, text_content, EMAIL_FROM_ADDRESS, to_addresses, cc=cc, bcc=bcc)
email.attach_alternative(html_content, 'text/html')
email.send()
| from django.core.mail.message import EmailMultiAlternatives
from django.template.loader import get_template
from project.settings import EMAIL_FROM_ADDRESS, BASE_URL
# TODO: celery taskify
def send_mail(template_name, subject, to_addresses, cc=None, bcc=None, custom_message=None, from_email=None, **context):
"""
Helper for sending templated email
:param str template_name: Name of the template to send. There should exist a txt and html version
:param str subject: Subject line of the email
:param str from_address: From address for email
:param list to_addresses: List of addresses to email. If str is provided, wrapped in list
:param list cc: List of addresses to carbon copy
:param list bcc: List of addresses to blind carbon copy
:param str custom_message Custom email message - for use instead of a template
:kwargs: Context vars for the email template
"""
context['base_url'] = BASE_URL
if template_name:
text_content = get_template('emails/{}.txt'.format(template_name)).render(context)
html_content = get_template('emails/{}.html'.format(template_name)).render(context)
if custom_message:
text_content = custom_message
html_content = custom_message
if not isinstance(to_addresses, list):
to_addresses = [to_addresses]
from_address = from_email or EMAIL_FROM_ADDRESS
email = EmailMultiAlternatives(subject, text_content, from_address, to_addresses, cc=cc, bcc=bcc)
email.attach_alternative(html_content, 'text/html')
email.send()
| Modify send_mail method to pass in more parameters, specifying text instead of template, and from_email. | Modify send_mail method to pass in more parameters, specifying text instead of template, and from_email.
| Python | apache-2.0 | pattisdr/lookit-api,pattisdr/lookit-api,CenterForOpenScience/lookit-api,CenterForOpenScience/lookit-api,pattisdr/lookit-api,CenterForOpenScience/lookit-api | from django.core.mail.message import EmailMultiAlternatives
from django.template.loader import get_template
from project.settings import EMAIL_FROM_ADDRESS, BASE_URL
# TODO: celery taskify
def send_mail(template_name, subject, to_addresses, cc=None, bcc=None, **context):
"""
Helper for sending templated email
:param str template_name: Name of the template to send. There should exist a txt and html version
:param str subject: Subject line of the email
:param str from_address: From address for email
:param list to_addresses: List of addresses to email. If str is provided, wrapped in list
:param list cc: List of addresses to carbon copy
:param list bcc: List of addresses to blind carbon copy
:kwargs: Context vars for the email template
"""
context['base_url'] = BASE_URL
plain = get_template('emails/{}.txt'.format(template_name))
html = get_template('emails/{}.html'.format(template_name))
if not isinstance(to_addresses, list):
to_addresses = [to_addresses]
text_content = plain.render(context)
html_content = html.render(context)
email = EmailMultiAlternatives(subject, text_content, EMAIL_FROM_ADDRESS, to_addresses, cc=cc, bcc=bcc)
email.attach_alternative(html_content, 'text/html')
email.send()
Modify send_mail method to pass in more parameters, specifying text instead of template, and from_email. | from django.core.mail.message import EmailMultiAlternatives
from django.template.loader import get_template
from project.settings import EMAIL_FROM_ADDRESS, BASE_URL
# TODO: celery taskify
def send_mail(template_name, subject, to_addresses, cc=None, bcc=None, custom_message=None, from_email=None, **context):
"""
Helper for sending templated email
:param str template_name: Name of the template to send. There should exist a txt and html version
:param str subject: Subject line of the email
:param str from_address: From address for email
:param list to_addresses: List of addresses to email. If str is provided, wrapped in list
:param list cc: List of addresses to carbon copy
:param list bcc: List of addresses to blind carbon copy
:param str custom_message Custom email message - for use instead of a template
:kwargs: Context vars for the email template
"""
context['base_url'] = BASE_URL
if template_name:
text_content = get_template('emails/{}.txt'.format(template_name)).render(context)
html_content = get_template('emails/{}.html'.format(template_name)).render(context)
if custom_message:
text_content = custom_message
html_content = custom_message
if not isinstance(to_addresses, list):
to_addresses = [to_addresses]
from_address = from_email or EMAIL_FROM_ADDRESS
email = EmailMultiAlternatives(subject, text_content, from_address, to_addresses, cc=cc, bcc=bcc)
email.attach_alternative(html_content, 'text/html')
email.send()
| <commit_before>from django.core.mail.message import EmailMultiAlternatives
from django.template.loader import get_template
from project.settings import EMAIL_FROM_ADDRESS, BASE_URL
# TODO: celery taskify
def send_mail(template_name, subject, to_addresses, cc=None, bcc=None, **context):
"""
Helper for sending templated email
:param str template_name: Name of the template to send. There should exist a txt and html version
:param str subject: Subject line of the email
:param str from_address: From address for email
:param list to_addresses: List of addresses to email. If str is provided, wrapped in list
:param list cc: List of addresses to carbon copy
:param list bcc: List of addresses to blind carbon copy
:kwargs: Context vars for the email template
"""
context['base_url'] = BASE_URL
plain = get_template('emails/{}.txt'.format(template_name))
html = get_template('emails/{}.html'.format(template_name))
if not isinstance(to_addresses, list):
to_addresses = [to_addresses]
text_content = plain.render(context)
html_content = html.render(context)
email = EmailMultiAlternatives(subject, text_content, EMAIL_FROM_ADDRESS, to_addresses, cc=cc, bcc=bcc)
email.attach_alternative(html_content, 'text/html')
email.send()
<commit_msg>Modify send_mail method to pass in more parameters, specifying text instead of template, and from_email.<commit_after> | from django.core.mail.message import EmailMultiAlternatives
from django.template.loader import get_template
from project.settings import EMAIL_FROM_ADDRESS, BASE_URL
# TODO: celery taskify
def send_mail(template_name, subject, to_addresses, cc=None, bcc=None, custom_message=None, from_email=None, **context):
"""
Helper for sending templated email
:param str template_name: Name of the template to send. There should exist a txt and html version
:param str subject: Subject line of the email
:param str from_address: From address for email
:param list to_addresses: List of addresses to email. If str is provided, wrapped in list
:param list cc: List of addresses to carbon copy
:param list bcc: List of addresses to blind carbon copy
:param str custom_message Custom email message - for use instead of a template
:kwargs: Context vars for the email template
"""
context['base_url'] = BASE_URL
if template_name:
text_content = get_template('emails/{}.txt'.format(template_name)).render(context)
html_content = get_template('emails/{}.html'.format(template_name)).render(context)
if custom_message:
text_content = custom_message
html_content = custom_message
if not isinstance(to_addresses, list):
to_addresses = [to_addresses]
from_address = from_email or EMAIL_FROM_ADDRESS
email = EmailMultiAlternatives(subject, text_content, from_address, to_addresses, cc=cc, bcc=bcc)
email.attach_alternative(html_content, 'text/html')
email.send()
| from django.core.mail.message import EmailMultiAlternatives
from django.template.loader import get_template
from project.settings import EMAIL_FROM_ADDRESS, BASE_URL
# TODO: celery taskify
def send_mail(template_name, subject, to_addresses, cc=None, bcc=None, **context):
"""
Helper for sending templated email
:param str template_name: Name of the template to send. There should exist a txt and html version
:param str subject: Subject line of the email
:param str from_address: From address for email
:param list to_addresses: List of addresses to email. If str is provided, wrapped in list
:param list cc: List of addresses to carbon copy
:param list bcc: List of addresses to blind carbon copy
:kwargs: Context vars for the email template
"""
context['base_url'] = BASE_URL
plain = get_template('emails/{}.txt'.format(template_name))
html = get_template('emails/{}.html'.format(template_name))
if not isinstance(to_addresses, list):
to_addresses = [to_addresses]
text_content = plain.render(context)
html_content = html.render(context)
email = EmailMultiAlternatives(subject, text_content, EMAIL_FROM_ADDRESS, to_addresses, cc=cc, bcc=bcc)
email.attach_alternative(html_content, 'text/html')
email.send()
Modify send_mail method to pass in more parameters, specifying text instead of template, and from_email.from django.core.mail.message import EmailMultiAlternatives
from django.template.loader import get_template
from project.settings import EMAIL_FROM_ADDRESS, BASE_URL
# TODO: celery taskify
def send_mail(template_name, subject, to_addresses, cc=None, bcc=None, custom_message=None, from_email=None, **context):
"""
Helper for sending templated email
:param str template_name: Name of the template to send. There should exist a txt and html version
:param str subject: Subject line of the email
:param str from_address: From address for email
:param list to_addresses: List of addresses to email. If str is provided, wrapped in list
:param list cc: List of addresses to carbon copy
:param list bcc: List of addresses to blind carbon copy
:param str custom_message Custom email message - for use instead of a template
:kwargs: Context vars for the email template
"""
context['base_url'] = BASE_URL
if template_name:
text_content = get_template('emails/{}.txt'.format(template_name)).render(context)
html_content = get_template('emails/{}.html'.format(template_name)).render(context)
if custom_message:
text_content = custom_message
html_content = custom_message
if not isinstance(to_addresses, list):
to_addresses = [to_addresses]
from_address = from_email or EMAIL_FROM_ADDRESS
email = EmailMultiAlternatives(subject, text_content, from_address, to_addresses, cc=cc, bcc=bcc)
email.attach_alternative(html_content, 'text/html')
email.send()
| <commit_before>from django.core.mail.message import EmailMultiAlternatives
from django.template.loader import get_template
from project.settings import EMAIL_FROM_ADDRESS, BASE_URL
# TODO: celery taskify
def send_mail(template_name, subject, to_addresses, cc=None, bcc=None, **context):
"""
Helper for sending templated email
:param str template_name: Name of the template to send. There should exist a txt and html version
:param str subject: Subject line of the email
:param str from_address: From address for email
:param list to_addresses: List of addresses to email. If str is provided, wrapped in list
:param list cc: List of addresses to carbon copy
:param list bcc: List of addresses to blind carbon copy
:kwargs: Context vars for the email template
"""
context['base_url'] = BASE_URL
plain = get_template('emails/{}.txt'.format(template_name))
html = get_template('emails/{}.html'.format(template_name))
if not isinstance(to_addresses, list):
to_addresses = [to_addresses]
text_content = plain.render(context)
html_content = html.render(context)
email = EmailMultiAlternatives(subject, text_content, EMAIL_FROM_ADDRESS, to_addresses, cc=cc, bcc=bcc)
email.attach_alternative(html_content, 'text/html')
email.send()
<commit_msg>Modify send_mail method to pass in more parameters, specifying text instead of template, and from_email.<commit_after>from django.core.mail.message import EmailMultiAlternatives
from django.template.loader import get_template
from project.settings import EMAIL_FROM_ADDRESS, BASE_URL
# TODO: celery taskify
def send_mail(template_name, subject, to_addresses, cc=None, bcc=None, custom_message=None, from_email=None, **context):
"""
Helper for sending templated email
:param str template_name: Name of the template to send. There should exist a txt and html version
:param str subject: Subject line of the email
:param str from_address: From address for email
:param list to_addresses: List of addresses to email. If str is provided, wrapped in list
:param list cc: List of addresses to carbon copy
:param list bcc: List of addresses to blind carbon copy
:param str custom_message Custom email message - for use instead of a template
:kwargs: Context vars for the email template
"""
context['base_url'] = BASE_URL
if template_name:
text_content = get_template('emails/{}.txt'.format(template_name)).render(context)
html_content = get_template('emails/{}.html'.format(template_name)).render(context)
if custom_message:
text_content = custom_message
html_content = custom_message
if not isinstance(to_addresses, list):
to_addresses = [to_addresses]
from_address = from_email or EMAIL_FROM_ADDRESS
email = EmailMultiAlternatives(subject, text_content, from_address, to_addresses, cc=cc, bcc=bcc)
email.attach_alternative(html_content, 'text/html')
email.send()
|
ccbceb486dd4775ec6dfe3764e522a869860703b | examples/rbd_fast/rbd_fast.py | examples/rbd_fast/rbd_fast.py | import sys
sys.path.append('../..')
from SALib.analyze import rbd_fast
from SALib.sample import latin
from SALib.test_functions import Ishigami
from SALib.util import read_param_file
# Read the parameter range file and generate samples
problem = read_param_file('../../src/SALib/test_functions/params/Ishigami.txt')
# Generate samples
param_values = latin.sample(problem, 1000)
# Run the "model" and save the output in a text file
# This will happen offline for external models
Y = Ishigami.evaluate(param_values)
# Perform the sensitivity analysis using the model output
# Specify which column of the output file to analyze (zero-indexed)
Si = rbd_fast.analyze(problem, param_values, Y, print_to_console=True)
# Returns a dictionary with keys 'S1' and 'ST'
# e.g. Si['S1'] contains the first-order index for each parameter, in the
# same order as the parameter file
| import sys
sys.path.append('../..')
from SALib.analyze import rbd_fast
from SALib.sample import latin
from SALib.test_functions import Ishigami
from SALib.util import read_param_file
# Read the parameter range file and generate samples
problem = read_param_file('../../src/SALib/test_functions/params/Ishigami.txt')
# Generate samples
param_values = latin.sample(problem, 1000)
# Run the "model" and save the output in a text file
# This will happen offline for external models
Y = Ishigami.evaluate(param_values)
# Perform the sensitivity analysis using the model output
# Specify which column of the output file to analyze (zero-indexed)
Si = rbd_fast.analyze(problem, param_values, Y, print_to_console=True)
# Returns a dictionary with key 'S1'
# e.g. Si['S1'] contains the first-order index for each parameter, in the
# same order as the parameter file
| Fix incorrect description of returned dict entries | Fix incorrect description of returned dict entries
| Python | mit | jdherman/SALib,SALib/SALib,jdherman/SALib | import sys
sys.path.append('../..')
from SALib.analyze import rbd_fast
from SALib.sample import latin
from SALib.test_functions import Ishigami
from SALib.util import read_param_file
# Read the parameter range file and generate samples
problem = read_param_file('../../src/SALib/test_functions/params/Ishigami.txt')
# Generate samples
param_values = latin.sample(problem, 1000)
# Run the "model" and save the output in a text file
# This will happen offline for external models
Y = Ishigami.evaluate(param_values)
# Perform the sensitivity analysis using the model output
# Specify which column of the output file to analyze (zero-indexed)
Si = rbd_fast.analyze(problem, param_values, Y, print_to_console=True)
# Returns a dictionary with keys 'S1' and 'ST'
# e.g. Si['S1'] contains the first-order index for each parameter, in the
# same order as the parameter file
Fix incorrect description of returned dict entries | import sys
sys.path.append('../..')
from SALib.analyze import rbd_fast
from SALib.sample import latin
from SALib.test_functions import Ishigami
from SALib.util import read_param_file
# Read the parameter range file and generate samples
problem = read_param_file('../../src/SALib/test_functions/params/Ishigami.txt')
# Generate samples
param_values = latin.sample(problem, 1000)
# Run the "model" and save the output in a text file
# This will happen offline for external models
Y = Ishigami.evaluate(param_values)
# Perform the sensitivity analysis using the model output
# Specify which column of the output file to analyze (zero-indexed)
Si = rbd_fast.analyze(problem, param_values, Y, print_to_console=True)
# Returns a dictionary with key 'S1'
# e.g. Si['S1'] contains the first-order index for each parameter, in the
# same order as the parameter file
| <commit_before>import sys
sys.path.append('../..')
from SALib.analyze import rbd_fast
from SALib.sample import latin
from SALib.test_functions import Ishigami
from SALib.util import read_param_file
# Read the parameter range file and generate samples
problem = read_param_file('../../src/SALib/test_functions/params/Ishigami.txt')
# Generate samples
param_values = latin.sample(problem, 1000)
# Run the "model" and save the output in a text file
# This will happen offline for external models
Y = Ishigami.evaluate(param_values)
# Perform the sensitivity analysis using the model output
# Specify which column of the output file to analyze (zero-indexed)
Si = rbd_fast.analyze(problem, param_values, Y, print_to_console=True)
# Returns a dictionary with keys 'S1' and 'ST'
# e.g. Si['S1'] contains the first-order index for each parameter, in the
# same order as the parameter file
<commit_msg>Fix incorrect description of returned dict entries<commit_after> | import sys
sys.path.append('../..')
from SALib.analyze import rbd_fast
from SALib.sample import latin
from SALib.test_functions import Ishigami
from SALib.util import read_param_file
# Read the parameter range file and generate samples
problem = read_param_file('../../src/SALib/test_functions/params/Ishigami.txt')
# Generate samples
param_values = latin.sample(problem, 1000)
# Run the "model" and save the output in a text file
# This will happen offline for external models
Y = Ishigami.evaluate(param_values)
# Perform the sensitivity analysis using the model output
# Specify which column of the output file to analyze (zero-indexed)
Si = rbd_fast.analyze(problem, param_values, Y, print_to_console=True)
# Returns a dictionary with key 'S1'
# e.g. Si['S1'] contains the first-order index for each parameter, in the
# same order as the parameter file
| import sys
sys.path.append('../..')
from SALib.analyze import rbd_fast
from SALib.sample import latin
from SALib.test_functions import Ishigami
from SALib.util import read_param_file
# Read the parameter range file and generate samples
problem = read_param_file('../../src/SALib/test_functions/params/Ishigami.txt')
# Generate samples
param_values = latin.sample(problem, 1000)
# Run the "model" and save the output in a text file
# This will happen offline for external models
Y = Ishigami.evaluate(param_values)
# Perform the sensitivity analysis using the model output
# Specify which column of the output file to analyze (zero-indexed)
Si = rbd_fast.analyze(problem, param_values, Y, print_to_console=True)
# Returns a dictionary with keys 'S1' and 'ST'
# e.g. Si['S1'] contains the first-order index for each parameter, in the
# same order as the parameter file
Fix incorrect description of returned dict entriesimport sys
sys.path.append('../..')
from SALib.analyze import rbd_fast
from SALib.sample import latin
from SALib.test_functions import Ishigami
from SALib.util import read_param_file
# Read the parameter range file and generate samples
problem = read_param_file('../../src/SALib/test_functions/params/Ishigami.txt')
# Generate samples
param_values = latin.sample(problem, 1000)
# Run the "model" and save the output in a text file
# This will happen offline for external models
Y = Ishigami.evaluate(param_values)
# Perform the sensitivity analysis using the model output
# Specify which column of the output file to analyze (zero-indexed)
Si = rbd_fast.analyze(problem, param_values, Y, print_to_console=True)
# Returns a dictionary with key 'S1'
# e.g. Si['S1'] contains the first-order index for each parameter, in the
# same order as the parameter file
| <commit_before>import sys
sys.path.append('../..')
from SALib.analyze import rbd_fast
from SALib.sample import latin
from SALib.test_functions import Ishigami
from SALib.util import read_param_file
# Read the parameter range file and generate samples
problem = read_param_file('../../src/SALib/test_functions/params/Ishigami.txt')
# Generate samples
param_values = latin.sample(problem, 1000)
# Run the "model" and save the output in a text file
# This will happen offline for external models
Y = Ishigami.evaluate(param_values)
# Perform the sensitivity analysis using the model output
# Specify which column of the output file to analyze (zero-indexed)
Si = rbd_fast.analyze(problem, param_values, Y, print_to_console=True)
# Returns a dictionary with keys 'S1' and 'ST'
# e.g. Si['S1'] contains the first-order index for each parameter, in the
# same order as the parameter file
<commit_msg>Fix incorrect description of returned dict entries<commit_after>import sys
sys.path.append('../..')
from SALib.analyze import rbd_fast
from SALib.sample import latin
from SALib.test_functions import Ishigami
from SALib.util import read_param_file
# Read the parameter range file and generate samples
problem = read_param_file('../../src/SALib/test_functions/params/Ishigami.txt')
# Generate samples
param_values = latin.sample(problem, 1000)
# Run the "model" and save the output in a text file
# This will happen offline for external models
Y = Ishigami.evaluate(param_values)
# Perform the sensitivity analysis using the model output
# Specify which column of the output file to analyze (zero-indexed)
Si = rbd_fast.analyze(problem, param_values, Y, print_to_console=True)
# Returns a dictionary with key 'S1'
# e.g. Si['S1'] contains the first-order index for each parameter, in the
# same order as the parameter file
|
4af812f9189a7bd29b9aea274eeed5cbd277dbcb | examples/widgets/actionbar.py | examples/widgets/actionbar.py | from kivy.base import runTouchApp
from kivy.lang import Builder
runTouchApp(Builder.load_string('''
ActionBar:
pos_hint: {'top':1}
ActionView:
use_separator: True
ActionPrevious:
title: 'Action Bar'
with_previous: False
ActionOverflow:
ActionButton:
text: 'Btn0'
icon: 'atlas://data/images/defaulttheme/audio-volume-high'
ActionButton:
text: 'Btn1'
ActionButton:
text: 'Btn2'
ActionButton:
text: 'Btn3'
ActionButton:
text: 'Btn4'
ActionGroup:
text: 'Group1'
ActionButton:
text: 'Btn5'
ActionButton:
text: 'Btn6'
ActionButton:
text: 'Btn7'
'''))
| from kivy.base import runTouchApp
from kivy.lang import Builder
runTouchApp(Builder.load_string('''
ActionBar:
pos_hint: {'top':1}
ActionView:
use_separator: True
ActionPrevious:
title: 'Action Bar'
with_previous: False
ActionOverflow:
ActionButton:
icon: 'atlas://data/images/defaulttheme/audio-volume-high'
ActionButton:
text: 'Btn1'
ActionButton:
text: 'Btn2'
ActionButton:
text: 'Btn3'
ActionButton:
text: 'Btn4'
ActionGroup:
text: 'Group1'
ActionButton:
text: 'Btn5'
ActionButton:
text: 'Btn6'
ActionButton:
text: 'Btn7'
'''))
| Remove overlapping caption in ActionBar example | Remove overlapping caption in ActionBar example
| Python | mit | LogicalDash/kivy,LogicalDash/kivy,Cheaterman/kivy,Cheaterman/kivy,inclement/kivy,kivy/kivy,rnixx/kivy,bionoid/kivy,akshayaurora/kivy,bionoid/kivy,Cheaterman/kivy,LogicalDash/kivy,kivy/kivy,LogicalDash/kivy,matham/kivy,inclement/kivy,akshayaurora/kivy,inclement/kivy,matham/kivy,kivy/kivy,bionoid/kivy,akshayaurora/kivy,Cheaterman/kivy,rnixx/kivy,matham/kivy,rnixx/kivy,matham/kivy,bionoid/kivy | from kivy.base import runTouchApp
from kivy.lang import Builder
runTouchApp(Builder.load_string('''
ActionBar:
pos_hint: {'top':1}
ActionView:
use_separator: True
ActionPrevious:
title: 'Action Bar'
with_previous: False
ActionOverflow:
ActionButton:
text: 'Btn0'
icon: 'atlas://data/images/defaulttheme/audio-volume-high'
ActionButton:
text: 'Btn1'
ActionButton:
text: 'Btn2'
ActionButton:
text: 'Btn3'
ActionButton:
text: 'Btn4'
ActionGroup:
text: 'Group1'
ActionButton:
text: 'Btn5'
ActionButton:
text: 'Btn6'
ActionButton:
text: 'Btn7'
'''))
Remove overlapping caption in ActionBar example | from kivy.base import runTouchApp
from kivy.lang import Builder
runTouchApp(Builder.load_string('''
ActionBar:
pos_hint: {'top':1}
ActionView:
use_separator: True
ActionPrevious:
title: 'Action Bar'
with_previous: False
ActionOverflow:
ActionButton:
icon: 'atlas://data/images/defaulttheme/audio-volume-high'
ActionButton:
text: 'Btn1'
ActionButton:
text: 'Btn2'
ActionButton:
text: 'Btn3'
ActionButton:
text: 'Btn4'
ActionGroup:
text: 'Group1'
ActionButton:
text: 'Btn5'
ActionButton:
text: 'Btn6'
ActionButton:
text: 'Btn7'
'''))
| <commit_before>from kivy.base import runTouchApp
from kivy.lang import Builder
runTouchApp(Builder.load_string('''
ActionBar:
pos_hint: {'top':1}
ActionView:
use_separator: True
ActionPrevious:
title: 'Action Bar'
with_previous: False
ActionOverflow:
ActionButton:
text: 'Btn0'
icon: 'atlas://data/images/defaulttheme/audio-volume-high'
ActionButton:
text: 'Btn1'
ActionButton:
text: 'Btn2'
ActionButton:
text: 'Btn3'
ActionButton:
text: 'Btn4'
ActionGroup:
text: 'Group1'
ActionButton:
text: 'Btn5'
ActionButton:
text: 'Btn6'
ActionButton:
text: 'Btn7'
'''))
<commit_msg>Remove overlapping caption in ActionBar example<commit_after> | from kivy.base import runTouchApp
from kivy.lang import Builder
runTouchApp(Builder.load_string('''
ActionBar:
pos_hint: {'top':1}
ActionView:
use_separator: True
ActionPrevious:
title: 'Action Bar'
with_previous: False
ActionOverflow:
ActionButton:
icon: 'atlas://data/images/defaulttheme/audio-volume-high'
ActionButton:
text: 'Btn1'
ActionButton:
text: 'Btn2'
ActionButton:
text: 'Btn3'
ActionButton:
text: 'Btn4'
ActionGroup:
text: 'Group1'
ActionButton:
text: 'Btn5'
ActionButton:
text: 'Btn6'
ActionButton:
text: 'Btn7'
'''))
| from kivy.base import runTouchApp
from kivy.lang import Builder
runTouchApp(Builder.load_string('''
ActionBar:
pos_hint: {'top':1}
ActionView:
use_separator: True
ActionPrevious:
title: 'Action Bar'
with_previous: False
ActionOverflow:
ActionButton:
text: 'Btn0'
icon: 'atlas://data/images/defaulttheme/audio-volume-high'
ActionButton:
text: 'Btn1'
ActionButton:
text: 'Btn2'
ActionButton:
text: 'Btn3'
ActionButton:
text: 'Btn4'
ActionGroup:
text: 'Group1'
ActionButton:
text: 'Btn5'
ActionButton:
text: 'Btn6'
ActionButton:
text: 'Btn7'
'''))
Remove overlapping caption in ActionBar examplefrom kivy.base import runTouchApp
from kivy.lang import Builder
runTouchApp(Builder.load_string('''
ActionBar:
pos_hint: {'top':1}
ActionView:
use_separator: True
ActionPrevious:
title: 'Action Bar'
with_previous: False
ActionOverflow:
ActionButton:
icon: 'atlas://data/images/defaulttheme/audio-volume-high'
ActionButton:
text: 'Btn1'
ActionButton:
text: 'Btn2'
ActionButton:
text: 'Btn3'
ActionButton:
text: 'Btn4'
ActionGroup:
text: 'Group1'
ActionButton:
text: 'Btn5'
ActionButton:
text: 'Btn6'
ActionButton:
text: 'Btn7'
'''))
| <commit_before>from kivy.base import runTouchApp
from kivy.lang import Builder
runTouchApp(Builder.load_string('''
ActionBar:
pos_hint: {'top':1}
ActionView:
use_separator: True
ActionPrevious:
title: 'Action Bar'
with_previous: False
ActionOverflow:
ActionButton:
text: 'Btn0'
icon: 'atlas://data/images/defaulttheme/audio-volume-high'
ActionButton:
text: 'Btn1'
ActionButton:
text: 'Btn2'
ActionButton:
text: 'Btn3'
ActionButton:
text: 'Btn4'
ActionGroup:
text: 'Group1'
ActionButton:
text: 'Btn5'
ActionButton:
text: 'Btn6'
ActionButton:
text: 'Btn7'
'''))
<commit_msg>Remove overlapping caption in ActionBar example<commit_after>from kivy.base import runTouchApp
from kivy.lang import Builder
runTouchApp(Builder.load_string('''
ActionBar:
pos_hint: {'top':1}
ActionView:
use_separator: True
ActionPrevious:
title: 'Action Bar'
with_previous: False
ActionOverflow:
ActionButton:
icon: 'atlas://data/images/defaulttheme/audio-volume-high'
ActionButton:
text: 'Btn1'
ActionButton:
text: 'Btn2'
ActionButton:
text: 'Btn3'
ActionButton:
text: 'Btn4'
ActionGroup:
text: 'Group1'
ActionButton:
text: 'Btn5'
ActionButton:
text: 'Btn6'
ActionButton:
text: 'Btn7'
'''))
|
8d73c71a0c9b8d4a226b90b9310562b490296038 | gen/CSiBE-v2.1.1/preprocessed-source-compiler.py | gen/CSiBE-v2.1.1/preprocessed-source-compiler.py | #!/usr/bin/env python
import argparse
import os
import subprocess
if __name__ == "__main__":
# Use wrappers for compilers (native)
c_compiler_name = "gcc"
if "CC" in os.environ:
c_compiler_name = os.environ["CC"]
preprocessed_sources = ""
if "CSIBE_PREPROCESSED_SOURCES" in os.environ:
preprocessed_sources = os.environ["CSIBE_PREPROCESSED_SOURCES"].split()
compiler_preprocessed_flags = ["-x",
"cpp-output",
"-c"]
compiler_additional_flags = ["-fno-builtin"]
compiler_call_list = [c_compiler_name]
compiler_call_list.extend(compiler_preprocessed_flags)
compiler_call_list.extend(compiler_additional_flags)
for source_path in preprocessed_sources:
actual_call_list = compiler_call_list
actual_call_list.append(source_path)
subprocess.call(compiler_call_list)
| #!/usr/bin/env python
import argparse
import os
import subprocess
if __name__ == "__main__":
# Use wrappers for compilers (native)
c_compiler_name = "gcc"
if "CC" in os.environ:
c_compiler_name = os.environ["CC"]
preprocessed_sources = ""
if "CSIBE_PREPROCESSED_SOURCES" in os.environ:
preprocessed_sources = os.environ["CSIBE_PREPROCESSED_SOURCES"].split()
compiler_preprocessed_flags = ["-x",
"cpp-output",
"-c"]
compiler_additional_flags = ["-fno-builtin"]
if c_compiler_name.endswith("g++") or c_compiler_name.endswith("clang++"):
compiler_additional_flags.extend(os.getenv("CSiBE_CXXFLAGS", "").split())
elif c_compiler_name.endswith("gcc") or c_compiler_name.endswith("clang"):
compiler_additional_flags.extend(os.getenv("CSiBE_CFLAGS", "").split())
compiler_call_list = [c_compiler_name]
compiler_call_list.extend(compiler_preprocessed_flags)
compiler_call_list.extend(compiler_additional_flags)
for source_path in preprocessed_sources:
actual_call_list = compiler_call_list
actual_call_list.append(source_path)
subprocess.call(compiler_call_list)
| Add requested CSiBE flags to the compilation of preprocessed files | Add requested CSiBE flags to the compilation of preprocessed files
| Python | bsd-3-clause | szeged/csibe,bgabor666/csibe,bgabor666/csibe,szeged/csibe,szeged/csibe,szeged/csibe,bgabor666/csibe,bgabor666/csibe,bgabor666/csibe,szeged/csibe,szeged/csibe,bgabor666/csibe,bgabor666/csibe,szeged/csibe | #!/usr/bin/env python
import argparse
import os
import subprocess
if __name__ == "__main__":
# Use wrappers for compilers (native)
c_compiler_name = "gcc"
if "CC" in os.environ:
c_compiler_name = os.environ["CC"]
preprocessed_sources = ""
if "CSIBE_PREPROCESSED_SOURCES" in os.environ:
preprocessed_sources = os.environ["CSIBE_PREPROCESSED_SOURCES"].split()
compiler_preprocessed_flags = ["-x",
"cpp-output",
"-c"]
compiler_additional_flags = ["-fno-builtin"]
compiler_call_list = [c_compiler_name]
compiler_call_list.extend(compiler_preprocessed_flags)
compiler_call_list.extend(compiler_additional_flags)
for source_path in preprocessed_sources:
actual_call_list = compiler_call_list
actual_call_list.append(source_path)
subprocess.call(compiler_call_list)
Add requested CSiBE flags to the compilation of preprocessed files | #!/usr/bin/env python
import argparse
import os
import subprocess
if __name__ == "__main__":
# Use wrappers for compilers (native)
c_compiler_name = "gcc"
if "CC" in os.environ:
c_compiler_name = os.environ["CC"]
preprocessed_sources = ""
if "CSIBE_PREPROCESSED_SOURCES" in os.environ:
preprocessed_sources = os.environ["CSIBE_PREPROCESSED_SOURCES"].split()
compiler_preprocessed_flags = ["-x",
"cpp-output",
"-c"]
compiler_additional_flags = ["-fno-builtin"]
if c_compiler_name.endswith("g++") or c_compiler_name.endswith("clang++"):
compiler_additional_flags.extend(os.getenv("CSiBE_CXXFLAGS", "").split())
elif c_compiler_name.endswith("gcc") or c_compiler_name.endswith("clang"):
compiler_additional_flags.extend(os.getenv("CSiBE_CFLAGS", "").split())
compiler_call_list = [c_compiler_name]
compiler_call_list.extend(compiler_preprocessed_flags)
compiler_call_list.extend(compiler_additional_flags)
for source_path in preprocessed_sources:
actual_call_list = compiler_call_list
actual_call_list.append(source_path)
subprocess.call(compiler_call_list)
| <commit_before>#!/usr/bin/env python
import argparse
import os
import subprocess
if __name__ == "__main__":
# Use wrappers for compilers (native)
c_compiler_name = "gcc"
if "CC" in os.environ:
c_compiler_name = os.environ["CC"]
preprocessed_sources = ""
if "CSIBE_PREPROCESSED_SOURCES" in os.environ:
preprocessed_sources = os.environ["CSIBE_PREPROCESSED_SOURCES"].split()
compiler_preprocessed_flags = ["-x",
"cpp-output",
"-c"]
compiler_additional_flags = ["-fno-builtin"]
compiler_call_list = [c_compiler_name]
compiler_call_list.extend(compiler_preprocessed_flags)
compiler_call_list.extend(compiler_additional_flags)
for source_path in preprocessed_sources:
actual_call_list = compiler_call_list
actual_call_list.append(source_path)
subprocess.call(compiler_call_list)
<commit_msg>Add requested CSiBE flags to the compilation of preprocessed files<commit_after> | #!/usr/bin/env python
import argparse
import os
import subprocess
if __name__ == "__main__":
# Use wrappers for compilers (native)
c_compiler_name = "gcc"
if "CC" in os.environ:
c_compiler_name = os.environ["CC"]
preprocessed_sources = ""
if "CSIBE_PREPROCESSED_SOURCES" in os.environ:
preprocessed_sources = os.environ["CSIBE_PREPROCESSED_SOURCES"].split()
compiler_preprocessed_flags = ["-x",
"cpp-output",
"-c"]
compiler_additional_flags = ["-fno-builtin"]
if c_compiler_name.endswith("g++") or c_compiler_name.endswith("clang++"):
compiler_additional_flags.extend(os.getenv("CSiBE_CXXFLAGS", "").split())
elif c_compiler_name.endswith("gcc") or c_compiler_name.endswith("clang"):
compiler_additional_flags.extend(os.getenv("CSiBE_CFLAGS", "").split())
compiler_call_list = [c_compiler_name]
compiler_call_list.extend(compiler_preprocessed_flags)
compiler_call_list.extend(compiler_additional_flags)
for source_path in preprocessed_sources:
actual_call_list = compiler_call_list
actual_call_list.append(source_path)
subprocess.call(compiler_call_list)
| #!/usr/bin/env python
import argparse
import os
import subprocess
if __name__ == "__main__":
# Use wrappers for compilers (native)
c_compiler_name = "gcc"
if "CC" in os.environ:
c_compiler_name = os.environ["CC"]
preprocessed_sources = ""
if "CSIBE_PREPROCESSED_SOURCES" in os.environ:
preprocessed_sources = os.environ["CSIBE_PREPROCESSED_SOURCES"].split()
compiler_preprocessed_flags = ["-x",
"cpp-output",
"-c"]
compiler_additional_flags = ["-fno-builtin"]
compiler_call_list = [c_compiler_name]
compiler_call_list.extend(compiler_preprocessed_flags)
compiler_call_list.extend(compiler_additional_flags)
for source_path in preprocessed_sources:
actual_call_list = compiler_call_list
actual_call_list.append(source_path)
subprocess.call(compiler_call_list)
Add requested CSiBE flags to the compilation of preprocessed files#!/usr/bin/env python
import argparse
import os
import subprocess
if __name__ == "__main__":
# Use wrappers for compilers (native)
c_compiler_name = "gcc"
if "CC" in os.environ:
c_compiler_name = os.environ["CC"]
preprocessed_sources = ""
if "CSIBE_PREPROCESSED_SOURCES" in os.environ:
preprocessed_sources = os.environ["CSIBE_PREPROCESSED_SOURCES"].split()
compiler_preprocessed_flags = ["-x",
"cpp-output",
"-c"]
compiler_additional_flags = ["-fno-builtin"]
if c_compiler_name.endswith("g++") or c_compiler_name.endswith("clang++"):
compiler_additional_flags.extend(os.getenv("CSiBE_CXXFLAGS", "").split())
elif c_compiler_name.endswith("gcc") or c_compiler_name.endswith("clang"):
compiler_additional_flags.extend(os.getenv("CSiBE_CFLAGS", "").split())
compiler_call_list = [c_compiler_name]
compiler_call_list.extend(compiler_preprocessed_flags)
compiler_call_list.extend(compiler_additional_flags)
for source_path in preprocessed_sources:
actual_call_list = compiler_call_list
actual_call_list.append(source_path)
subprocess.call(compiler_call_list)
| <commit_before>#!/usr/bin/env python
import argparse
import os
import subprocess
if __name__ == "__main__":
# Use wrappers for compilers (native)
c_compiler_name = "gcc"
if "CC" in os.environ:
c_compiler_name = os.environ["CC"]
preprocessed_sources = ""
if "CSIBE_PREPROCESSED_SOURCES" in os.environ:
preprocessed_sources = os.environ["CSIBE_PREPROCESSED_SOURCES"].split()
compiler_preprocessed_flags = ["-x",
"cpp-output",
"-c"]
compiler_additional_flags = ["-fno-builtin"]
compiler_call_list = [c_compiler_name]
compiler_call_list.extend(compiler_preprocessed_flags)
compiler_call_list.extend(compiler_additional_flags)
for source_path in preprocessed_sources:
actual_call_list = compiler_call_list
actual_call_list.append(source_path)
subprocess.call(compiler_call_list)
<commit_msg>Add requested CSiBE flags to the compilation of preprocessed files<commit_after>#!/usr/bin/env python
import argparse
import os
import subprocess
if __name__ == "__main__":
# Use wrappers for compilers (native)
c_compiler_name = "gcc"
if "CC" in os.environ:
c_compiler_name = os.environ["CC"]
preprocessed_sources = ""
if "CSIBE_PREPROCESSED_SOURCES" in os.environ:
preprocessed_sources = os.environ["CSIBE_PREPROCESSED_SOURCES"].split()
compiler_preprocessed_flags = ["-x",
"cpp-output",
"-c"]
compiler_additional_flags = ["-fno-builtin"]
if c_compiler_name.endswith("g++") or c_compiler_name.endswith("clang++"):
compiler_additional_flags.extend(os.getenv("CSiBE_CXXFLAGS", "").split())
elif c_compiler_name.endswith("gcc") or c_compiler_name.endswith("clang"):
compiler_additional_flags.extend(os.getenv("CSiBE_CFLAGS", "").split())
compiler_call_list = [c_compiler_name]
compiler_call_list.extend(compiler_preprocessed_flags)
compiler_call_list.extend(compiler_additional_flags)
for source_path in preprocessed_sources:
actual_call_list = compiler_call_list
actual_call_list.append(source_path)
subprocess.call(compiler_call_list)
|
1c7487e50def0bb6bffd7af30e4f1a948197bee8 | tests/settings.py | tests/settings.py |
DATABASE_ENGINE = 'sqlite3'
DATABASE_NAME = ':memory:'
DATABASE_USER = ''
DATABASE_PASSWORD = ''
DATABASE_HOST = ''
DATABASE_PORT = ''
INSTALLED_APPS = (
'djmoney',
'testapp'
) |
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
INSTALLED_APPS = (
'djmoney',
'testapp'
)
| Switch to Django 1.2+ method of specifying databases. | Switch to Django 1.2+ method of specifying databases.
At least this way the tests run. Even though they do not pass yet.
| Python | bsd-3-clause | tsouvarev/django-money,recklessromeo/django-money,iXioN/django-money,pjdelport/django-money,recklessromeo/django-money,rescale/django-money,tsouvarev/django-money,iXioN/django-money,AlexRiina/django-money |
DATABASE_ENGINE = 'sqlite3'
DATABASE_NAME = ':memory:'
DATABASE_USER = ''
DATABASE_PASSWORD = ''
DATABASE_HOST = ''
DATABASE_PORT = ''
INSTALLED_APPS = (
'djmoney',
'testapp'
)Switch to Django 1.2+ method of specifying databases.
At least this way the tests run. Even though they do not pass yet. |
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
INSTALLED_APPS = (
'djmoney',
'testapp'
)
| <commit_before>
DATABASE_ENGINE = 'sqlite3'
DATABASE_NAME = ':memory:'
DATABASE_USER = ''
DATABASE_PASSWORD = ''
DATABASE_HOST = ''
DATABASE_PORT = ''
INSTALLED_APPS = (
'djmoney',
'testapp'
)<commit_msg>Switch to Django 1.2+ method of specifying databases.
At least this way the tests run. Even though they do not pass yet.<commit_after> |
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
INSTALLED_APPS = (
'djmoney',
'testapp'
)
|
DATABASE_ENGINE = 'sqlite3'
DATABASE_NAME = ':memory:'
DATABASE_USER = ''
DATABASE_PASSWORD = ''
DATABASE_HOST = ''
DATABASE_PORT = ''
INSTALLED_APPS = (
'djmoney',
'testapp'
)Switch to Django 1.2+ method of specifying databases.
At least this way the tests run. Even though they do not pass yet.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
INSTALLED_APPS = (
'djmoney',
'testapp'
)
| <commit_before>
DATABASE_ENGINE = 'sqlite3'
DATABASE_NAME = ':memory:'
DATABASE_USER = ''
DATABASE_PASSWORD = ''
DATABASE_HOST = ''
DATABASE_PORT = ''
INSTALLED_APPS = (
'djmoney',
'testapp'
)<commit_msg>Switch to Django 1.2+ method of specifying databases.
At least this way the tests run. Even though they do not pass yet.<commit_after>
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
INSTALLED_APPS = (
'djmoney',
'testapp'
)
|
a2142fb8a592a9ad9b4870d4685ec02cfa621a77 | tests/settings.py | tests/settings.py | import os
import urllib
TRUSTED_ROOT_FILE = os.path.join(
os.path.dirname(os.path.abspath(__file__)), "AppleIncRootCertificate.cer"
)
SECRET_KEY = "notsecr3t"
IAP_SETTINGS = {
"TRUSTED_ROOT_FILE": TRUSTED_ROOT_FILE,
"PRODUCTION_BUNDLE_ID": "com.educreations.ios.Educreations",
}
if not os.path.isfile(TRUSTED_ROOT_FILE):
trusted_root_data = urllib.urlretrieve(
"https://www.apple.com/appleca/AppleIncRootCertificate.cer", TRUSTED_ROOT_FILE
)
| import os
import urllib
TRUSTED_ROOT_FILE = os.path.join(
os.path.dirname(os.path.abspath(__file__)), "AppleIncRootCertificate.cer"
)
SECRET_KEY = "notsecr3t"
IAP_SETTINGS = {
"TRUSTED_ROOT_FILE": TRUSTED_ROOT_FILE,
"PRODUCTION_BUNDLE_ID": "com.educreations.ios.Educreations",
}
if not os.path.isfile(TRUSTED_ROOT_FILE):
try:
trusted_root_data = urllib.urlretrieve(
"https://www.apple.com/appleca/AppleIncRootCertificate.cer",
TRUSTED_ROOT_FILE,
)
except AttributeError:
# Python 3
trusted_root_data = urllib.request.urlretrieve(
"https://www.apple.com/appleca/AppleIncRootCertificate.cer",
TRUSTED_ROOT_FILE,
)
| Fix cert retreival on python 3 | Fix cert retreival on python 3
| Python | mit | educreations/python-iap | import os
import urllib
TRUSTED_ROOT_FILE = os.path.join(
os.path.dirname(os.path.abspath(__file__)), "AppleIncRootCertificate.cer"
)
SECRET_KEY = "notsecr3t"
IAP_SETTINGS = {
"TRUSTED_ROOT_FILE": TRUSTED_ROOT_FILE,
"PRODUCTION_BUNDLE_ID": "com.educreations.ios.Educreations",
}
if not os.path.isfile(TRUSTED_ROOT_FILE):
trusted_root_data = urllib.urlretrieve(
"https://www.apple.com/appleca/AppleIncRootCertificate.cer", TRUSTED_ROOT_FILE
)
Fix cert retreival on python 3 | import os
import urllib
TRUSTED_ROOT_FILE = os.path.join(
os.path.dirname(os.path.abspath(__file__)), "AppleIncRootCertificate.cer"
)
SECRET_KEY = "notsecr3t"
IAP_SETTINGS = {
"TRUSTED_ROOT_FILE": TRUSTED_ROOT_FILE,
"PRODUCTION_BUNDLE_ID": "com.educreations.ios.Educreations",
}
if not os.path.isfile(TRUSTED_ROOT_FILE):
try:
trusted_root_data = urllib.urlretrieve(
"https://www.apple.com/appleca/AppleIncRootCertificate.cer",
TRUSTED_ROOT_FILE,
)
except AttributeError:
# Python 3
trusted_root_data = urllib.request.urlretrieve(
"https://www.apple.com/appleca/AppleIncRootCertificate.cer",
TRUSTED_ROOT_FILE,
)
| <commit_before>import os
import urllib
TRUSTED_ROOT_FILE = os.path.join(
os.path.dirname(os.path.abspath(__file__)), "AppleIncRootCertificate.cer"
)
SECRET_KEY = "notsecr3t"
IAP_SETTINGS = {
"TRUSTED_ROOT_FILE": TRUSTED_ROOT_FILE,
"PRODUCTION_BUNDLE_ID": "com.educreations.ios.Educreations",
}
if not os.path.isfile(TRUSTED_ROOT_FILE):
trusted_root_data = urllib.urlretrieve(
"https://www.apple.com/appleca/AppleIncRootCertificate.cer", TRUSTED_ROOT_FILE
)
<commit_msg>Fix cert retreival on python 3<commit_after> | import os
import urllib
TRUSTED_ROOT_FILE = os.path.join(
os.path.dirname(os.path.abspath(__file__)), "AppleIncRootCertificate.cer"
)
SECRET_KEY = "notsecr3t"
IAP_SETTINGS = {
"TRUSTED_ROOT_FILE": TRUSTED_ROOT_FILE,
"PRODUCTION_BUNDLE_ID": "com.educreations.ios.Educreations",
}
if not os.path.isfile(TRUSTED_ROOT_FILE):
try:
trusted_root_data = urllib.urlretrieve(
"https://www.apple.com/appleca/AppleIncRootCertificate.cer",
TRUSTED_ROOT_FILE,
)
except AttributeError:
# Python 3
trusted_root_data = urllib.request.urlretrieve(
"https://www.apple.com/appleca/AppleIncRootCertificate.cer",
TRUSTED_ROOT_FILE,
)
| import os
import urllib
TRUSTED_ROOT_FILE = os.path.join(
os.path.dirname(os.path.abspath(__file__)), "AppleIncRootCertificate.cer"
)
SECRET_KEY = "notsecr3t"
IAP_SETTINGS = {
"TRUSTED_ROOT_FILE": TRUSTED_ROOT_FILE,
"PRODUCTION_BUNDLE_ID": "com.educreations.ios.Educreations",
}
if not os.path.isfile(TRUSTED_ROOT_FILE):
trusted_root_data = urllib.urlretrieve(
"https://www.apple.com/appleca/AppleIncRootCertificate.cer", TRUSTED_ROOT_FILE
)
Fix cert retreival on python 3import os
import urllib
TRUSTED_ROOT_FILE = os.path.join(
os.path.dirname(os.path.abspath(__file__)), "AppleIncRootCertificate.cer"
)
SECRET_KEY = "notsecr3t"
IAP_SETTINGS = {
"TRUSTED_ROOT_FILE": TRUSTED_ROOT_FILE,
"PRODUCTION_BUNDLE_ID": "com.educreations.ios.Educreations",
}
if not os.path.isfile(TRUSTED_ROOT_FILE):
try:
trusted_root_data = urllib.urlretrieve(
"https://www.apple.com/appleca/AppleIncRootCertificate.cer",
TRUSTED_ROOT_FILE,
)
except AttributeError:
# Python 3
trusted_root_data = urllib.request.urlretrieve(
"https://www.apple.com/appleca/AppleIncRootCertificate.cer",
TRUSTED_ROOT_FILE,
)
| <commit_before>import os
import urllib
TRUSTED_ROOT_FILE = os.path.join(
os.path.dirname(os.path.abspath(__file__)), "AppleIncRootCertificate.cer"
)
SECRET_KEY = "notsecr3t"
IAP_SETTINGS = {
"TRUSTED_ROOT_FILE": TRUSTED_ROOT_FILE,
"PRODUCTION_BUNDLE_ID": "com.educreations.ios.Educreations",
}
if not os.path.isfile(TRUSTED_ROOT_FILE):
trusted_root_data = urllib.urlretrieve(
"https://www.apple.com/appleca/AppleIncRootCertificate.cer", TRUSTED_ROOT_FILE
)
<commit_msg>Fix cert retreival on python 3<commit_after>import os
import urllib
TRUSTED_ROOT_FILE = os.path.join(
os.path.dirname(os.path.abspath(__file__)), "AppleIncRootCertificate.cer"
)
SECRET_KEY = "notsecr3t"
IAP_SETTINGS = {
"TRUSTED_ROOT_FILE": TRUSTED_ROOT_FILE,
"PRODUCTION_BUNDLE_ID": "com.educreations.ios.Educreations",
}
if not os.path.isfile(TRUSTED_ROOT_FILE):
try:
trusted_root_data = urllib.urlretrieve(
"https://www.apple.com/appleca/AppleIncRootCertificate.cer",
TRUSTED_ROOT_FILE,
)
except AttributeError:
# Python 3
trusted_root_data = urllib.request.urlretrieve(
"https://www.apple.com/appleca/AppleIncRootCertificate.cer",
TRUSTED_ROOT_FILE,
)
|
18603df8d13cf0eff753cb713e6c52ae30179f30 | experiments/camera-stdin-stdout/bg-subtract.py | experiments/camera-stdin-stdout/bg-subtract.py | #!/usr/bin/python
import cv2
import ImageReader
escape_key = 27
reader = ImageReader.ImageReader()
fgbg = cv2.createBackgroundSubtractorMOG2()
while True:
imgread, img = reader.decode()
if imgread:
fgmask = fgbg.apply(img)
cv2.imshow("frame", fgmask)
key = cv2.waitKey(1) & 0xFF
if key == escape_key:
break
cv2.destroyAllWindows()
| #!/usr/bin/python
import cv2
import ImageReader
import numpy as np
import sys
escape_key = 27
reader = ImageReader.ImageReader()
fgbg = cv2.createBackgroundSubtractorMOG2()
while True:
imgread, img = reader.decode()
if imgread:
fgmask = fgbg.apply(img)
retval, encodedimage = cv2.imencode(".jpg", fgmask)
np.savetxt(sys.stdout, encodedimage, fmt='%c', newline='')
key = cv2.waitKey(1) & 0xFF
if key == escape_key:
break
cv2.destroyAllWindows()
| Print to stdout the changed video | Print to stdout the changed video
| Python | mit | Mindavi/Positiebepalingssysteem | #!/usr/bin/python
import cv2
import ImageReader
escape_key = 27
reader = ImageReader.ImageReader()
fgbg = cv2.createBackgroundSubtractorMOG2()
while True:
imgread, img = reader.decode()
if imgread:
fgmask = fgbg.apply(img)
cv2.imshow("frame", fgmask)
key = cv2.waitKey(1) & 0xFF
if key == escape_key:
break
cv2.destroyAllWindows()
Print to stdout the changed video | #!/usr/bin/python
import cv2
import ImageReader
import numpy as np
import sys
escape_key = 27
reader = ImageReader.ImageReader()
fgbg = cv2.createBackgroundSubtractorMOG2()
while True:
imgread, img = reader.decode()
if imgread:
fgmask = fgbg.apply(img)
retval, encodedimage = cv2.imencode(".jpg", fgmask)
np.savetxt(sys.stdout, encodedimage, fmt='%c', newline='')
key = cv2.waitKey(1) & 0xFF
if key == escape_key:
break
cv2.destroyAllWindows()
| <commit_before>#!/usr/bin/python
import cv2
import ImageReader
escape_key = 27
reader = ImageReader.ImageReader()
fgbg = cv2.createBackgroundSubtractorMOG2()
while True:
imgread, img = reader.decode()
if imgread:
fgmask = fgbg.apply(img)
cv2.imshow("frame", fgmask)
key = cv2.waitKey(1) & 0xFF
if key == escape_key:
break
cv2.destroyAllWindows()
<commit_msg>Print to stdout the changed video<commit_after> | #!/usr/bin/python
import cv2
import ImageReader
import numpy as np
import sys
escape_key = 27
reader = ImageReader.ImageReader()
fgbg = cv2.createBackgroundSubtractorMOG2()
while True:
imgread, img = reader.decode()
if imgread:
fgmask = fgbg.apply(img)
retval, encodedimage = cv2.imencode(".jpg", fgmask)
np.savetxt(sys.stdout, encodedimage, fmt='%c', newline='')
key = cv2.waitKey(1) & 0xFF
if key == escape_key:
break
cv2.destroyAllWindows()
| #!/usr/bin/python
import cv2
import ImageReader
escape_key = 27
reader = ImageReader.ImageReader()
fgbg = cv2.createBackgroundSubtractorMOG2()
while True:
imgread, img = reader.decode()
if imgread:
fgmask = fgbg.apply(img)
cv2.imshow("frame", fgmask)
key = cv2.waitKey(1) & 0xFF
if key == escape_key:
break
cv2.destroyAllWindows()
Print to stdout the changed video#!/usr/bin/python
import cv2
import ImageReader
import numpy as np
import sys
escape_key = 27
reader = ImageReader.ImageReader()
fgbg = cv2.createBackgroundSubtractorMOG2()
while True:
imgread, img = reader.decode()
if imgread:
fgmask = fgbg.apply(img)
retval, encodedimage = cv2.imencode(".jpg", fgmask)
np.savetxt(sys.stdout, encodedimage, fmt='%c', newline='')
key = cv2.waitKey(1) & 0xFF
if key == escape_key:
break
cv2.destroyAllWindows()
| <commit_before>#!/usr/bin/python
import cv2
import ImageReader
escape_key = 27
reader = ImageReader.ImageReader()
fgbg = cv2.createBackgroundSubtractorMOG2()
while True:
imgread, img = reader.decode()
if imgread:
fgmask = fgbg.apply(img)
cv2.imshow("frame", fgmask)
key = cv2.waitKey(1) & 0xFF
if key == escape_key:
break
cv2.destroyAllWindows()
<commit_msg>Print to stdout the changed video<commit_after>#!/usr/bin/python
import cv2
import ImageReader
import numpy as np
import sys
escape_key = 27
reader = ImageReader.ImageReader()
fgbg = cv2.createBackgroundSubtractorMOG2()
while True:
imgread, img = reader.decode()
if imgread:
fgmask = fgbg.apply(img)
retval, encodedimage = cv2.imencode(".jpg", fgmask)
np.savetxt(sys.stdout, encodedimage, fmt='%c', newline='')
key = cv2.waitKey(1) & 0xFF
if key == escape_key:
break
cv2.destroyAllWindows()
|
252b0f5e69b7dddb0560e1ac37de1e6ea6e38bb9 | app.py | app.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from flask import Flask, request, json
from flask.ext.cors import CORS
import database
import rsser
# Update data before application is allowed to start
database.update_database()
app = Flask(__name__)
CORS(app)
@app.route('/speakercast/speakers')
def speakers():
speakers = [{'name': name, 'talks': count}
for count, name in database.get_all_speaker_and_counts()]
return json.dumps(speakers)
@app.route('/speakercast/generate', methods=['POST', 'OPTIONS'])
def generate():
if request.method == 'OPTIONS':
return ""
data = json.loads(request.data)
speakers = data['speakers']
id_ = database.generate_id(speakers)
print("Generating id ({}) for {}".format(id_, speakers))
return id_
@app.route('/speakercast/feed/<id>')
def feed(id):
speakers = database.get_speakers(id)
if speakers is None:
# TODO: Send some error
return "ERROR"
talks = database.get_talks(speakers)
return rsser.create_rss_feed(talks=talks, speakers=list(speakers))
if __name__ == "__main__":
app.run(debug=True)
| #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from flask import Flask, request, json
from flask.ext.cors import CORS
import database
import rsser
# Update data before application is allowed to start
database.update_database()
app = Flask(__name__)
CORS(app)
@app.route('/speakercast/speakers')
def speakers():
speakers = [{'name': name, 'talks': count}
for count, name in database.get_all_speaker_and_counts()]
return json.dumps(speakers)
@app.route('/speakercast/generate', methods=['POST', 'OPTIONS'])
def generate():
if request.method == 'OPTIONS':
return ""
data = json.loads(request.data)
speakers = data['speakers']
if len(speakers) == 0:
return ""
id_ = database.generate_id(speakers)
print("Generated id ({}) for {}".format(id_, speakers))
return id_
@app.route('/speakercast/feed/<id>')
def feed(id):
speakers = database.get_speakers(id)
if speakers is None:
# TODO: Send some error
return "ERROR"
talks = database.get_talks(speakers)
return rsser.create_rss_feed(talks=talks, speakers=list(speakers))
if __name__ == "__main__":
app.run(debug=True)
| Handle case of generating ID with no speakers | Handle case of generating ID with no speakers
| Python | bsd-3-clause | philipbl/talk_feed,philipbl/SpeakerCast | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from flask import Flask, request, json
from flask.ext.cors import CORS
import database
import rsser
# Update data before application is allowed to start
database.update_database()
app = Flask(__name__)
CORS(app)
@app.route('/speakercast/speakers')
def speakers():
speakers = [{'name': name, 'talks': count}
for count, name in database.get_all_speaker_and_counts()]
return json.dumps(speakers)
@app.route('/speakercast/generate', methods=['POST', 'OPTIONS'])
def generate():
if request.method == 'OPTIONS':
return ""
data = json.loads(request.data)
speakers = data['speakers']
id_ = database.generate_id(speakers)
print("Generating id ({}) for {}".format(id_, speakers))
return id_
@app.route('/speakercast/feed/<id>')
def feed(id):
speakers = database.get_speakers(id)
if speakers is None:
# TODO: Send some error
return "ERROR"
talks = database.get_talks(speakers)
return rsser.create_rss_feed(talks=talks, speakers=list(speakers))
if __name__ == "__main__":
app.run(debug=True)
Handle case of generating ID with no speakers | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from flask import Flask, request, json
from flask.ext.cors import CORS
import database
import rsser
# Update data before application is allowed to start
database.update_database()
app = Flask(__name__)
CORS(app)
@app.route('/speakercast/speakers')
def speakers():
speakers = [{'name': name, 'talks': count}
for count, name in database.get_all_speaker_and_counts()]
return json.dumps(speakers)
@app.route('/speakercast/generate', methods=['POST', 'OPTIONS'])
def generate():
if request.method == 'OPTIONS':
return ""
data = json.loads(request.data)
speakers = data['speakers']
if len(speakers) == 0:
return ""
id_ = database.generate_id(speakers)
print("Generated id ({}) for {}".format(id_, speakers))
return id_
@app.route('/speakercast/feed/<id>')
def feed(id):
speakers = database.get_speakers(id)
if speakers is None:
# TODO: Send some error
return "ERROR"
talks = database.get_talks(speakers)
return rsser.create_rss_feed(talks=talks, speakers=list(speakers))
if __name__ == "__main__":
app.run(debug=True)
| <commit_before>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from flask import Flask, request, json
from flask.ext.cors import CORS
import database
import rsser
# Update data before application is allowed to start
database.update_database()
app = Flask(__name__)
CORS(app)
@app.route('/speakercast/speakers')
def speakers():
speakers = [{'name': name, 'talks': count}
for count, name in database.get_all_speaker_and_counts()]
return json.dumps(speakers)
@app.route('/speakercast/generate', methods=['POST', 'OPTIONS'])
def generate():
if request.method == 'OPTIONS':
return ""
data = json.loads(request.data)
speakers = data['speakers']
id_ = database.generate_id(speakers)
print("Generating id ({}) for {}".format(id_, speakers))
return id_
@app.route('/speakercast/feed/<id>')
def feed(id):
speakers = database.get_speakers(id)
if speakers is None:
# TODO: Send some error
return "ERROR"
talks = database.get_talks(speakers)
return rsser.create_rss_feed(talks=talks, speakers=list(speakers))
if __name__ == "__main__":
app.run(debug=True)
<commit_msg>Handle case of generating ID with no speakers<commit_after> | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from flask import Flask, request, json
from flask.ext.cors import CORS
import database
import rsser
# Update data before application is allowed to start
database.update_database()
app = Flask(__name__)
CORS(app)
@app.route('/speakercast/speakers')
def speakers():
speakers = [{'name': name, 'talks': count}
for count, name in database.get_all_speaker_and_counts()]
return json.dumps(speakers)
@app.route('/speakercast/generate', methods=['POST', 'OPTIONS'])
def generate():
if request.method == 'OPTIONS':
return ""
data = json.loads(request.data)
speakers = data['speakers']
if len(speakers) == 0:
return ""
id_ = database.generate_id(speakers)
print("Generated id ({}) for {}".format(id_, speakers))
return id_
@app.route('/speakercast/feed/<id>')
def feed(id):
speakers = database.get_speakers(id)
if speakers is None:
# TODO: Send some error
return "ERROR"
talks = database.get_talks(speakers)
return rsser.create_rss_feed(talks=talks, speakers=list(speakers))
if __name__ == "__main__":
app.run(debug=True)
| #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from flask import Flask, request, json
from flask.ext.cors import CORS
import database
import rsser
# Update data before application is allowed to start
database.update_database()
app = Flask(__name__)
CORS(app)
@app.route('/speakercast/speakers')
def speakers():
speakers = [{'name': name, 'talks': count}
for count, name in database.get_all_speaker_and_counts()]
return json.dumps(speakers)
@app.route('/speakercast/generate', methods=['POST', 'OPTIONS'])
def generate():
if request.method == 'OPTIONS':
return ""
data = json.loads(request.data)
speakers = data['speakers']
id_ = database.generate_id(speakers)
print("Generating id ({}) for {}".format(id_, speakers))
return id_
@app.route('/speakercast/feed/<id>')
def feed(id):
speakers = database.get_speakers(id)
if speakers is None:
# TODO: Send some error
return "ERROR"
talks = database.get_talks(speakers)
return rsser.create_rss_feed(talks=talks, speakers=list(speakers))
if __name__ == "__main__":
app.run(debug=True)
Handle case of generating ID with no speakers#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from flask import Flask, request, json
from flask.ext.cors import CORS
import database
import rsser
# Update data before application is allowed to start
database.update_database()
app = Flask(__name__)
CORS(app)
@app.route('/speakercast/speakers')
def speakers():
speakers = [{'name': name, 'talks': count}
for count, name in database.get_all_speaker_and_counts()]
return json.dumps(speakers)
@app.route('/speakercast/generate', methods=['POST', 'OPTIONS'])
def generate():
if request.method == 'OPTIONS':
return ""
data = json.loads(request.data)
speakers = data['speakers']
if len(speakers) == 0:
return ""
id_ = database.generate_id(speakers)
print("Generated id ({}) for {}".format(id_, speakers))
return id_
@app.route('/speakercast/feed/<id>')
def feed(id):
speakers = database.get_speakers(id)
if speakers is None:
# TODO: Send some error
return "ERROR"
talks = database.get_talks(speakers)
return rsser.create_rss_feed(talks=talks, speakers=list(speakers))
if __name__ == "__main__":
app.run(debug=True)
| <commit_before>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from flask import Flask, request, json
from flask.ext.cors import CORS
import database
import rsser
# Update data before application is allowed to start
database.update_database()
app = Flask(__name__)
CORS(app)
@app.route('/speakercast/speakers')
def speakers():
speakers = [{'name': name, 'talks': count}
for count, name in database.get_all_speaker_and_counts()]
return json.dumps(speakers)
@app.route('/speakercast/generate', methods=['POST', 'OPTIONS'])
def generate():
if request.method == 'OPTIONS':
return ""
data = json.loads(request.data)
speakers = data['speakers']
id_ = database.generate_id(speakers)
print("Generating id ({}) for {}".format(id_, speakers))
return id_
@app.route('/speakercast/feed/<id>')
def feed(id):
speakers = database.get_speakers(id)
if speakers is None:
# TODO: Send some error
return "ERROR"
talks = database.get_talks(speakers)
return rsser.create_rss_feed(talks=talks, speakers=list(speakers))
if __name__ == "__main__":
app.run(debug=True)
<commit_msg>Handle case of generating ID with no speakers<commit_after>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from flask import Flask, request, json
from flask.ext.cors import CORS
import database
import rsser
# Update data before application is allowed to start
database.update_database()
app = Flask(__name__)
CORS(app)
@app.route('/speakercast/speakers')
def speakers():
speakers = [{'name': name, 'talks': count}
for count, name in database.get_all_speaker_and_counts()]
return json.dumps(speakers)
@app.route('/speakercast/generate', methods=['POST', 'OPTIONS'])
def generate():
if request.method == 'OPTIONS':
return ""
data = json.loads(request.data)
speakers = data['speakers']
if len(speakers) == 0:
return ""
id_ = database.generate_id(speakers)
print("Generated id ({}) for {}".format(id_, speakers))
return id_
@app.route('/speakercast/feed/<id>')
def feed(id):
speakers = database.get_speakers(id)
if speakers is None:
# TODO: Send some error
return "ERROR"
talks = database.get_talks(speakers)
return rsser.create_rss_feed(talks=talks, speakers=list(speakers))
if __name__ == "__main__":
app.run(debug=True)
|
e198eb0fe6e4a916e2207588f4123675afe15bcf | functions/scale_grad.py | functions/scale_grad.py | import numpy
import chainer
from chainer.utils import type_check
class ScaleGrad(chainer.Function):
def __init__(self, scale=1.0):
self.scale = scale
def check_type_forward(self, in_types):
type_check.expect(
in_types.size() == 1,
in_types[0].dtype == numpy.float32
)
def forward(self, x):
return x
def backward(self, x, gy):
return tuple(g * self.scale for g in gy)
def scale_grad(x, scale):
return ScaleGrad(scale=scale)(x)
| import numpy
import chainer
from chainer.utils import type_check
class ScaleGrad(chainer.Function):
def __init__(self, scale):
self.scale = scale
def check_type_forward(self, in_types):
type_check.expect(
in_types.size() == 1,
in_types[0].dtype == numpy.float32
)
def forward(self, x):
return x
def backward(self, x, gy):
return tuple(g * self.scale for g in gy)
def scale_grad(x, scale):
return ScaleGrad(scale=scale)(x)
| Remove the default value for scale | Remove the default value for scale
| Python | mit | toslunar/chainerrl,toslunar/chainerrl | import numpy
import chainer
from chainer.utils import type_check
class ScaleGrad(chainer.Function):
def __init__(self, scale=1.0):
self.scale = scale
def check_type_forward(self, in_types):
type_check.expect(
in_types.size() == 1,
in_types[0].dtype == numpy.float32
)
def forward(self, x):
return x
def backward(self, x, gy):
return tuple(g * self.scale for g in gy)
def scale_grad(x, scale):
return ScaleGrad(scale=scale)(x)
Remove the default value for scale | import numpy
import chainer
from chainer.utils import type_check
class ScaleGrad(chainer.Function):
def __init__(self, scale):
self.scale = scale
def check_type_forward(self, in_types):
type_check.expect(
in_types.size() == 1,
in_types[0].dtype == numpy.float32
)
def forward(self, x):
return x
def backward(self, x, gy):
return tuple(g * self.scale for g in gy)
def scale_grad(x, scale):
return ScaleGrad(scale=scale)(x)
| <commit_before>import numpy
import chainer
from chainer.utils import type_check
class ScaleGrad(chainer.Function):
def __init__(self, scale=1.0):
self.scale = scale
def check_type_forward(self, in_types):
type_check.expect(
in_types.size() == 1,
in_types[0].dtype == numpy.float32
)
def forward(self, x):
return x
def backward(self, x, gy):
return tuple(g * self.scale for g in gy)
def scale_grad(x, scale):
return ScaleGrad(scale=scale)(x)
<commit_msg>Remove the default value for scale<commit_after> | import numpy
import chainer
from chainer.utils import type_check
class ScaleGrad(chainer.Function):
def __init__(self, scale):
self.scale = scale
def check_type_forward(self, in_types):
type_check.expect(
in_types.size() == 1,
in_types[0].dtype == numpy.float32
)
def forward(self, x):
return x
def backward(self, x, gy):
return tuple(g * self.scale for g in gy)
def scale_grad(x, scale):
return ScaleGrad(scale=scale)(x)
| import numpy
import chainer
from chainer.utils import type_check
class ScaleGrad(chainer.Function):
def __init__(self, scale=1.0):
self.scale = scale
def check_type_forward(self, in_types):
type_check.expect(
in_types.size() == 1,
in_types[0].dtype == numpy.float32
)
def forward(self, x):
return x
def backward(self, x, gy):
return tuple(g * self.scale for g in gy)
def scale_grad(x, scale):
return ScaleGrad(scale=scale)(x)
Remove the default value for scaleimport numpy
import chainer
from chainer.utils import type_check
class ScaleGrad(chainer.Function):
def __init__(self, scale):
self.scale = scale
def check_type_forward(self, in_types):
type_check.expect(
in_types.size() == 1,
in_types[0].dtype == numpy.float32
)
def forward(self, x):
return x
def backward(self, x, gy):
return tuple(g * self.scale for g in gy)
def scale_grad(x, scale):
return ScaleGrad(scale=scale)(x)
| <commit_before>import numpy
import chainer
from chainer.utils import type_check
class ScaleGrad(chainer.Function):
def __init__(self, scale=1.0):
self.scale = scale
def check_type_forward(self, in_types):
type_check.expect(
in_types.size() == 1,
in_types[0].dtype == numpy.float32
)
def forward(self, x):
return x
def backward(self, x, gy):
return tuple(g * self.scale for g in gy)
def scale_grad(x, scale):
return ScaleGrad(scale=scale)(x)
<commit_msg>Remove the default value for scale<commit_after>import numpy
import chainer
from chainer.utils import type_check
class ScaleGrad(chainer.Function):
def __init__(self, scale):
self.scale = scale
def check_type_forward(self, in_types):
type_check.expect(
in_types.size() == 1,
in_types[0].dtype == numpy.float32
)
def forward(self, x):
return x
def backward(self, x, gy):
return tuple(g * self.scale for g in gy)
def scale_grad(x, scale):
return ScaleGrad(scale=scale)(x)
|
8771bbdba5b10a3b9fab2822eccdec64d221edb4 | catalog/admin.py | catalog/admin.py | from django.contrib import admin
from .models import Author, Book, BookInstance, Genre, Language
# admin.site.register(Book)
# admin.site.register(Author)
admin.site.register(Genre)
# admin.site.register(BookInstance)
admin.site.register(Language)
# Define the admin class
class AuthorAdmin(admin.ModelAdmin):
list_display = ('last_name', 'first_name', 'date_of_birth', 'date_of_death')
fields = ['first_name', 'last_name', ('date_of_birth', 'date_of_death')]
# Register the admin class with the associated model
admin.site.register(Author, AuthorAdmin)
# Register the Admin classes for Book using the decorator
class BooksInstanceInline(admin.TabularInline):
model = BookInstance
@admin.register(Book)
class BookAdmin(admin.ModelAdmin):
list_display = ('title', 'author', 'display_genre')
inlines = [BooksInstanceInline]
# Register the Admin classes for BookInstance using the decorator
@admin.register(BookInstance)
class BookInstanceAdmin(admin.ModelAdmin):
list_filter = ('status', 'due_back')
fieldsets = (
(None, {
'fields': ('book', 'imprint', 'id')
}),
('Availability', {
'fields': ('status', 'due_back')
}),
)
| from django.contrib import admin
from .models import Author, Book, BookInstance, Genre, Language
# admin.site.register(Book)
# admin.site.register(Author)
admin.site.register(Genre)
# admin.site.register(BookInstance)
admin.site.register(Language)
class AuthorsInstanceInline(admin.TabularInline):
model = Book
# Define the admin class
class AuthorAdmin(admin.ModelAdmin):
list_display = ('last_name', 'first_name', 'date_of_birth', 'date_of_death')
fields = ['first_name', 'last_name', ('date_of_birth', 'date_of_death')]
inlines = [AuthorsInstanceInline]
# Register the admin class with the associated model
admin.site.register(Author, AuthorAdmin)
# Register the Admin classes for Book using the decorator
class BooksInstanceInline(admin.TabularInline):
model = BookInstance
@admin.register(Book)
class BookAdmin(admin.ModelAdmin):
list_display = ('title', 'author', 'display_genre')
inlines = [BooksInstanceInline]
# Register the Admin classes for BookInstance using the decorator
@admin.register(BookInstance)
class BookInstanceAdmin(admin.ModelAdmin):
list_filter = ('status', 'due_back')
fieldsets = (
(None, {
'fields': ('book', 'imprint', 'id')
}),
('Availability', {
'fields': ('status', 'due_back')
}),
)
list_display = ('book', 'status', 'due_back', 'id')
| Configure BookInstance list view and add an inline listing | Configure BookInstance list view and add an inline listing
| Python | bsd-3-clause | pavlenk0/my-catalog,pavlenk0/my-catalog | from django.contrib import admin
from .models import Author, Book, BookInstance, Genre, Language
# admin.site.register(Book)
# admin.site.register(Author)
admin.site.register(Genre)
# admin.site.register(BookInstance)
admin.site.register(Language)
# Define the admin class
class AuthorAdmin(admin.ModelAdmin):
list_display = ('last_name', 'first_name', 'date_of_birth', 'date_of_death')
fields = ['first_name', 'last_name', ('date_of_birth', 'date_of_death')]
# Register the admin class with the associated model
admin.site.register(Author, AuthorAdmin)
# Register the Admin classes for Book using the decorator
class BooksInstanceInline(admin.TabularInline):
model = BookInstance
@admin.register(Book)
class BookAdmin(admin.ModelAdmin):
list_display = ('title', 'author', 'display_genre')
inlines = [BooksInstanceInline]
# Register the Admin classes for BookInstance using the decorator
@admin.register(BookInstance)
class BookInstanceAdmin(admin.ModelAdmin):
list_filter = ('status', 'due_back')
fieldsets = (
(None, {
'fields': ('book', 'imprint', 'id')
}),
('Availability', {
'fields': ('status', 'due_back')
}),
)
Configure BookInstance list view and add an inline listing | from django.contrib import admin
from .models import Author, Book, BookInstance, Genre, Language
# admin.site.register(Book)
# admin.site.register(Author)
admin.site.register(Genre)
# admin.site.register(BookInstance)
admin.site.register(Language)
class AuthorsInstanceInline(admin.TabularInline):
model = Book
# Define the admin class
class AuthorAdmin(admin.ModelAdmin):
list_display = ('last_name', 'first_name', 'date_of_birth', 'date_of_death')
fields = ['first_name', 'last_name', ('date_of_birth', 'date_of_death')]
inlines = [AuthorsInstanceInline]
# Register the admin class with the associated model
admin.site.register(Author, AuthorAdmin)
# Register the Admin classes for Book using the decorator
class BooksInstanceInline(admin.TabularInline):
model = BookInstance
@admin.register(Book)
class BookAdmin(admin.ModelAdmin):
list_display = ('title', 'author', 'display_genre')
inlines = [BooksInstanceInline]
# Register the Admin classes for BookInstance using the decorator
@admin.register(BookInstance)
class BookInstanceAdmin(admin.ModelAdmin):
list_filter = ('status', 'due_back')
fieldsets = (
(None, {
'fields': ('book', 'imprint', 'id')
}),
('Availability', {
'fields': ('status', 'due_back')
}),
)
list_display = ('book', 'status', 'due_back', 'id')
| <commit_before>from django.contrib import admin
from .models import Author, Book, BookInstance, Genre, Language
# admin.site.register(Book)
# admin.site.register(Author)
admin.site.register(Genre)
# admin.site.register(BookInstance)
admin.site.register(Language)
# Define the admin class
class AuthorAdmin(admin.ModelAdmin):
list_display = ('last_name', 'first_name', 'date_of_birth', 'date_of_death')
fields = ['first_name', 'last_name', ('date_of_birth', 'date_of_death')]
# Register the admin class with the associated model
admin.site.register(Author, AuthorAdmin)
# Register the Admin classes for Book using the decorator
class BooksInstanceInline(admin.TabularInline):
model = BookInstance
@admin.register(Book)
class BookAdmin(admin.ModelAdmin):
list_display = ('title', 'author', 'display_genre')
inlines = [BooksInstanceInline]
# Register the Admin classes for BookInstance using the decorator
@admin.register(BookInstance)
class BookInstanceAdmin(admin.ModelAdmin):
list_filter = ('status', 'due_back')
fieldsets = (
(None, {
'fields': ('book', 'imprint', 'id')
}),
('Availability', {
'fields': ('status', 'due_back')
}),
)
<commit_msg>Configure BookInstance list view and add an inline listing <commit_after> | from django.contrib import admin
from .models import Author, Book, BookInstance, Genre, Language
# admin.site.register(Book)
# admin.site.register(Author)
admin.site.register(Genre)
# admin.site.register(BookInstance)
admin.site.register(Language)
class AuthorsInstanceInline(admin.TabularInline):
model = Book
# Define the admin class
class AuthorAdmin(admin.ModelAdmin):
list_display = ('last_name', 'first_name', 'date_of_birth', 'date_of_death')
fields = ['first_name', 'last_name', ('date_of_birth', 'date_of_death')]
inlines = [AuthorsInstanceInline]
# Register the admin class with the associated model
admin.site.register(Author, AuthorAdmin)
# Register the Admin classes for Book using the decorator
class BooksInstanceInline(admin.TabularInline):
model = BookInstance
@admin.register(Book)
class BookAdmin(admin.ModelAdmin):
list_display = ('title', 'author', 'display_genre')
inlines = [BooksInstanceInline]
# Register the Admin classes for BookInstance using the decorator
@admin.register(BookInstance)
class BookInstanceAdmin(admin.ModelAdmin):
list_filter = ('status', 'due_back')
fieldsets = (
(None, {
'fields': ('book', 'imprint', 'id')
}),
('Availability', {
'fields': ('status', 'due_back')
}),
)
list_display = ('book', 'status', 'due_back', 'id')
| from django.contrib import admin
from .models import Author, Book, BookInstance, Genre, Language
# admin.site.register(Book)
# admin.site.register(Author)
admin.site.register(Genre)
# admin.site.register(BookInstance)
admin.site.register(Language)
# Define the admin class
class AuthorAdmin(admin.ModelAdmin):
list_display = ('last_name', 'first_name', 'date_of_birth', 'date_of_death')
fields = ['first_name', 'last_name', ('date_of_birth', 'date_of_death')]
# Register the admin class with the associated model
admin.site.register(Author, AuthorAdmin)
# Register the Admin classes for Book using the decorator
class BooksInstanceInline(admin.TabularInline):
model = BookInstance
@admin.register(Book)
class BookAdmin(admin.ModelAdmin):
list_display = ('title', 'author', 'display_genre')
inlines = [BooksInstanceInline]
# Register the Admin classes for BookInstance using the decorator
@admin.register(BookInstance)
class BookInstanceAdmin(admin.ModelAdmin):
list_filter = ('status', 'due_back')
fieldsets = (
(None, {
'fields': ('book', 'imprint', 'id')
}),
('Availability', {
'fields': ('status', 'due_back')
}),
)
Configure BookInstance list view and add an inline listing from django.contrib import admin
from .models import Author, Book, BookInstance, Genre, Language
# admin.site.register(Book)
# admin.site.register(Author)
admin.site.register(Genre)
# admin.site.register(BookInstance)
admin.site.register(Language)
class AuthorsInstanceInline(admin.TabularInline):
model = Book
# Define the admin class
class AuthorAdmin(admin.ModelAdmin):
list_display = ('last_name', 'first_name', 'date_of_birth', 'date_of_death')
fields = ['first_name', 'last_name', ('date_of_birth', 'date_of_death')]
inlines = [AuthorsInstanceInline]
# Register the admin class with the associated model
admin.site.register(Author, AuthorAdmin)
# Register the Admin classes for Book using the decorator
class BooksInstanceInline(admin.TabularInline):
model = BookInstance
@admin.register(Book)
class BookAdmin(admin.ModelAdmin):
list_display = ('title', 'author', 'display_genre')
inlines = [BooksInstanceInline]
# Register the Admin classes for BookInstance using the decorator
@admin.register(BookInstance)
class BookInstanceAdmin(admin.ModelAdmin):
list_filter = ('status', 'due_back')
fieldsets = (
(None, {
'fields': ('book', 'imprint', 'id')
}),
('Availability', {
'fields': ('status', 'due_back')
}),
)
list_display = ('book', 'status', 'due_back', 'id')
| <commit_before>from django.contrib import admin
from .models import Author, Book, BookInstance, Genre, Language
# admin.site.register(Book)
# admin.site.register(Author)
admin.site.register(Genre)
# admin.site.register(BookInstance)
admin.site.register(Language)
# Define the admin class
class AuthorAdmin(admin.ModelAdmin):
list_display = ('last_name', 'first_name', 'date_of_birth', 'date_of_death')
fields = ['first_name', 'last_name', ('date_of_birth', 'date_of_death')]
# Register the admin class with the associated model
admin.site.register(Author, AuthorAdmin)
# Register the Admin classes for Book using the decorator
class BooksInstanceInline(admin.TabularInline):
model = BookInstance
@admin.register(Book)
class BookAdmin(admin.ModelAdmin):
list_display = ('title', 'author', 'display_genre')
inlines = [BooksInstanceInline]
# Register the Admin classes for BookInstance using the decorator
@admin.register(BookInstance)
class BookInstanceAdmin(admin.ModelAdmin):
list_filter = ('status', 'due_back')
fieldsets = (
(None, {
'fields': ('book', 'imprint', 'id')
}),
('Availability', {
'fields': ('status', 'due_back')
}),
)
<commit_msg>Configure BookInstance list view and add an inline listing <commit_after>from django.contrib import admin
from .models import Author, Book, BookInstance, Genre, Language
# admin.site.register(Book)
# admin.site.register(Author)
admin.site.register(Genre)
# admin.site.register(BookInstance)
admin.site.register(Language)
class AuthorsInstanceInline(admin.TabularInline):
model = Book
# Define the admin class
class AuthorAdmin(admin.ModelAdmin):
list_display = ('last_name', 'first_name', 'date_of_birth', 'date_of_death')
fields = ['first_name', 'last_name', ('date_of_birth', 'date_of_death')]
inlines = [AuthorsInstanceInline]
# Register the admin class with the associated model
admin.site.register(Author, AuthorAdmin)
# Register the Admin classes for Book using the decorator
class BooksInstanceInline(admin.TabularInline):
model = BookInstance
@admin.register(Book)
class BookAdmin(admin.ModelAdmin):
list_display = ('title', 'author', 'display_genre')
inlines = [BooksInstanceInline]
# Register the Admin classes for BookInstance using the decorator
@admin.register(BookInstance)
class BookInstanceAdmin(admin.ModelAdmin):
list_filter = ('status', 'due_back')
fieldsets = (
(None, {
'fields': ('book', 'imprint', 'id')
}),
('Availability', {
'fields': ('status', 'due_back')
}),
)
list_display = ('book', 'status', 'due_back', 'id')
|
fe34a904af1d691f96b19c87ee11129eecb09dc5 | byceps/blueprints/snippet_admin/service.py | byceps/blueprints/snippet_admin/service.py | # -*- coding: utf-8 -*-
"""
byceps.blueprints.snippet_admin.service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2016 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from difflib import HtmlDiff
from ...database import db
from ..party.models import Party
from ..snippet.models.snippet import Snippet
def get_parties_with_snippet_counts():
"""Yield (party, snippet count) pairs."""
parties = Party.query.all()
snippet_counts_by_party_id = _get_snippet_counts_by_party_id()
for party in parties:
snippet_count = snippet_counts_by_party_id.get(party.id, 0)
yield party, snippet_count
def _get_snippet_counts_by_party_id():
return dict(db.session \
.query(
Snippet.party_id,
db.func.count(Snippet.id)
) \
.group_by(Snippet.party_id) \
.all())
def create_html_diff(from_text, to_text, from_description, to_description,
*, numlines=3):
"""Calculate the difference between the two texts and render it as HTML."""
from_lines = from_text.split('\n')
to_lines = to_text.split('\n')
return HtmlDiff().make_table(from_lines, to_lines,
from_description, to_description,
context=True, numlines=numlines)
| # -*- coding: utf-8 -*-
"""
byceps.blueprints.snippet_admin.service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2016 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from difflib import HtmlDiff
from ...database import db
from ..party.models import Party
from ..snippet.models.snippet import Snippet
def get_parties_with_snippet_counts():
"""Yield (party, snippet count) pairs."""
parties = Party.query.all()
snippet_counts_by_party_id = _get_snippet_counts_by_party_id()
for party in parties:
snippet_count = snippet_counts_by_party_id.get(party.id, 0)
yield party, snippet_count
def _get_snippet_counts_by_party_id():
return dict(db.session \
.query(
Snippet.party_id,
db.func.count(Snippet.id)
) \
.group_by(Snippet.party_id) \
.all())
def create_html_diff(from_text, to_text, from_description, to_description,
*, numlines=3):
"""Calculate the difference between the two texts and render it as HTML."""
from_lines = (from_text or '').split('\n')
to_lines = (to_text or '').split('\n')
return HtmlDiff().make_table(from_lines, to_lines,
from_description, to_description,
context=True, numlines=numlines)
| Handle values to be compared being `None`. | Handle values to be compared being `None`.
| Python | bsd-3-clause | m-ober/byceps,homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps,m-ober/byceps,m-ober/byceps | # -*- coding: utf-8 -*-
"""
byceps.blueprints.snippet_admin.service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2016 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from difflib import HtmlDiff
from ...database import db
from ..party.models import Party
from ..snippet.models.snippet import Snippet
def get_parties_with_snippet_counts():
"""Yield (party, snippet count) pairs."""
parties = Party.query.all()
snippet_counts_by_party_id = _get_snippet_counts_by_party_id()
for party in parties:
snippet_count = snippet_counts_by_party_id.get(party.id, 0)
yield party, snippet_count
def _get_snippet_counts_by_party_id():
return dict(db.session \
.query(
Snippet.party_id,
db.func.count(Snippet.id)
) \
.group_by(Snippet.party_id) \
.all())
def create_html_diff(from_text, to_text, from_description, to_description,
*, numlines=3):
"""Calculate the difference between the two texts and render it as HTML."""
from_lines = from_text.split('\n')
to_lines = to_text.split('\n')
return HtmlDiff().make_table(from_lines, to_lines,
from_description, to_description,
context=True, numlines=numlines)
Handle values to be compared being `None`. | # -*- coding: utf-8 -*-
"""
byceps.blueprints.snippet_admin.service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2016 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from difflib import HtmlDiff
from ...database import db
from ..party.models import Party
from ..snippet.models.snippet import Snippet
def get_parties_with_snippet_counts():
"""Yield (party, snippet count) pairs."""
parties = Party.query.all()
snippet_counts_by_party_id = _get_snippet_counts_by_party_id()
for party in parties:
snippet_count = snippet_counts_by_party_id.get(party.id, 0)
yield party, snippet_count
def _get_snippet_counts_by_party_id():
return dict(db.session \
.query(
Snippet.party_id,
db.func.count(Snippet.id)
) \
.group_by(Snippet.party_id) \
.all())
def create_html_diff(from_text, to_text, from_description, to_description,
*, numlines=3):
"""Calculate the difference between the two texts and render it as HTML."""
from_lines = (from_text or '').split('\n')
to_lines = (to_text or '').split('\n')
return HtmlDiff().make_table(from_lines, to_lines,
from_description, to_description,
context=True, numlines=numlines)
| <commit_before># -*- coding: utf-8 -*-
"""
byceps.blueprints.snippet_admin.service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2016 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from difflib import HtmlDiff
from ...database import db
from ..party.models import Party
from ..snippet.models.snippet import Snippet
def get_parties_with_snippet_counts():
"""Yield (party, snippet count) pairs."""
parties = Party.query.all()
snippet_counts_by_party_id = _get_snippet_counts_by_party_id()
for party in parties:
snippet_count = snippet_counts_by_party_id.get(party.id, 0)
yield party, snippet_count
def _get_snippet_counts_by_party_id():
return dict(db.session \
.query(
Snippet.party_id,
db.func.count(Snippet.id)
) \
.group_by(Snippet.party_id) \
.all())
def create_html_diff(from_text, to_text, from_description, to_description,
*, numlines=3):
"""Calculate the difference between the two texts and render it as HTML."""
from_lines = from_text.split('\n')
to_lines = to_text.split('\n')
return HtmlDiff().make_table(from_lines, to_lines,
from_description, to_description,
context=True, numlines=numlines)
<commit_msg>Handle values to be compared being `None`.<commit_after> | # -*- coding: utf-8 -*-
"""
byceps.blueprints.snippet_admin.service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2016 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from difflib import HtmlDiff
from ...database import db
from ..party.models import Party
from ..snippet.models.snippet import Snippet
def get_parties_with_snippet_counts():
"""Yield (party, snippet count) pairs."""
parties = Party.query.all()
snippet_counts_by_party_id = _get_snippet_counts_by_party_id()
for party in parties:
snippet_count = snippet_counts_by_party_id.get(party.id, 0)
yield party, snippet_count
def _get_snippet_counts_by_party_id():
return dict(db.session \
.query(
Snippet.party_id,
db.func.count(Snippet.id)
) \
.group_by(Snippet.party_id) \
.all())
def create_html_diff(from_text, to_text, from_description, to_description,
*, numlines=3):
"""Calculate the difference between the two texts and render it as HTML."""
from_lines = (from_text or '').split('\n')
to_lines = (to_text or '').split('\n')
return HtmlDiff().make_table(from_lines, to_lines,
from_description, to_description,
context=True, numlines=numlines)
| # -*- coding: utf-8 -*-
"""
byceps.blueprints.snippet_admin.service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2016 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from difflib import HtmlDiff
from ...database import db
from ..party.models import Party
from ..snippet.models.snippet import Snippet
def get_parties_with_snippet_counts():
"""Yield (party, snippet count) pairs."""
parties = Party.query.all()
snippet_counts_by_party_id = _get_snippet_counts_by_party_id()
for party in parties:
snippet_count = snippet_counts_by_party_id.get(party.id, 0)
yield party, snippet_count
def _get_snippet_counts_by_party_id():
return dict(db.session \
.query(
Snippet.party_id,
db.func.count(Snippet.id)
) \
.group_by(Snippet.party_id) \
.all())
def create_html_diff(from_text, to_text, from_description, to_description,
*, numlines=3):
"""Calculate the difference between the two texts and render it as HTML."""
from_lines = from_text.split('\n')
to_lines = to_text.split('\n')
return HtmlDiff().make_table(from_lines, to_lines,
from_description, to_description,
context=True, numlines=numlines)
Handle values to be compared being `None`.# -*- coding: utf-8 -*-
"""
byceps.blueprints.snippet_admin.service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2016 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from difflib import HtmlDiff
from ...database import db
from ..party.models import Party
from ..snippet.models.snippet import Snippet
def get_parties_with_snippet_counts():
"""Yield (party, snippet count) pairs."""
parties = Party.query.all()
snippet_counts_by_party_id = _get_snippet_counts_by_party_id()
for party in parties:
snippet_count = snippet_counts_by_party_id.get(party.id, 0)
yield party, snippet_count
def _get_snippet_counts_by_party_id():
return dict(db.session \
.query(
Snippet.party_id,
db.func.count(Snippet.id)
) \
.group_by(Snippet.party_id) \
.all())
def create_html_diff(from_text, to_text, from_description, to_description,
*, numlines=3):
"""Calculate the difference between the two texts and render it as HTML."""
from_lines = (from_text or '').split('\n')
to_lines = (to_text or '').split('\n')
return HtmlDiff().make_table(from_lines, to_lines,
from_description, to_description,
context=True, numlines=numlines)
| <commit_before># -*- coding: utf-8 -*-
"""
byceps.blueprints.snippet_admin.service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2016 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from difflib import HtmlDiff
from ...database import db
from ..party.models import Party
from ..snippet.models.snippet import Snippet
def get_parties_with_snippet_counts():
"""Yield (party, snippet count) pairs."""
parties = Party.query.all()
snippet_counts_by_party_id = _get_snippet_counts_by_party_id()
for party in parties:
snippet_count = snippet_counts_by_party_id.get(party.id, 0)
yield party, snippet_count
def _get_snippet_counts_by_party_id():
return dict(db.session \
.query(
Snippet.party_id,
db.func.count(Snippet.id)
) \
.group_by(Snippet.party_id) \
.all())
def create_html_diff(from_text, to_text, from_description, to_description,
*, numlines=3):
"""Calculate the difference between the two texts and render it as HTML."""
from_lines = from_text.split('\n')
to_lines = to_text.split('\n')
return HtmlDiff().make_table(from_lines, to_lines,
from_description, to_description,
context=True, numlines=numlines)
<commit_msg>Handle values to be compared being `None`.<commit_after># -*- coding: utf-8 -*-
"""
byceps.blueprints.snippet_admin.service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2016 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from difflib import HtmlDiff
from ...database import db
from ..party.models import Party
from ..snippet.models.snippet import Snippet
def get_parties_with_snippet_counts():
"""Yield (party, snippet count) pairs."""
parties = Party.query.all()
snippet_counts_by_party_id = _get_snippet_counts_by_party_id()
for party in parties:
snippet_count = snippet_counts_by_party_id.get(party.id, 0)
yield party, snippet_count
def _get_snippet_counts_by_party_id():
return dict(db.session \
.query(
Snippet.party_id,
db.func.count(Snippet.id)
) \
.group_by(Snippet.party_id) \
.all())
def create_html_diff(from_text, to_text, from_description, to_description,
*, numlines=3):
"""Calculate the difference between the two texts and render it as HTML."""
from_lines = (from_text or '').split('\n')
to_lines = (to_text or '').split('\n')
return HtmlDiff().make_table(from_lines, to_lines,
from_description, to_description,
context=True, numlines=numlines)
|
946ef89ea55c30b9eb6684b4d73e96b05cf5d23d | aspen/server.py | aspen/server.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from algorithm import Algorithm
class Server(object):
def __init__(self, argv=None):
self.argv = argv
def get_algorithm(self):
return Algorithm('aspen.algorithms.server')
def get_website(self):
"""Return a website object. Useful in testing.
"""
algorithm = self.get_algorithm()
algorithm.run(argv=self.argv, _through='get_website_from_argv')
return algorithm.state['website']
def main(self, argv=None):
"""http://aspen.io/cli/
"""
try:
argv = argv if argv is not None else self.argv
algorithm = self.get_algorithm()
algorithm.run(argv=argv)
except (SystemExit, KeyboardInterrupt):
# Under some (most?) network engines, a SIGINT will be trapped by the
# SIGINT signal handler above. However, gevent does "something" with
# signals and our signal handler never fires. However, we *do* get a
# KeyboardInterrupt here in that case. *shrug*
#
# See: https://github.com/gittip/aspen-python/issues/196
pass
except:
import aspen, traceback
aspen.log_dammit("Oh no! Aspen crashed!")
aspen.log_dammit(traceback.format_exc())
if __name__ == '__main__':
Server().main()
| from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from algorithm import Algorithm
def main():
Server().main()
class Server(object):
def __init__(self, argv=None):
self.argv = argv
def get_algorithm(self):
return Algorithm('aspen.algorithms.server')
def get_website(self):
"""Return a website object. Useful in testing.
"""
algorithm = self.get_algorithm()
algorithm.run(argv=self.argv, _through='get_website_from_argv')
return algorithm.state['website']
def main(self, argv=None):
"""http://aspen.io/cli/
"""
try:
argv = argv if argv is not None else self.argv
algorithm = self.get_algorithm()
algorithm.run(argv=argv)
except (SystemExit, KeyboardInterrupt):
# Under some (most?) network engines, a SIGINT will be trapped by the
# SIGINT signal handler above. However, gevent does "something" with
# signals and our signal handler never fires. However, we *do* get a
# KeyboardInterrupt here in that case. *shrug*
#
# See: https://github.com/gittip/aspen-python/issues/196
pass
except:
import aspen, traceback
aspen.log_dammit("Oh no! Aspen crashed!")
aspen.log_dammit(traceback.format_exc())
if __name__ == '__main__':
main()
| Fix CLI api (was missing entrypoint hook) | Fix CLI api (was missing entrypoint hook)
| Python | mit | gratipay/aspen.py,gratipay/aspen.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from algorithm import Algorithm
class Server(object):
def __init__(self, argv=None):
self.argv = argv
def get_algorithm(self):
return Algorithm('aspen.algorithms.server')
def get_website(self):
"""Return a website object. Useful in testing.
"""
algorithm = self.get_algorithm()
algorithm.run(argv=self.argv, _through='get_website_from_argv')
return algorithm.state['website']
def main(self, argv=None):
"""http://aspen.io/cli/
"""
try:
argv = argv if argv is not None else self.argv
algorithm = self.get_algorithm()
algorithm.run(argv=argv)
except (SystemExit, KeyboardInterrupt):
# Under some (most?) network engines, a SIGINT will be trapped by the
# SIGINT signal handler above. However, gevent does "something" with
# signals and our signal handler never fires. However, we *do* get a
# KeyboardInterrupt here in that case. *shrug*
#
# See: https://github.com/gittip/aspen-python/issues/196
pass
except:
import aspen, traceback
aspen.log_dammit("Oh no! Aspen crashed!")
aspen.log_dammit(traceback.format_exc())
if __name__ == '__main__':
Server().main()
Fix CLI api (was missing entrypoint hook) | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from algorithm import Algorithm
def main():
Server().main()
class Server(object):
def __init__(self, argv=None):
self.argv = argv
def get_algorithm(self):
return Algorithm('aspen.algorithms.server')
def get_website(self):
"""Return a website object. Useful in testing.
"""
algorithm = self.get_algorithm()
algorithm.run(argv=self.argv, _through='get_website_from_argv')
return algorithm.state['website']
def main(self, argv=None):
"""http://aspen.io/cli/
"""
try:
argv = argv if argv is not None else self.argv
algorithm = self.get_algorithm()
algorithm.run(argv=argv)
except (SystemExit, KeyboardInterrupt):
# Under some (most?) network engines, a SIGINT will be trapped by the
# SIGINT signal handler above. However, gevent does "something" with
# signals and our signal handler never fires. However, we *do* get a
# KeyboardInterrupt here in that case. *shrug*
#
# See: https://github.com/gittip/aspen-python/issues/196
pass
except:
import aspen, traceback
aspen.log_dammit("Oh no! Aspen crashed!")
aspen.log_dammit(traceback.format_exc())
if __name__ == '__main__':
main()
| <commit_before>from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from algorithm import Algorithm
class Server(object):
def __init__(self, argv=None):
self.argv = argv
def get_algorithm(self):
return Algorithm('aspen.algorithms.server')
def get_website(self):
"""Return a website object. Useful in testing.
"""
algorithm = self.get_algorithm()
algorithm.run(argv=self.argv, _through='get_website_from_argv')
return algorithm.state['website']
def main(self, argv=None):
"""http://aspen.io/cli/
"""
try:
argv = argv if argv is not None else self.argv
algorithm = self.get_algorithm()
algorithm.run(argv=argv)
except (SystemExit, KeyboardInterrupt):
# Under some (most?) network engines, a SIGINT will be trapped by the
# SIGINT signal handler above. However, gevent does "something" with
# signals and our signal handler never fires. However, we *do* get a
# KeyboardInterrupt here in that case. *shrug*
#
# See: https://github.com/gittip/aspen-python/issues/196
pass
except:
import aspen, traceback
aspen.log_dammit("Oh no! Aspen crashed!")
aspen.log_dammit(traceback.format_exc())
if __name__ == '__main__':
Server().main()
<commit_msg>Fix CLI api (was missing entrypoint hook)<commit_after> | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from algorithm import Algorithm
def main():
Server().main()
class Server(object):
def __init__(self, argv=None):
self.argv = argv
def get_algorithm(self):
return Algorithm('aspen.algorithms.server')
def get_website(self):
"""Return a website object. Useful in testing.
"""
algorithm = self.get_algorithm()
algorithm.run(argv=self.argv, _through='get_website_from_argv')
return algorithm.state['website']
def main(self, argv=None):
"""http://aspen.io/cli/
"""
try:
argv = argv if argv is not None else self.argv
algorithm = self.get_algorithm()
algorithm.run(argv=argv)
except (SystemExit, KeyboardInterrupt):
# Under some (most?) network engines, a SIGINT will be trapped by the
# SIGINT signal handler above. However, gevent does "something" with
# signals and our signal handler never fires. However, we *do* get a
# KeyboardInterrupt here in that case. *shrug*
#
# See: https://github.com/gittip/aspen-python/issues/196
pass
except:
import aspen, traceback
aspen.log_dammit("Oh no! Aspen crashed!")
aspen.log_dammit(traceback.format_exc())
if __name__ == '__main__':
main()
| from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from algorithm import Algorithm
class Server(object):
def __init__(self, argv=None):
self.argv = argv
def get_algorithm(self):
return Algorithm('aspen.algorithms.server')
def get_website(self):
"""Return a website object. Useful in testing.
"""
algorithm = self.get_algorithm()
algorithm.run(argv=self.argv, _through='get_website_from_argv')
return algorithm.state['website']
def main(self, argv=None):
"""http://aspen.io/cli/
"""
try:
argv = argv if argv is not None else self.argv
algorithm = self.get_algorithm()
algorithm.run(argv=argv)
except (SystemExit, KeyboardInterrupt):
# Under some (most?) network engines, a SIGINT will be trapped by the
# SIGINT signal handler above. However, gevent does "something" with
# signals and our signal handler never fires. However, we *do* get a
# KeyboardInterrupt here in that case. *shrug*
#
# See: https://github.com/gittip/aspen-python/issues/196
pass
except:
import aspen, traceback
aspen.log_dammit("Oh no! Aspen crashed!")
aspen.log_dammit(traceback.format_exc())
if __name__ == '__main__':
Server().main()
Fix CLI api (was missing entrypoint hook)from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from algorithm import Algorithm
def main():
Server().main()
class Server(object):
def __init__(self, argv=None):
self.argv = argv
def get_algorithm(self):
return Algorithm('aspen.algorithms.server')
def get_website(self):
"""Return a website object. Useful in testing.
"""
algorithm = self.get_algorithm()
algorithm.run(argv=self.argv, _through='get_website_from_argv')
return algorithm.state['website']
def main(self, argv=None):
"""http://aspen.io/cli/
"""
try:
argv = argv if argv is not None else self.argv
algorithm = self.get_algorithm()
algorithm.run(argv=argv)
except (SystemExit, KeyboardInterrupt):
# Under some (most?) network engines, a SIGINT will be trapped by the
# SIGINT signal handler above. However, gevent does "something" with
# signals and our signal handler never fires. However, we *do* get a
# KeyboardInterrupt here in that case. *shrug*
#
# See: https://github.com/gittip/aspen-python/issues/196
pass
except:
import aspen, traceback
aspen.log_dammit("Oh no! Aspen crashed!")
aspen.log_dammit(traceback.format_exc())
if __name__ == '__main__':
main()
| <commit_before>from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from algorithm import Algorithm
class Server(object):
def __init__(self, argv=None):
self.argv = argv
def get_algorithm(self):
return Algorithm('aspen.algorithms.server')
def get_website(self):
"""Return a website object. Useful in testing.
"""
algorithm = self.get_algorithm()
algorithm.run(argv=self.argv, _through='get_website_from_argv')
return algorithm.state['website']
def main(self, argv=None):
"""http://aspen.io/cli/
"""
try:
argv = argv if argv is not None else self.argv
algorithm = self.get_algorithm()
algorithm.run(argv=argv)
except (SystemExit, KeyboardInterrupt):
# Under some (most?) network engines, a SIGINT will be trapped by the
# SIGINT signal handler above. However, gevent does "something" with
# signals and our signal handler never fires. However, we *do* get a
# KeyboardInterrupt here in that case. *shrug*
#
# See: https://github.com/gittip/aspen-python/issues/196
pass
except:
import aspen, traceback
aspen.log_dammit("Oh no! Aspen crashed!")
aspen.log_dammit(traceback.format_exc())
if __name__ == '__main__':
Server().main()
<commit_msg>Fix CLI api (was missing entrypoint hook)<commit_after>from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from algorithm import Algorithm
def main():
Server().main()
class Server(object):
def __init__(self, argv=None):
self.argv = argv
def get_algorithm(self):
return Algorithm('aspen.algorithms.server')
def get_website(self):
"""Return a website object. Useful in testing.
"""
algorithm = self.get_algorithm()
algorithm.run(argv=self.argv, _through='get_website_from_argv')
return algorithm.state['website']
def main(self, argv=None):
"""http://aspen.io/cli/
"""
try:
argv = argv if argv is not None else self.argv
algorithm = self.get_algorithm()
algorithm.run(argv=argv)
except (SystemExit, KeyboardInterrupt):
# Under some (most?) network engines, a SIGINT will be trapped by the
# SIGINT signal handler above. However, gevent does "something" with
# signals and our signal handler never fires. However, we *do* get a
# KeyboardInterrupt here in that case. *shrug*
#
# See: https://github.com/gittip/aspen-python/issues/196
pass
except:
import aspen, traceback
aspen.log_dammit("Oh no! Aspen crashed!")
aspen.log_dammit(traceback.format_exc())
if __name__ == '__main__':
main()
|
11f36192f1b74cd68d90a9cc0ed592c0c1b0148d | cdr_stats/mongodb_connection_middleware.py | cdr_stats/mongodb_connection_middleware.py | from django.conf import settings
from django.http import HttpResponseRedirect
from pymongo.connection import Connection
from pymongo.errors import ConnectionFailure
class MongodbConnectionMiddleware(object):
def process_request(self, request):
try:
connection = Connection(settings.CDR_MONGO_HOST, settings.CDR_MONGO_PORT)
if connection.is_locked:
if connection.unlock(): # if db gets unlocked
return None
return HttpResponseRedirect('/?db_error=locked')
else:
return None
except ConnectionFailure:
return HttpResponseRedirect('/?db_error=closed')
| from django.conf import settings
from django import http
from django.http import HttpResponseRedirect
from pymongo.connection import Connection
from pymongo.errors import ConnectionFailure
class MongodbConnectionMiddleware(object):
def process_request(self, request):
try:
connection = Connection(settings.CDR_MONGO_HOST, settings.CDR_MONGO_PORT)
if connection.is_locked:
if connection.unlock(): # if db gets unlocked
return None
return HttpResponseRedirect('/?db_error=locked')
else:
#check if collection have any data
db = connection[settings.CDR_MONGO_DB_NAME]
collection = db[settings.CDR_MONGO_CDR_COMMON]
doc = collection.find_one()
if not doc:
return http.HttpResponseForbidden('<h1>Error Import data</h1> Make sure you have existing data in your collections')
else:
return None
except ConnectionFailure:
return HttpResponseRedirect('/?db_error=closed')
| Add middleware check for existing data | Add middleware check for existing data
| Python | mpl-2.0 | Star2Billing/cdr-stats,Star2Billing/cdr-stats,cdr-stats/cdr-stats,areski/cdr-stats,areski/cdr-stats,areski/cdr-stats,cdr-stats/cdr-stats,cdr-stats/cdr-stats,cdr-stats/cdr-stats,areski/cdr-stats,Star2Billing/cdr-stats,Star2Billing/cdr-stats | from django.conf import settings
from django.http import HttpResponseRedirect
from pymongo.connection import Connection
from pymongo.errors import ConnectionFailure
class MongodbConnectionMiddleware(object):
def process_request(self, request):
try:
connection = Connection(settings.CDR_MONGO_HOST, settings.CDR_MONGO_PORT)
if connection.is_locked:
if connection.unlock(): # if db gets unlocked
return None
return HttpResponseRedirect('/?db_error=locked')
else:
return None
except ConnectionFailure:
return HttpResponseRedirect('/?db_error=closed')
Add middleware check for existing data | from django.conf import settings
from django import http
from django.http import HttpResponseRedirect
from pymongo.connection import Connection
from pymongo.errors import ConnectionFailure
class MongodbConnectionMiddleware(object):
def process_request(self, request):
try:
connection = Connection(settings.CDR_MONGO_HOST, settings.CDR_MONGO_PORT)
if connection.is_locked:
if connection.unlock(): # if db gets unlocked
return None
return HttpResponseRedirect('/?db_error=locked')
else:
#check if collection have any data
db = connection[settings.CDR_MONGO_DB_NAME]
collection = db[settings.CDR_MONGO_CDR_COMMON]
doc = collection.find_one()
if not doc:
return http.HttpResponseForbidden('<h1>Error Import data</h1> Make sure you have existing data in your collections')
else:
return None
except ConnectionFailure:
return HttpResponseRedirect('/?db_error=closed')
| <commit_before>from django.conf import settings
from django.http import HttpResponseRedirect
from pymongo.connection import Connection
from pymongo.errors import ConnectionFailure
class MongodbConnectionMiddleware(object):
def process_request(self, request):
try:
connection = Connection(settings.CDR_MONGO_HOST, settings.CDR_MONGO_PORT)
if connection.is_locked:
if connection.unlock(): # if db gets unlocked
return None
return HttpResponseRedirect('/?db_error=locked')
else:
return None
except ConnectionFailure:
return HttpResponseRedirect('/?db_error=closed')
<commit_msg>Add middleware check for existing data<commit_after> | from django.conf import settings
from django import http
from django.http import HttpResponseRedirect
from pymongo.connection import Connection
from pymongo.errors import ConnectionFailure
class MongodbConnectionMiddleware(object):
def process_request(self, request):
try:
connection = Connection(settings.CDR_MONGO_HOST, settings.CDR_MONGO_PORT)
if connection.is_locked:
if connection.unlock(): # if db gets unlocked
return None
return HttpResponseRedirect('/?db_error=locked')
else:
#check if collection have any data
db = connection[settings.CDR_MONGO_DB_NAME]
collection = db[settings.CDR_MONGO_CDR_COMMON]
doc = collection.find_one()
if not doc:
return http.HttpResponseForbidden('<h1>Error Import data</h1> Make sure you have existing data in your collections')
else:
return None
except ConnectionFailure:
return HttpResponseRedirect('/?db_error=closed')
| from django.conf import settings
from django.http import HttpResponseRedirect
from pymongo.connection import Connection
from pymongo.errors import ConnectionFailure
class MongodbConnectionMiddleware(object):
def process_request(self, request):
try:
connection = Connection(settings.CDR_MONGO_HOST, settings.CDR_MONGO_PORT)
if connection.is_locked:
if connection.unlock(): # if db gets unlocked
return None
return HttpResponseRedirect('/?db_error=locked')
else:
return None
except ConnectionFailure:
return HttpResponseRedirect('/?db_error=closed')
Add middleware check for existing datafrom django.conf import settings
from django import http
from django.http import HttpResponseRedirect
from pymongo.connection import Connection
from pymongo.errors import ConnectionFailure
class MongodbConnectionMiddleware(object):
def process_request(self, request):
try:
connection = Connection(settings.CDR_MONGO_HOST, settings.CDR_MONGO_PORT)
if connection.is_locked:
if connection.unlock(): # if db gets unlocked
return None
return HttpResponseRedirect('/?db_error=locked')
else:
#check if collection have any data
db = connection[settings.CDR_MONGO_DB_NAME]
collection = db[settings.CDR_MONGO_CDR_COMMON]
doc = collection.find_one()
if not doc:
return http.HttpResponseForbidden('<h1>Error Import data</h1> Make sure you have existing data in your collections')
else:
return None
except ConnectionFailure:
return HttpResponseRedirect('/?db_error=closed')
| <commit_before>from django.conf import settings
from django.http import HttpResponseRedirect
from pymongo.connection import Connection
from pymongo.errors import ConnectionFailure
class MongodbConnectionMiddleware(object):
def process_request(self, request):
try:
connection = Connection(settings.CDR_MONGO_HOST, settings.CDR_MONGO_PORT)
if connection.is_locked:
if connection.unlock(): # if db gets unlocked
return None
return HttpResponseRedirect('/?db_error=locked')
else:
return None
except ConnectionFailure:
return HttpResponseRedirect('/?db_error=closed')
<commit_msg>Add middleware check for existing data<commit_after>from django.conf import settings
from django import http
from django.http import HttpResponseRedirect
from pymongo.connection import Connection
from pymongo.errors import ConnectionFailure
class MongodbConnectionMiddleware(object):
def process_request(self, request):
try:
connection = Connection(settings.CDR_MONGO_HOST, settings.CDR_MONGO_PORT)
if connection.is_locked:
if connection.unlock(): # if db gets unlocked
return None
return HttpResponseRedirect('/?db_error=locked')
else:
#check if collection have any data
db = connection[settings.CDR_MONGO_DB_NAME]
collection = db[settings.CDR_MONGO_CDR_COMMON]
doc = collection.find_one()
if not doc:
return http.HttpResponseForbidden('<h1>Error Import data</h1> Make sure you have existing data in your collections')
else:
return None
except ConnectionFailure:
return HttpResponseRedirect('/?db_error=closed')
|
6ef3e8778ad05c1dddcf6660f24f762f1725b906 | features/environment.py | features/environment.py | import os
import tempfile
from flask import json
import config
def before_scenario(context, scenario):
context.db_fd, context.db_url = tempfile.mkstemp()
config.SQLALCHEMY_DATABASE_URI = 'sqlite:///' + context.db_url
import tsserver
tsserver.app.config['TESTING'] = True
context.app = tsserver.app.test_client()
def request(url, method='GET'):
"""
Wrapper over Flask.open function that parses returned data as JSON
:param method: HTTP method to be used. GET is used by default
:param url: URL to retrieve
:return: Response object
"""
rv = context.app.open(url, method=method)
rv.json_data = json.loads(rv.data)
return rv
context.request = request
def after_scenario(context, scenario):
os.close(context.db_fd)
os.unlink(context.db_url)
| import os
import tempfile
from flask import json
import tsserver
# If set to True, each time the test is run, new database is created as a
# temporary file. If the value is equal to False, tests will be using SQLite
# in-memory database.
USE_DB_TEMP_FILE = False
def before_scenario(context, scenario):
if USE_DB_TEMP_FILE:
context.db_fd, context.db_url = tempfile.mkstemp()
db_url = 'sqlite:///' + context.db_url
else:
db_url = 'sqlite://'
tsserver.app.config['SQLALCHEMY_DATABASE_URI'] = db_url
# Ensure the tests are actually run in temporary database
assert str(tsserver.db.engine.url) == db_url
tsserver.app.config['TESTING'] = True
tsserver.db.create_all()
context.app = tsserver.app.test_client()
def request(url, method='GET'):
"""
Wrapper over Flask.open function that parses returned data as JSON
:param method: HTTP method to be used. GET is used by default
:param url: URL to retrieve
:return: Response object
"""
rv = context.app.open(url, method=method)
rv.json_data = json.loads(rv.data)
return rv
context.request = request
def after_scenario(context, scenario):
if USE_DB_TEMP_FILE:
os.close(context.db_fd)
os.unlink(context.db_url)
| Use SQLite in-memory database in tests | Use SQLite in-memory database in tests
Also, probably fix temporary databases not working.
| Python | mit | m4tx/techswarm-server | import os
import tempfile
from flask import json
import config
def before_scenario(context, scenario):
context.db_fd, context.db_url = tempfile.mkstemp()
config.SQLALCHEMY_DATABASE_URI = 'sqlite:///' + context.db_url
import tsserver
tsserver.app.config['TESTING'] = True
context.app = tsserver.app.test_client()
def request(url, method='GET'):
"""
Wrapper over Flask.open function that parses returned data as JSON
:param method: HTTP method to be used. GET is used by default
:param url: URL to retrieve
:return: Response object
"""
rv = context.app.open(url, method=method)
rv.json_data = json.loads(rv.data)
return rv
context.request = request
def after_scenario(context, scenario):
os.close(context.db_fd)
os.unlink(context.db_url)
Use SQLite in-memory database in tests
Also, probably fix temporary databases not working. | import os
import tempfile
from flask import json
import tsserver
# If set to True, each time the test is run, new database is created as a
# temporary file. If the value is equal to False, tests will be using SQLite
# in-memory database.
USE_DB_TEMP_FILE = False
def before_scenario(context, scenario):
if USE_DB_TEMP_FILE:
context.db_fd, context.db_url = tempfile.mkstemp()
db_url = 'sqlite:///' + context.db_url
else:
db_url = 'sqlite://'
tsserver.app.config['SQLALCHEMY_DATABASE_URI'] = db_url
# Ensure the tests are actually run in temporary database
assert str(tsserver.db.engine.url) == db_url
tsserver.app.config['TESTING'] = True
tsserver.db.create_all()
context.app = tsserver.app.test_client()
def request(url, method='GET'):
"""
Wrapper over Flask.open function that parses returned data as JSON
:param method: HTTP method to be used. GET is used by default
:param url: URL to retrieve
:return: Response object
"""
rv = context.app.open(url, method=method)
rv.json_data = json.loads(rv.data)
return rv
context.request = request
def after_scenario(context, scenario):
if USE_DB_TEMP_FILE:
os.close(context.db_fd)
os.unlink(context.db_url)
| <commit_before>import os
import tempfile
from flask import json
import config
def before_scenario(context, scenario):
context.db_fd, context.db_url = tempfile.mkstemp()
config.SQLALCHEMY_DATABASE_URI = 'sqlite:///' + context.db_url
import tsserver
tsserver.app.config['TESTING'] = True
context.app = tsserver.app.test_client()
def request(url, method='GET'):
"""
Wrapper over Flask.open function that parses returned data as JSON
:param method: HTTP method to be used. GET is used by default
:param url: URL to retrieve
:return: Response object
"""
rv = context.app.open(url, method=method)
rv.json_data = json.loads(rv.data)
return rv
context.request = request
def after_scenario(context, scenario):
os.close(context.db_fd)
os.unlink(context.db_url)
<commit_msg>Use SQLite in-memory database in tests
Also, probably fix temporary databases not working.<commit_after> | import os
import tempfile
from flask import json
import tsserver
# If set to True, each time the test is run, new database is created as a
# temporary file. If the value is equal to False, tests will be using SQLite
# in-memory database.
USE_DB_TEMP_FILE = False
def before_scenario(context, scenario):
if USE_DB_TEMP_FILE:
context.db_fd, context.db_url = tempfile.mkstemp()
db_url = 'sqlite:///' + context.db_url
else:
db_url = 'sqlite://'
tsserver.app.config['SQLALCHEMY_DATABASE_URI'] = db_url
# Ensure the tests are actually run in temporary database
assert str(tsserver.db.engine.url) == db_url
tsserver.app.config['TESTING'] = True
tsserver.db.create_all()
context.app = tsserver.app.test_client()
def request(url, method='GET'):
"""
Wrapper over Flask.open function that parses returned data as JSON
:param method: HTTP method to be used. GET is used by default
:param url: URL to retrieve
:return: Response object
"""
rv = context.app.open(url, method=method)
rv.json_data = json.loads(rv.data)
return rv
context.request = request
def after_scenario(context, scenario):
if USE_DB_TEMP_FILE:
os.close(context.db_fd)
os.unlink(context.db_url)
| import os
import tempfile
from flask import json
import config
def before_scenario(context, scenario):
context.db_fd, context.db_url = tempfile.mkstemp()
config.SQLALCHEMY_DATABASE_URI = 'sqlite:///' + context.db_url
import tsserver
tsserver.app.config['TESTING'] = True
context.app = tsserver.app.test_client()
def request(url, method='GET'):
"""
Wrapper over Flask.open function that parses returned data as JSON
:param method: HTTP method to be used. GET is used by default
:param url: URL to retrieve
:return: Response object
"""
rv = context.app.open(url, method=method)
rv.json_data = json.loads(rv.data)
return rv
context.request = request
def after_scenario(context, scenario):
os.close(context.db_fd)
os.unlink(context.db_url)
Use SQLite in-memory database in tests
Also, probably fix temporary databases not working.import os
import tempfile
from flask import json
import tsserver
# If set to True, each time the test is run, new database is created as a
# temporary file. If the value is equal to False, tests will be using SQLite
# in-memory database.
USE_DB_TEMP_FILE = False
def before_scenario(context, scenario):
if USE_DB_TEMP_FILE:
context.db_fd, context.db_url = tempfile.mkstemp()
db_url = 'sqlite:///' + context.db_url
else:
db_url = 'sqlite://'
tsserver.app.config['SQLALCHEMY_DATABASE_URI'] = db_url
# Ensure the tests are actually run in temporary database
assert str(tsserver.db.engine.url) == db_url
tsserver.app.config['TESTING'] = True
tsserver.db.create_all()
context.app = tsserver.app.test_client()
def request(url, method='GET'):
"""
Wrapper over Flask.open function that parses returned data as JSON
:param method: HTTP method to be used. GET is used by default
:param url: URL to retrieve
:return: Response object
"""
rv = context.app.open(url, method=method)
rv.json_data = json.loads(rv.data)
return rv
context.request = request
def after_scenario(context, scenario):
if USE_DB_TEMP_FILE:
os.close(context.db_fd)
os.unlink(context.db_url)
| <commit_before>import os
import tempfile
from flask import json
import config
def before_scenario(context, scenario):
context.db_fd, context.db_url = tempfile.mkstemp()
config.SQLALCHEMY_DATABASE_URI = 'sqlite:///' + context.db_url
import tsserver
tsserver.app.config['TESTING'] = True
context.app = tsserver.app.test_client()
def request(url, method='GET'):
"""
Wrapper over Flask.open function that parses returned data as JSON
:param method: HTTP method to be used. GET is used by default
:param url: URL to retrieve
:return: Response object
"""
rv = context.app.open(url, method=method)
rv.json_data = json.loads(rv.data)
return rv
context.request = request
def after_scenario(context, scenario):
os.close(context.db_fd)
os.unlink(context.db_url)
<commit_msg>Use SQLite in-memory database in tests
Also, probably fix temporary databases not working.<commit_after>import os
import tempfile
from flask import json
import tsserver
# If set to True, each time the test is run, new database is created as a
# temporary file. If the value is equal to False, tests will be using SQLite
# in-memory database.
USE_DB_TEMP_FILE = False
def before_scenario(context, scenario):
if USE_DB_TEMP_FILE:
context.db_fd, context.db_url = tempfile.mkstemp()
db_url = 'sqlite:///' + context.db_url
else:
db_url = 'sqlite://'
tsserver.app.config['SQLALCHEMY_DATABASE_URI'] = db_url
# Ensure the tests are actually run in temporary database
assert str(tsserver.db.engine.url) == db_url
tsserver.app.config['TESTING'] = True
tsserver.db.create_all()
context.app = tsserver.app.test_client()
def request(url, method='GET'):
"""
Wrapper over Flask.open function that parses returned data as JSON
:param method: HTTP method to be used. GET is used by default
:param url: URL to retrieve
:return: Response object
"""
rv = context.app.open(url, method=method)
rv.json_data = json.loads(rv.data)
return rv
context.request = request
def after_scenario(context, scenario):
if USE_DB_TEMP_FILE:
os.close(context.db_fd)
os.unlink(context.db_url)
|
dd15767944a3ec37a0ff568323384200d3fb540c | django_olcc/urls.py | django_olcc/urls.py | from django.conf import settings
from django.conf.urls.defaults import patterns, include, url
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.views.generic.simple import direct_to_template
# Enable the django admin
admin.autodiscover()
urlpatterns = patterns('',
# Wire up olcc urls
url(r'', include('olcc.urls')),
# Wire up the admin urls
url(r'^admin/', include(admin.site.urls)),
# humans.txt
(r'^humans\.txt$', direct_to_template,
{'template': 'humans.txt', 'mimetype': 'text/plain'}),
# robots.txt
(r'^robots\.txt$', direct_to_template,
{'template': 'robots.txt', 'mimetype': 'text/plain'}),
# crossdomain.xml
(r'^crossdomain\.xml$', direct_to_template,
{'template': 'crossdomain.xml', 'mimetype': 'application/xml'}),
)
# Static files
urlpatterns += staticfiles_urlpatterns()
| from django.conf import settings
from django.conf.urls.defaults import patterns, include, url
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.views.generic.simple import direct_to_template
# Enable the django admin
admin.autodiscover()
urlpatterns = patterns('',
# Wire up olcc urls
url(r'', include('olcc.urls')),
# Wire up the admin urls
url(r'^admin/', include(admin.site.urls)),
# humans.txt
(r'^humans\.txt$', direct_to_template,
{'template': 'humans.txt', 'mimetype': 'text/plain'}),
# robots.txt
(r'^robots\.txt$', direct_to_template,
{'template': 'robots.txt', 'mimetype': 'text/plain'}),
# crossdomain.xml
(r'^crossdomain\.xml$', direct_to_template,
{'template': 'crossdomain.xml', 'mimetype': 'application/xml'}),
)
# Static files
if settings.DEBUG:
urlpatterns += staticfiles_urlpatterns()
else:
urlpatterns += patterns('',
(r'^static/(?P.*)$', 'django.views.static.serve',
{'document_root': settings.STATIC_ROOT}),
)
| Update URL patterns for staticfiles. | Update URL patterns for staticfiles.
| Python | mit | twaddington/django-olcc,twaddington/django-olcc,twaddington/django-olcc | from django.conf import settings
from django.conf.urls.defaults import patterns, include, url
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.views.generic.simple import direct_to_template
# Enable the django admin
admin.autodiscover()
urlpatterns = patterns('',
# Wire up olcc urls
url(r'', include('olcc.urls')),
# Wire up the admin urls
url(r'^admin/', include(admin.site.urls)),
# humans.txt
(r'^humans\.txt$', direct_to_template,
{'template': 'humans.txt', 'mimetype': 'text/plain'}),
# robots.txt
(r'^robots\.txt$', direct_to_template,
{'template': 'robots.txt', 'mimetype': 'text/plain'}),
# crossdomain.xml
(r'^crossdomain\.xml$', direct_to_template,
{'template': 'crossdomain.xml', 'mimetype': 'application/xml'}),
)
# Static files
urlpatterns += staticfiles_urlpatterns()
Update URL patterns for staticfiles. | from django.conf import settings
from django.conf.urls.defaults import patterns, include, url
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.views.generic.simple import direct_to_template
# Enable the django admin
admin.autodiscover()
urlpatterns = patterns('',
# Wire up olcc urls
url(r'', include('olcc.urls')),
# Wire up the admin urls
url(r'^admin/', include(admin.site.urls)),
# humans.txt
(r'^humans\.txt$', direct_to_template,
{'template': 'humans.txt', 'mimetype': 'text/plain'}),
# robots.txt
(r'^robots\.txt$', direct_to_template,
{'template': 'robots.txt', 'mimetype': 'text/plain'}),
# crossdomain.xml
(r'^crossdomain\.xml$', direct_to_template,
{'template': 'crossdomain.xml', 'mimetype': 'application/xml'}),
)
# Static files
if settings.DEBUG:
urlpatterns += staticfiles_urlpatterns()
else:
urlpatterns += patterns('',
(r'^static/(?P.*)$', 'django.views.static.serve',
{'document_root': settings.STATIC_ROOT}),
)
| <commit_before>from django.conf import settings
from django.conf.urls.defaults import patterns, include, url
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.views.generic.simple import direct_to_template
# Enable the django admin
admin.autodiscover()
urlpatterns = patterns('',
# Wire up olcc urls
url(r'', include('olcc.urls')),
# Wire up the admin urls
url(r'^admin/', include(admin.site.urls)),
# humans.txt
(r'^humans\.txt$', direct_to_template,
{'template': 'humans.txt', 'mimetype': 'text/plain'}),
# robots.txt
(r'^robots\.txt$', direct_to_template,
{'template': 'robots.txt', 'mimetype': 'text/plain'}),
# crossdomain.xml
(r'^crossdomain\.xml$', direct_to_template,
{'template': 'crossdomain.xml', 'mimetype': 'application/xml'}),
)
# Static files
urlpatterns += staticfiles_urlpatterns()
<commit_msg>Update URL patterns for staticfiles.<commit_after> | from django.conf import settings
from django.conf.urls.defaults import patterns, include, url
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.views.generic.simple import direct_to_template
# Enable the django admin
admin.autodiscover()
urlpatterns = patterns('',
# Wire up olcc urls
url(r'', include('olcc.urls')),
# Wire up the admin urls
url(r'^admin/', include(admin.site.urls)),
# humans.txt
(r'^humans\.txt$', direct_to_template,
{'template': 'humans.txt', 'mimetype': 'text/plain'}),
# robots.txt
(r'^robots\.txt$', direct_to_template,
{'template': 'robots.txt', 'mimetype': 'text/plain'}),
# crossdomain.xml
(r'^crossdomain\.xml$', direct_to_template,
{'template': 'crossdomain.xml', 'mimetype': 'application/xml'}),
)
# Static files
if settings.DEBUG:
urlpatterns += staticfiles_urlpatterns()
else:
urlpatterns += patterns('',
(r'^static/(?P.*)$', 'django.views.static.serve',
{'document_root': settings.STATIC_ROOT}),
)
| from django.conf import settings
from django.conf.urls.defaults import patterns, include, url
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.views.generic.simple import direct_to_template
# Enable the django admin
admin.autodiscover()
urlpatterns = patterns('',
# Wire up olcc urls
url(r'', include('olcc.urls')),
# Wire up the admin urls
url(r'^admin/', include(admin.site.urls)),
# humans.txt
(r'^humans\.txt$', direct_to_template,
{'template': 'humans.txt', 'mimetype': 'text/plain'}),
# robots.txt
(r'^robots\.txt$', direct_to_template,
{'template': 'robots.txt', 'mimetype': 'text/plain'}),
# crossdomain.xml
(r'^crossdomain\.xml$', direct_to_template,
{'template': 'crossdomain.xml', 'mimetype': 'application/xml'}),
)
# Static files
urlpatterns += staticfiles_urlpatterns()
Update URL patterns for staticfiles.from django.conf import settings
from django.conf.urls.defaults import patterns, include, url
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.views.generic.simple import direct_to_template
# Enable the django admin
admin.autodiscover()
urlpatterns = patterns('',
# Wire up olcc urls
url(r'', include('olcc.urls')),
# Wire up the admin urls
url(r'^admin/', include(admin.site.urls)),
# humans.txt
(r'^humans\.txt$', direct_to_template,
{'template': 'humans.txt', 'mimetype': 'text/plain'}),
# robots.txt
(r'^robots\.txt$', direct_to_template,
{'template': 'robots.txt', 'mimetype': 'text/plain'}),
# crossdomain.xml
(r'^crossdomain\.xml$', direct_to_template,
{'template': 'crossdomain.xml', 'mimetype': 'application/xml'}),
)
# Static files
if settings.DEBUG:
urlpatterns += staticfiles_urlpatterns()
else:
urlpatterns += patterns('',
(r'^static/(?P.*)$', 'django.views.static.serve',
{'document_root': settings.STATIC_ROOT}),
)
| <commit_before>from django.conf import settings
from django.conf.urls.defaults import patterns, include, url
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.views.generic.simple import direct_to_template
# Enable the django admin
admin.autodiscover()
urlpatterns = patterns('',
# Wire up olcc urls
url(r'', include('olcc.urls')),
# Wire up the admin urls
url(r'^admin/', include(admin.site.urls)),
# humans.txt
(r'^humans\.txt$', direct_to_template,
{'template': 'humans.txt', 'mimetype': 'text/plain'}),
# robots.txt
(r'^robots\.txt$', direct_to_template,
{'template': 'robots.txt', 'mimetype': 'text/plain'}),
# crossdomain.xml
(r'^crossdomain\.xml$', direct_to_template,
{'template': 'crossdomain.xml', 'mimetype': 'application/xml'}),
)
# Static files
urlpatterns += staticfiles_urlpatterns()
<commit_msg>Update URL patterns for staticfiles.<commit_after>from django.conf import settings
from django.conf.urls.defaults import patterns, include, url
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.views.generic.simple import direct_to_template
# Enable the django admin
admin.autodiscover()
urlpatterns = patterns('',
# Wire up olcc urls
url(r'', include('olcc.urls')),
# Wire up the admin urls
url(r'^admin/', include(admin.site.urls)),
# humans.txt
(r'^humans\.txt$', direct_to_template,
{'template': 'humans.txt', 'mimetype': 'text/plain'}),
# robots.txt
(r'^robots\.txt$', direct_to_template,
{'template': 'robots.txt', 'mimetype': 'text/plain'}),
# crossdomain.xml
(r'^crossdomain\.xml$', direct_to_template,
{'template': 'crossdomain.xml', 'mimetype': 'application/xml'}),
)
# Static files
if settings.DEBUG:
urlpatterns += staticfiles_urlpatterns()
else:
urlpatterns += patterns('',
(r'^static/(?P.*)$', 'django.views.static.serve',
{'document_root': settings.STATIC_ROOT}),
)
|
ec0a27694454f0765f63f9c762d42190759fd672 | utils/templatetags/text_tags.py | utils/templatetags/text_tags.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
# Erik Stein <code@classlibrary.net>, 2015
import re
from django import template
from django.template.defaultfilters import stringfilter
from django.utils.html import conditional_escape
from django.utils.safestring import mark_safe
from .. import text as text_utils
register = template.Library()
@register.filter()
def conditional_punctuation(value, punctuation=",", space=" "):
"""
Appends punctuation if the (stripped) value is not empty
and the value does not already end in a punctuation mark (.,:;!?).
"""
value = value.strip()
if value:
if value[-1] not in ".,:;!?":
value += conditional_escape(punctuation)
value += conditional_escape(space) # Append previously stripped space
return value
conditional_punctuation.is_safe = True
WHITESPACE = re.compile('\s+')
@register.filter(needs_autoescape=True)
@stringfilter
def nbsp(text, autoescape=True):
if autoescape:
esc = conditional_escape
else:
esc = lambda x: x
return mark_safe(WHITESPACE.sub(' ', esc(text.strip())))
@register.filter(needs_autoescape=False)
@stringfilter
def html_entities_to_unicode(text):
return mark_safe(text_utils.html_entities_to_unicode(text))
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
# Erik Stein <code@classlibrary.net>, 2015
import re
from django import template
from django.template.defaultfilters import stringfilter
from django.utils.encoding import force_text
from django.utils.html import conditional_escape
from django.utils.safestring import mark_safe
from .. import text as text_utils
register = template.Library()
@register.filter()
def conditional_punctuation(value, punctuation=",", space=" "):
"""
Appends punctuation if the (stripped) value is not empty
and the value does not already end in a punctuation mark (.,:;!?).
"""
value = force_text(value or "").strip()
if value:
if value[-1] not in ".,:;!?":
value += conditional_escape(punctuation)
value += conditional_escape(space) # Append previously stripped space
return value
conditional_punctuation.is_safe = True
WHITESPACE = re.compile('\s+')
@register.filter(needs_autoescape=True)
@stringfilter
def nbsp(text, autoescape=True):
if autoescape:
esc = conditional_escape
else:
esc = lambda x: x
return mark_safe(WHITESPACE.sub(' ', esc(text.strip())))
@register.filter(needs_autoescape=False)
@stringfilter
def html_entities_to_unicode(text):
return mark_safe(text_utils.html_entities_to_unicode(text))
| Make sure conditional_punctuation can handle all value type (using force_text). | Make sure conditional_punctuation can handle all value type (using force_text).
| Python | mit | sha-red/django-shared-utils,sha-red/django-shared-utils | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
# Erik Stein <code@classlibrary.net>, 2015
import re
from django import template
from django.template.defaultfilters import stringfilter
from django.utils.html import conditional_escape
from django.utils.safestring import mark_safe
from .. import text as text_utils
register = template.Library()
@register.filter()
def conditional_punctuation(value, punctuation=",", space=" "):
"""
Appends punctuation if the (stripped) value is not empty
and the value does not already end in a punctuation mark (.,:;!?).
"""
value = value.strip()
if value:
if value[-1] not in ".,:;!?":
value += conditional_escape(punctuation)
value += conditional_escape(space) # Append previously stripped space
return value
conditional_punctuation.is_safe = True
WHITESPACE = re.compile('\s+')
@register.filter(needs_autoescape=True)
@stringfilter
def nbsp(text, autoescape=True):
if autoescape:
esc = conditional_escape
else:
esc = lambda x: x
return mark_safe(WHITESPACE.sub(' ', esc(text.strip())))
@register.filter(needs_autoescape=False)
@stringfilter
def html_entities_to_unicode(text):
return mark_safe(text_utils.html_entities_to_unicode(text))
Make sure conditional_punctuation can handle all value type (using force_text). | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
# Erik Stein <code@classlibrary.net>, 2015
import re
from django import template
from django.template.defaultfilters import stringfilter
from django.utils.encoding import force_text
from django.utils.html import conditional_escape
from django.utils.safestring import mark_safe
from .. import text as text_utils
register = template.Library()
@register.filter()
def conditional_punctuation(value, punctuation=",", space=" "):
"""
Appends punctuation if the (stripped) value is not empty
and the value does not already end in a punctuation mark (.,:;!?).
"""
value = force_text(value or "").strip()
if value:
if value[-1] not in ".,:;!?":
value += conditional_escape(punctuation)
value += conditional_escape(space) # Append previously stripped space
return value
conditional_punctuation.is_safe = True
WHITESPACE = re.compile('\s+')
@register.filter(needs_autoescape=True)
@stringfilter
def nbsp(text, autoescape=True):
if autoescape:
esc = conditional_escape
else:
esc = lambda x: x
return mark_safe(WHITESPACE.sub(' ', esc(text.strip())))
@register.filter(needs_autoescape=False)
@stringfilter
def html_entities_to_unicode(text):
return mark_safe(text_utils.html_entities_to_unicode(text))
| <commit_before># -*- coding: utf-8 -*-
from __future__ import unicode_literals
# Erik Stein <code@classlibrary.net>, 2015
import re
from django import template
from django.template.defaultfilters import stringfilter
from django.utils.html import conditional_escape
from django.utils.safestring import mark_safe
from .. import text as text_utils
register = template.Library()
@register.filter()
def conditional_punctuation(value, punctuation=",", space=" "):
"""
Appends punctuation if the (stripped) value is not empty
and the value does not already end in a punctuation mark (.,:;!?).
"""
value = value.strip()
if value:
if value[-1] not in ".,:;!?":
value += conditional_escape(punctuation)
value += conditional_escape(space) # Append previously stripped space
return value
conditional_punctuation.is_safe = True
WHITESPACE = re.compile('\s+')
@register.filter(needs_autoescape=True)
@stringfilter
def nbsp(text, autoescape=True):
if autoescape:
esc = conditional_escape
else:
esc = lambda x: x
return mark_safe(WHITESPACE.sub(' ', esc(text.strip())))
@register.filter(needs_autoescape=False)
@stringfilter
def html_entities_to_unicode(text):
return mark_safe(text_utils.html_entities_to_unicode(text))
<commit_msg>Make sure conditional_punctuation can handle all value type (using force_text).<commit_after> | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
# Erik Stein <code@classlibrary.net>, 2015
import re
from django import template
from django.template.defaultfilters import stringfilter
from django.utils.encoding import force_text
from django.utils.html import conditional_escape
from django.utils.safestring import mark_safe
from .. import text as text_utils
register = template.Library()
@register.filter()
def conditional_punctuation(value, punctuation=",", space=" "):
"""
Appends punctuation if the (stripped) value is not empty
and the value does not already end in a punctuation mark (.,:;!?).
"""
value = force_text(value or "").strip()
if value:
if value[-1] not in ".,:;!?":
value += conditional_escape(punctuation)
value += conditional_escape(space) # Append previously stripped space
return value
conditional_punctuation.is_safe = True
WHITESPACE = re.compile('\s+')
@register.filter(needs_autoescape=True)
@stringfilter
def nbsp(text, autoescape=True):
if autoescape:
esc = conditional_escape
else:
esc = lambda x: x
return mark_safe(WHITESPACE.sub(' ', esc(text.strip())))
@register.filter(needs_autoescape=False)
@stringfilter
def html_entities_to_unicode(text):
return mark_safe(text_utils.html_entities_to_unicode(text))
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals
# Erik Stein <code@classlibrary.net>, 2015
import re
from django import template
from django.template.defaultfilters import stringfilter
from django.utils.html import conditional_escape
from django.utils.safestring import mark_safe
from .. import text as text_utils
register = template.Library()
@register.filter()
def conditional_punctuation(value, punctuation=",", space=" "):
"""
Appends punctuation if the (stripped) value is not empty
and the value does not already end in a punctuation mark (.,:;!?).
"""
value = value.strip()
if value:
if value[-1] not in ".,:;!?":
value += conditional_escape(punctuation)
value += conditional_escape(space) # Append previously stripped space
return value
conditional_punctuation.is_safe = True
WHITESPACE = re.compile('\s+')
@register.filter(needs_autoescape=True)
@stringfilter
def nbsp(text, autoescape=True):
if autoescape:
esc = conditional_escape
else:
esc = lambda x: x
return mark_safe(WHITESPACE.sub(' ', esc(text.strip())))
@register.filter(needs_autoescape=False)
@stringfilter
def html_entities_to_unicode(text):
return mark_safe(text_utils.html_entities_to_unicode(text))
Make sure conditional_punctuation can handle all value type (using force_text).# -*- coding: utf-8 -*-
from __future__ import unicode_literals
# Erik Stein <code@classlibrary.net>, 2015
import re
from django import template
from django.template.defaultfilters import stringfilter
from django.utils.encoding import force_text
from django.utils.html import conditional_escape
from django.utils.safestring import mark_safe
from .. import text as text_utils
register = template.Library()
@register.filter()
def conditional_punctuation(value, punctuation=",", space=" "):
"""
Appends punctuation if the (stripped) value is not empty
and the value does not already end in a punctuation mark (.,:;!?).
"""
value = force_text(value or "").strip()
if value:
if value[-1] not in ".,:;!?":
value += conditional_escape(punctuation)
value += conditional_escape(space) # Append previously stripped space
return value
conditional_punctuation.is_safe = True
WHITESPACE = re.compile('\s+')
@register.filter(needs_autoescape=True)
@stringfilter
def nbsp(text, autoescape=True):
if autoescape:
esc = conditional_escape
else:
esc = lambda x: x
return mark_safe(WHITESPACE.sub(' ', esc(text.strip())))
@register.filter(needs_autoescape=False)
@stringfilter
def html_entities_to_unicode(text):
return mark_safe(text_utils.html_entities_to_unicode(text))
| <commit_before># -*- coding: utf-8 -*-
from __future__ import unicode_literals
# Erik Stein <code@classlibrary.net>, 2015
import re
from django import template
from django.template.defaultfilters import stringfilter
from django.utils.html import conditional_escape
from django.utils.safestring import mark_safe
from .. import text as text_utils
register = template.Library()
@register.filter()
def conditional_punctuation(value, punctuation=",", space=" "):
"""
Appends punctuation if the (stripped) value is not empty
and the value does not already end in a punctuation mark (.,:;!?).
"""
value = value.strip()
if value:
if value[-1] not in ".,:;!?":
value += conditional_escape(punctuation)
value += conditional_escape(space) # Append previously stripped space
return value
conditional_punctuation.is_safe = True
WHITESPACE = re.compile('\s+')
@register.filter(needs_autoescape=True)
@stringfilter
def nbsp(text, autoescape=True):
if autoescape:
esc = conditional_escape
else:
esc = lambda x: x
return mark_safe(WHITESPACE.sub(' ', esc(text.strip())))
@register.filter(needs_autoescape=False)
@stringfilter
def html_entities_to_unicode(text):
return mark_safe(text_utils.html_entities_to_unicode(text))
<commit_msg>Make sure conditional_punctuation can handle all value type (using force_text).<commit_after># -*- coding: utf-8 -*-
from __future__ import unicode_literals
# Erik Stein <code@classlibrary.net>, 2015
import re
from django import template
from django.template.defaultfilters import stringfilter
from django.utils.encoding import force_text
from django.utils.html import conditional_escape
from django.utils.safestring import mark_safe
from .. import text as text_utils
register = template.Library()
@register.filter()
def conditional_punctuation(value, punctuation=",", space=" "):
"""
Appends punctuation if the (stripped) value is not empty
and the value does not already end in a punctuation mark (.,:;!?).
"""
value = force_text(value or "").strip()
if value:
if value[-1] not in ".,:;!?":
value += conditional_escape(punctuation)
value += conditional_escape(space) # Append previously stripped space
return value
conditional_punctuation.is_safe = True
WHITESPACE = re.compile('\s+')
@register.filter(needs_autoescape=True)
@stringfilter
def nbsp(text, autoescape=True):
if autoescape:
esc = conditional_escape
else:
esc = lambda x: x
return mark_safe(WHITESPACE.sub(' ', esc(text.strip())))
@register.filter(needs_autoescape=False)
@stringfilter
def html_entities_to_unicode(text):
return mark_safe(text_utils.html_entities_to_unicode(text))
|
f410b51f850d2fb75de16d9de4e95be5eb7a4e07 | python/peacock/utils/TextSubWindow.py | python/peacock/utils/TextSubWindow.py | from PyQt5 import QtCore, QtWidgets
class TextSubWindow(QtWidgets.QTextEdit):
"""
TextEdit that saves it size when it closes and closes itself if the main widget disappears.
"""
def __init__(self):
super(TextSubWindow, self).__init__()
self.setWindowFlags(QtCore.Qt.SubWindow)
self._size = None
def sizeHint(self, *args):
"""
Return the saved size.
"""
if self._size:
return self._size
else:
return super(TextSubWindow, self).size()
def closeEvent(self, *args):
"""
Store the size of the window.
"""
self._size = self.size()
super(TextSubWindow, self).closeEvent(*args)
| from PyQt5 import QtWidgets
class TextSubWindow(QtWidgets.QTextEdit):
"""
TextEdit that saves it size when it closes and closes itself if the main widget disappears.
"""
def __init__(self):
super(TextSubWindow, self).__init__()
self._size = None
def sizeHint(self, *args):
"""
Return the saved size.
"""
if self._size:
return self._size
else:
return super(TextSubWindow, self).size()
def closeEvent(self, *args):
"""
Store the size of the window.
"""
self._size = self.size()
super(TextSubWindow, self).closeEvent(*args)
| Fix problem with copying from text window. | Fix problem with copying from text window.
closes #9843
| Python | lgpl-2.1 | harterj/moose,jessecarterMOOSE/moose,yipenggao/moose,yipenggao/moose,milljm/moose,harterj/moose,laagesen/moose,Chuban/moose,andrsd/moose,permcody/moose,dschwen/moose,milljm/moose,laagesen/moose,permcody/moose,laagesen/moose,nuclear-wizard/moose,jessecarterMOOSE/moose,bwspenc/moose,dschwen/moose,sapitts/moose,yipenggao/moose,bwspenc/moose,friedmud/moose,YaqiWang/moose,YaqiWang/moose,milljm/moose,nuclear-wizard/moose,Chuban/moose,jessecarterMOOSE/moose,laagesen/moose,andrsd/moose,harterj/moose,lindsayad/moose,bwspenc/moose,friedmud/moose,lindsayad/moose,friedmud/moose,permcody/moose,dschwen/moose,bwspenc/moose,nuclear-wizard/moose,jessecarterMOOSE/moose,lindsayad/moose,SudiptaBiswas/moose,idaholab/moose,harterj/moose,yipenggao/moose,lindsayad/moose,jessecarterMOOSE/moose,dschwen/moose,bwspenc/moose,idaholab/moose,milljm/moose,Chuban/moose,sapitts/moose,idaholab/moose,laagesen/moose,milljm/moose,YaqiWang/moose,andrsd/moose,YaqiWang/moose,dschwen/moose,lindsayad/moose,sapitts/moose,Chuban/moose,SudiptaBiswas/moose,harterj/moose,idaholab/moose,andrsd/moose,nuclear-wizard/moose,sapitts/moose,andrsd/moose,SudiptaBiswas/moose,friedmud/moose,SudiptaBiswas/moose,SudiptaBiswas/moose,idaholab/moose,sapitts/moose,permcody/moose | from PyQt5 import QtCore, QtWidgets
class TextSubWindow(QtWidgets.QTextEdit):
"""
TextEdit that saves it size when it closes and closes itself if the main widget disappears.
"""
def __init__(self):
super(TextSubWindow, self).__init__()
self.setWindowFlags(QtCore.Qt.SubWindow)
self._size = None
def sizeHint(self, *args):
"""
Return the saved size.
"""
if self._size:
return self._size
else:
return super(TextSubWindow, self).size()
def closeEvent(self, *args):
"""
Store the size of the window.
"""
self._size = self.size()
super(TextSubWindow, self).closeEvent(*args)
Fix problem with copying from text window.
closes #9843 | from PyQt5 import QtWidgets
class TextSubWindow(QtWidgets.QTextEdit):
"""
TextEdit that saves it size when it closes and closes itself if the main widget disappears.
"""
def __init__(self):
super(TextSubWindow, self).__init__()
self._size = None
def sizeHint(self, *args):
"""
Return the saved size.
"""
if self._size:
return self._size
else:
return super(TextSubWindow, self).size()
def closeEvent(self, *args):
"""
Store the size of the window.
"""
self._size = self.size()
super(TextSubWindow, self).closeEvent(*args)
| <commit_before>from PyQt5 import QtCore, QtWidgets
class TextSubWindow(QtWidgets.QTextEdit):
"""
TextEdit that saves it size when it closes and closes itself if the main widget disappears.
"""
def __init__(self):
super(TextSubWindow, self).__init__()
self.setWindowFlags(QtCore.Qt.SubWindow)
self._size = None
def sizeHint(self, *args):
"""
Return the saved size.
"""
if self._size:
return self._size
else:
return super(TextSubWindow, self).size()
def closeEvent(self, *args):
"""
Store the size of the window.
"""
self._size = self.size()
super(TextSubWindow, self).closeEvent(*args)
<commit_msg>Fix problem with copying from text window.
closes #9843<commit_after> | from PyQt5 import QtWidgets
class TextSubWindow(QtWidgets.QTextEdit):
"""
TextEdit that saves it size when it closes and closes itself if the main widget disappears.
"""
def __init__(self):
super(TextSubWindow, self).__init__()
self._size = None
def sizeHint(self, *args):
"""
Return the saved size.
"""
if self._size:
return self._size
else:
return super(TextSubWindow, self).size()
def closeEvent(self, *args):
"""
Store the size of the window.
"""
self._size = self.size()
super(TextSubWindow, self).closeEvent(*args)
| from PyQt5 import QtCore, QtWidgets
class TextSubWindow(QtWidgets.QTextEdit):
"""
TextEdit that saves it size when it closes and closes itself if the main widget disappears.
"""
def __init__(self):
super(TextSubWindow, self).__init__()
self.setWindowFlags(QtCore.Qt.SubWindow)
self._size = None
def sizeHint(self, *args):
"""
Return the saved size.
"""
if self._size:
return self._size
else:
return super(TextSubWindow, self).size()
def closeEvent(self, *args):
"""
Store the size of the window.
"""
self._size = self.size()
super(TextSubWindow, self).closeEvent(*args)
Fix problem with copying from text window.
closes #9843from PyQt5 import QtWidgets
class TextSubWindow(QtWidgets.QTextEdit):
"""
TextEdit that saves it size when it closes and closes itself if the main widget disappears.
"""
def __init__(self):
super(TextSubWindow, self).__init__()
self._size = None
def sizeHint(self, *args):
"""
Return the saved size.
"""
if self._size:
return self._size
else:
return super(TextSubWindow, self).size()
def closeEvent(self, *args):
"""
Store the size of the window.
"""
self._size = self.size()
super(TextSubWindow, self).closeEvent(*args)
| <commit_before>from PyQt5 import QtCore, QtWidgets
class TextSubWindow(QtWidgets.QTextEdit):
"""
TextEdit that saves it size when it closes and closes itself if the main widget disappears.
"""
def __init__(self):
super(TextSubWindow, self).__init__()
self.setWindowFlags(QtCore.Qt.SubWindow)
self._size = None
def sizeHint(self, *args):
"""
Return the saved size.
"""
if self._size:
return self._size
else:
return super(TextSubWindow, self).size()
def closeEvent(self, *args):
"""
Store the size of the window.
"""
self._size = self.size()
super(TextSubWindow, self).closeEvent(*args)
<commit_msg>Fix problem with copying from text window.
closes #9843<commit_after>from PyQt5 import QtWidgets
class TextSubWindow(QtWidgets.QTextEdit):
"""
TextEdit that saves it size when it closes and closes itself if the main widget disappears.
"""
def __init__(self):
super(TextSubWindow, self).__init__()
self._size = None
def sizeHint(self, *args):
"""
Return the saved size.
"""
if self._size:
return self._size
else:
return super(TextSubWindow, self).size()
def closeEvent(self, *args):
"""
Store the size of the window.
"""
self._size = self.size()
super(TextSubWindow, self).closeEvent(*args)
|
965b459717302b674a8b06a243f2d002ce182aaa | prajna/readers.py | prajna/readers.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function
import logging
import os
from pelican.readers import BaseReader
logger = logging.getLogger(__name__)
class SlokaReader(BaseReader):
enabled = True
file_extensions = ['json']
extensions = None
def __init__(self, *args, **kwargs):
logger.debug("SlokaReader: Initialize")
super(SlokaReader, self).__init__(*args, **kwargs)
def read(self, source_path):
logger.debug("SlokaReader: Read: ", self, source_path)
source_file_ext = os.path.splitext(source_path)[-1][1:]
if (source_file_ext not in self.file_extensions):
logger.debug("SlokaReader: Read: Skip ", self, source_path)
return None, None
content = 'some content'
metadata = {'text': 'something'}
return content, metadata
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function
import logging
import os
from pelican.readers import BaseReader
logger = logging.getLogger(__name__)
class SlokaReader(BaseReader):
enabled = True
file_extensions = ['json']
extensions = None
def __init__(self, *args, **kwargs):
logger.debug("SlokaReader: Initialize")
super(SlokaReader, self).__init__(*args, **kwargs)
def read(self, source_path):
logger.debug("SlokaReader: Read: %s", source_path)
source_file_ext = os.path.splitext(source_path)[-1][1:]
if (source_file_ext not in self.file_extensions):
logger.debug("SlokaReader: Read: Skip %s", source_path)
return None, None
content = 'some content'
metadata = {'text': 'something'}
return content, metadata
| Add format string to debug message. | Add format string to debug message.
| Python | mit | mananam/pelican-prajna,mananam/pelican-prajna | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function
import logging
import os
from pelican.readers import BaseReader
logger = logging.getLogger(__name__)
class SlokaReader(BaseReader):
enabled = True
file_extensions = ['json']
extensions = None
def __init__(self, *args, **kwargs):
logger.debug("SlokaReader: Initialize")
super(SlokaReader, self).__init__(*args, **kwargs)
def read(self, source_path):
logger.debug("SlokaReader: Read: ", self, source_path)
source_file_ext = os.path.splitext(source_path)[-1][1:]
if (source_file_ext not in self.file_extensions):
logger.debug("SlokaReader: Read: Skip ", self, source_path)
return None, None
content = 'some content'
metadata = {'text': 'something'}
return content, metadata
Add format string to debug message. | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function
import logging
import os
from pelican.readers import BaseReader
logger = logging.getLogger(__name__)
class SlokaReader(BaseReader):
enabled = True
file_extensions = ['json']
extensions = None
def __init__(self, *args, **kwargs):
logger.debug("SlokaReader: Initialize")
super(SlokaReader, self).__init__(*args, **kwargs)
def read(self, source_path):
logger.debug("SlokaReader: Read: %s", source_path)
source_file_ext = os.path.splitext(source_path)[-1][1:]
if (source_file_ext not in self.file_extensions):
logger.debug("SlokaReader: Read: Skip %s", source_path)
return None, None
content = 'some content'
metadata = {'text': 'something'}
return content, metadata
| <commit_before># -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function
import logging
import os
from pelican.readers import BaseReader
logger = logging.getLogger(__name__)
class SlokaReader(BaseReader):
enabled = True
file_extensions = ['json']
extensions = None
def __init__(self, *args, **kwargs):
logger.debug("SlokaReader: Initialize")
super(SlokaReader, self).__init__(*args, **kwargs)
def read(self, source_path):
logger.debug("SlokaReader: Read: ", self, source_path)
source_file_ext = os.path.splitext(source_path)[-1][1:]
if (source_file_ext not in self.file_extensions):
logger.debug("SlokaReader: Read: Skip ", self, source_path)
return None, None
content = 'some content'
metadata = {'text': 'something'}
return content, metadata
<commit_msg>Add format string to debug message.<commit_after> | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function
import logging
import os
from pelican.readers import BaseReader
logger = logging.getLogger(__name__)
class SlokaReader(BaseReader):
enabled = True
file_extensions = ['json']
extensions = None
def __init__(self, *args, **kwargs):
logger.debug("SlokaReader: Initialize")
super(SlokaReader, self).__init__(*args, **kwargs)
def read(self, source_path):
logger.debug("SlokaReader: Read: %s", source_path)
source_file_ext = os.path.splitext(source_path)[-1][1:]
if (source_file_ext not in self.file_extensions):
logger.debug("SlokaReader: Read: Skip %s", source_path)
return None, None
content = 'some content'
metadata = {'text': 'something'}
return content, metadata
| # -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function
import logging
import os
from pelican.readers import BaseReader
logger = logging.getLogger(__name__)
class SlokaReader(BaseReader):
enabled = True
file_extensions = ['json']
extensions = None
def __init__(self, *args, **kwargs):
logger.debug("SlokaReader: Initialize")
super(SlokaReader, self).__init__(*args, **kwargs)
def read(self, source_path):
logger.debug("SlokaReader: Read: ", self, source_path)
source_file_ext = os.path.splitext(source_path)[-1][1:]
if (source_file_ext not in self.file_extensions):
logger.debug("SlokaReader: Read: Skip ", self, source_path)
return None, None
content = 'some content'
metadata = {'text': 'something'}
return content, metadata
Add format string to debug message.# -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function
import logging
import os
from pelican.readers import BaseReader
logger = logging.getLogger(__name__)
class SlokaReader(BaseReader):
enabled = True
file_extensions = ['json']
extensions = None
def __init__(self, *args, **kwargs):
logger.debug("SlokaReader: Initialize")
super(SlokaReader, self).__init__(*args, **kwargs)
def read(self, source_path):
logger.debug("SlokaReader: Read: %s", source_path)
source_file_ext = os.path.splitext(source_path)[-1][1:]
if (source_file_ext not in self.file_extensions):
logger.debug("SlokaReader: Read: Skip %s", source_path)
return None, None
content = 'some content'
metadata = {'text': 'something'}
return content, metadata
| <commit_before># -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function
import logging
import os
from pelican.readers import BaseReader
logger = logging.getLogger(__name__)
class SlokaReader(BaseReader):
enabled = True
file_extensions = ['json']
extensions = None
def __init__(self, *args, **kwargs):
logger.debug("SlokaReader: Initialize")
super(SlokaReader, self).__init__(*args, **kwargs)
def read(self, source_path):
logger.debug("SlokaReader: Read: ", self, source_path)
source_file_ext = os.path.splitext(source_path)[-1][1:]
if (source_file_ext not in self.file_extensions):
logger.debug("SlokaReader: Read: Skip ", self, source_path)
return None, None
content = 'some content'
metadata = {'text': 'something'}
return content, metadata
<commit_msg>Add format string to debug message.<commit_after># -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function
import logging
import os
from pelican.readers import BaseReader
logger = logging.getLogger(__name__)
class SlokaReader(BaseReader):
enabled = True
file_extensions = ['json']
extensions = None
def __init__(self, *args, **kwargs):
logger.debug("SlokaReader: Initialize")
super(SlokaReader, self).__init__(*args, **kwargs)
def read(self, source_path):
logger.debug("SlokaReader: Read: %s", source_path)
source_file_ext = os.path.splitext(source_path)[-1][1:]
if (source_file_ext not in self.file_extensions):
logger.debug("SlokaReader: Read: Skip %s", source_path)
return None, None
content = 'some content'
metadata = {'text': 'something'}
return content, metadata
|
4dfe50691b911d05be9a82946df77e234283ffe2 | codejail/util.py | codejail/util.py | """Helpers for codejail."""
import contextlib
import os
import shutil
import tempfile
class TempDirectory(object):
def __init__(self):
self.temp_dir = tempfile.mkdtemp(prefix="codejail-")
# Make directory readable by other users ('sandbox' user needs to be
# able to read it).
os.chmod(self.temp_dir, 0775)
def clean_up(self):
# if this errors, something is genuinely wrong, so don't ignore errors.
shutil.rmtree(self.temp_dir)
@contextlib.contextmanager
def temp_directory():
"""
A context manager to make and use a temp directory.
The directory will be removed when done.
"""
tmp = TempDirectory()
try:
yield tmp.temp_dir
finally:
tmp.clean_up()
class ChangeDirectory(object):
def __init__(self, new_dir):
self.old_dir = os.getcwd()
os.chdir(new_dir)
def clean_up(self):
os.chdir(self.old_dir)
@contextlib.contextmanager
def change_directory(new_dir):
"""
A context manager to change the directory, and then change it back.
"""
cd = ChangeDirectory(new_dir)
try:
yield new_dir
finally:
cd.clean_up()
| """Helpers for codejail."""
import contextlib
import os
import shutil
import tempfile
@contextlib.contextmanager
def temp_directory():
"""
A context manager to make and use a temp directory.
The directory will be removed when done.
"""
temp_dir = tempfile.mkdtemp(prefix="codejail-")
# Make directory readable by other users ('sandbox' user needs to be
# able to read it).
os.chmod(temp_dir, 0775)
try:
yield temp_dir
finally:
# if this errors, something is genuinely wrong, so don't ignore errors.
shutil.rmtree(temp_dir)
@contextlib.contextmanager
def change_directory(new_dir):
"""
A context manager to change the directory, and then change it back.
"""
old_dir = os.getcwd()
os.chdir(new_dir)
try:
yield new_dir
finally:
os.chdir(old_dir)
| Simplify these decorators, since we don't use the classes here anyway. | Simplify these decorators, since we don't use the classes here anyway.
| Python | apache-2.0 | edx/codejail,StepicOrg/codejail | """Helpers for codejail."""
import contextlib
import os
import shutil
import tempfile
class TempDirectory(object):
def __init__(self):
self.temp_dir = tempfile.mkdtemp(prefix="codejail-")
# Make directory readable by other users ('sandbox' user needs to be
# able to read it).
os.chmod(self.temp_dir, 0775)
def clean_up(self):
# if this errors, something is genuinely wrong, so don't ignore errors.
shutil.rmtree(self.temp_dir)
@contextlib.contextmanager
def temp_directory():
"""
A context manager to make and use a temp directory.
The directory will be removed when done.
"""
tmp = TempDirectory()
try:
yield tmp.temp_dir
finally:
tmp.clean_up()
class ChangeDirectory(object):
def __init__(self, new_dir):
self.old_dir = os.getcwd()
os.chdir(new_dir)
def clean_up(self):
os.chdir(self.old_dir)
@contextlib.contextmanager
def change_directory(new_dir):
"""
A context manager to change the directory, and then change it back.
"""
cd = ChangeDirectory(new_dir)
try:
yield new_dir
finally:
cd.clean_up()
Simplify these decorators, since we don't use the classes here anyway. | """Helpers for codejail."""
import contextlib
import os
import shutil
import tempfile
@contextlib.contextmanager
def temp_directory():
"""
A context manager to make and use a temp directory.
The directory will be removed when done.
"""
temp_dir = tempfile.mkdtemp(prefix="codejail-")
# Make directory readable by other users ('sandbox' user needs to be
# able to read it).
os.chmod(temp_dir, 0775)
try:
yield temp_dir
finally:
# if this errors, something is genuinely wrong, so don't ignore errors.
shutil.rmtree(temp_dir)
@contextlib.contextmanager
def change_directory(new_dir):
"""
A context manager to change the directory, and then change it back.
"""
old_dir = os.getcwd()
os.chdir(new_dir)
try:
yield new_dir
finally:
os.chdir(old_dir)
| <commit_before>"""Helpers for codejail."""
import contextlib
import os
import shutil
import tempfile
class TempDirectory(object):
def __init__(self):
self.temp_dir = tempfile.mkdtemp(prefix="codejail-")
# Make directory readable by other users ('sandbox' user needs to be
# able to read it).
os.chmod(self.temp_dir, 0775)
def clean_up(self):
# if this errors, something is genuinely wrong, so don't ignore errors.
shutil.rmtree(self.temp_dir)
@contextlib.contextmanager
def temp_directory():
"""
A context manager to make and use a temp directory.
The directory will be removed when done.
"""
tmp = TempDirectory()
try:
yield tmp.temp_dir
finally:
tmp.clean_up()
class ChangeDirectory(object):
def __init__(self, new_dir):
self.old_dir = os.getcwd()
os.chdir(new_dir)
def clean_up(self):
os.chdir(self.old_dir)
@contextlib.contextmanager
def change_directory(new_dir):
"""
A context manager to change the directory, and then change it back.
"""
cd = ChangeDirectory(new_dir)
try:
yield new_dir
finally:
cd.clean_up()
<commit_msg>Simplify these decorators, since we don't use the classes here anyway.<commit_after> | """Helpers for codejail."""
import contextlib
import os
import shutil
import tempfile
@contextlib.contextmanager
def temp_directory():
"""
A context manager to make and use a temp directory.
The directory will be removed when done.
"""
temp_dir = tempfile.mkdtemp(prefix="codejail-")
# Make directory readable by other users ('sandbox' user needs to be
# able to read it).
os.chmod(temp_dir, 0775)
try:
yield temp_dir
finally:
# if this errors, something is genuinely wrong, so don't ignore errors.
shutil.rmtree(temp_dir)
@contextlib.contextmanager
def change_directory(new_dir):
"""
A context manager to change the directory, and then change it back.
"""
old_dir = os.getcwd()
os.chdir(new_dir)
try:
yield new_dir
finally:
os.chdir(old_dir)
| """Helpers for codejail."""
import contextlib
import os
import shutil
import tempfile
class TempDirectory(object):
def __init__(self):
self.temp_dir = tempfile.mkdtemp(prefix="codejail-")
# Make directory readable by other users ('sandbox' user needs to be
# able to read it).
os.chmod(self.temp_dir, 0775)
def clean_up(self):
# if this errors, something is genuinely wrong, so don't ignore errors.
shutil.rmtree(self.temp_dir)
@contextlib.contextmanager
def temp_directory():
"""
A context manager to make and use a temp directory.
The directory will be removed when done.
"""
tmp = TempDirectory()
try:
yield tmp.temp_dir
finally:
tmp.clean_up()
class ChangeDirectory(object):
def __init__(self, new_dir):
self.old_dir = os.getcwd()
os.chdir(new_dir)
def clean_up(self):
os.chdir(self.old_dir)
@contextlib.contextmanager
def change_directory(new_dir):
"""
A context manager to change the directory, and then change it back.
"""
cd = ChangeDirectory(new_dir)
try:
yield new_dir
finally:
cd.clean_up()
Simplify these decorators, since we don't use the classes here anyway."""Helpers for codejail."""
import contextlib
import os
import shutil
import tempfile
@contextlib.contextmanager
def temp_directory():
"""
A context manager to make and use a temp directory.
The directory will be removed when done.
"""
temp_dir = tempfile.mkdtemp(prefix="codejail-")
# Make directory readable by other users ('sandbox' user needs to be
# able to read it).
os.chmod(temp_dir, 0775)
try:
yield temp_dir
finally:
# if this errors, something is genuinely wrong, so don't ignore errors.
shutil.rmtree(temp_dir)
@contextlib.contextmanager
def change_directory(new_dir):
"""
A context manager to change the directory, and then change it back.
"""
old_dir = os.getcwd()
os.chdir(new_dir)
try:
yield new_dir
finally:
os.chdir(old_dir)
| <commit_before>"""Helpers for codejail."""
import contextlib
import os
import shutil
import tempfile
class TempDirectory(object):
def __init__(self):
self.temp_dir = tempfile.mkdtemp(prefix="codejail-")
# Make directory readable by other users ('sandbox' user needs to be
# able to read it).
os.chmod(self.temp_dir, 0775)
def clean_up(self):
# if this errors, something is genuinely wrong, so don't ignore errors.
shutil.rmtree(self.temp_dir)
@contextlib.contextmanager
def temp_directory():
"""
A context manager to make and use a temp directory.
The directory will be removed when done.
"""
tmp = TempDirectory()
try:
yield tmp.temp_dir
finally:
tmp.clean_up()
class ChangeDirectory(object):
def __init__(self, new_dir):
self.old_dir = os.getcwd()
os.chdir(new_dir)
def clean_up(self):
os.chdir(self.old_dir)
@contextlib.contextmanager
def change_directory(new_dir):
"""
A context manager to change the directory, and then change it back.
"""
cd = ChangeDirectory(new_dir)
try:
yield new_dir
finally:
cd.clean_up()
<commit_msg>Simplify these decorators, since we don't use the classes here anyway.<commit_after>"""Helpers for codejail."""
import contextlib
import os
import shutil
import tempfile
@contextlib.contextmanager
def temp_directory():
"""
A context manager to make and use a temp directory.
The directory will be removed when done.
"""
temp_dir = tempfile.mkdtemp(prefix="codejail-")
# Make directory readable by other users ('sandbox' user needs to be
# able to read it).
os.chmod(temp_dir, 0775)
try:
yield temp_dir
finally:
# if this errors, something is genuinely wrong, so don't ignore errors.
shutil.rmtree(temp_dir)
@contextlib.contextmanager
def change_directory(new_dir):
"""
A context manager to change the directory, and then change it back.
"""
old_dir = os.getcwd()
os.chdir(new_dir)
try:
yield new_dir
finally:
os.chdir(old_dir)
|
c0808574aaf410683f9c405e98be74a3ad4f4f2c | tests/events_test.py | tests/events_test.py | from unittest import TestCase
from mock import Mock
from nyuki.events import EventManager, Event, on_event
class Loop(Mock):
STACK = list()
def async(self, cb, *args):
self.STACK.append(cb)
class TestEventManager(TestCase):
def setUp(self):
loop = Mock()
self.manager = EventManager(loop)
def test_001_init(self):
# Ensure callback tree has been properly setup.
self.assertCountEqual(self.manager._callbacks.keys(), list(Event))
def test_002a_register(self):
pass
def test_002b_register_error(self):
pass
def test_003a_trigger(self):
pass
def test_003b_trigger_error(self):
pass
def tearDown(self):
pass | from unittest import TestCase
from mock import Mock
from nyuki.events import EventManager, Event, on_event
class TestOnEvent(TestCase):
def test_001_call(self):
@on_event(Event.Connected, Event.Disconnected)
def test():
pass
self.assertIsInstance(test.on_event, set)
class TestEventManager(TestCase):
def setUp(self):
self.loop = Mock()
self.manager = EventManager(self.loop)
def test_001_init(self):
# Ensure callback tree has been properly setup
self.assertCountEqual(self.manager._callbacks.keys(), list(Event))
def test_002a_register(self):
# For all kind of event, we're ensure we can add a callback
for event in Event:
callback = (lambda x: x)
self.manager.register(event, callback)
self.assertIn(callback, self.manager._callbacks[event])
def test_002b_register_error(self):
# Here's what happens when the specified event does not exists
event = Mock()
callback = (lambda x: x)
self.assertRaises(ValueError, self.manager.register, event, callback)
def test_003a_trigger(self):
# Ensure callbacks are properly scheduled when an event is triggered
callbacks = list()
self.loop.async = (lambda c, *args: callbacks.append(c))
cb = (lambda x: x)
self.manager.register(Event.Connected, cb)
self.manager.trigger(Event.Connected)
self.assertIn(cb, callbacks)
def test_003b_trigger_error(self):
# Ensure we can not trigger an event that does not exists
event = Mock()
self.assertRaises(ValueError, self.manager.trigger, event)
| Add unit tests on events. | Add unit tests on events.
| Python | apache-2.0 | optiflows/nyuki,optiflows/nyuki,gdraynz/nyuki,gdraynz/nyuki | from unittest import TestCase
from mock import Mock
from nyuki.events import EventManager, Event, on_event
class Loop(Mock):
STACK = list()
def async(self, cb, *args):
self.STACK.append(cb)
class TestEventManager(TestCase):
def setUp(self):
loop = Mock()
self.manager = EventManager(loop)
def test_001_init(self):
# Ensure callback tree has been properly setup.
self.assertCountEqual(self.manager._callbacks.keys(), list(Event))
def test_002a_register(self):
pass
def test_002b_register_error(self):
pass
def test_003a_trigger(self):
pass
def test_003b_trigger_error(self):
pass
def tearDown(self):
passAdd unit tests on events. | from unittest import TestCase
from mock import Mock
from nyuki.events import EventManager, Event, on_event
class TestOnEvent(TestCase):
def test_001_call(self):
@on_event(Event.Connected, Event.Disconnected)
def test():
pass
self.assertIsInstance(test.on_event, set)
class TestEventManager(TestCase):
def setUp(self):
self.loop = Mock()
self.manager = EventManager(self.loop)
def test_001_init(self):
# Ensure callback tree has been properly setup
self.assertCountEqual(self.manager._callbacks.keys(), list(Event))
def test_002a_register(self):
# For all kind of event, we're ensure we can add a callback
for event in Event:
callback = (lambda x: x)
self.manager.register(event, callback)
self.assertIn(callback, self.manager._callbacks[event])
def test_002b_register_error(self):
# Here's what happens when the specified event does not exists
event = Mock()
callback = (lambda x: x)
self.assertRaises(ValueError, self.manager.register, event, callback)
def test_003a_trigger(self):
# Ensure callbacks are properly scheduled when an event is triggered
callbacks = list()
self.loop.async = (lambda c, *args: callbacks.append(c))
cb = (lambda x: x)
self.manager.register(Event.Connected, cb)
self.manager.trigger(Event.Connected)
self.assertIn(cb, callbacks)
def test_003b_trigger_error(self):
# Ensure we can not trigger an event that does not exists
event = Mock()
self.assertRaises(ValueError, self.manager.trigger, event)
| <commit_before>from unittest import TestCase
from mock import Mock
from nyuki.events import EventManager, Event, on_event
class Loop(Mock):
STACK = list()
def async(self, cb, *args):
self.STACK.append(cb)
class TestEventManager(TestCase):
def setUp(self):
loop = Mock()
self.manager = EventManager(loop)
def test_001_init(self):
# Ensure callback tree has been properly setup.
self.assertCountEqual(self.manager._callbacks.keys(), list(Event))
def test_002a_register(self):
pass
def test_002b_register_error(self):
pass
def test_003a_trigger(self):
pass
def test_003b_trigger_error(self):
pass
def tearDown(self):
pass<commit_msg>Add unit tests on events.<commit_after> | from unittest import TestCase
from mock import Mock
from nyuki.events import EventManager, Event, on_event
class TestOnEvent(TestCase):
def test_001_call(self):
@on_event(Event.Connected, Event.Disconnected)
def test():
pass
self.assertIsInstance(test.on_event, set)
class TestEventManager(TestCase):
def setUp(self):
self.loop = Mock()
self.manager = EventManager(self.loop)
def test_001_init(self):
# Ensure callback tree has been properly setup
self.assertCountEqual(self.manager._callbacks.keys(), list(Event))
def test_002a_register(self):
# For all kind of event, we're ensure we can add a callback
for event in Event:
callback = (lambda x: x)
self.manager.register(event, callback)
self.assertIn(callback, self.manager._callbacks[event])
def test_002b_register_error(self):
# Here's what happens when the specified event does not exists
event = Mock()
callback = (lambda x: x)
self.assertRaises(ValueError, self.manager.register, event, callback)
def test_003a_trigger(self):
# Ensure callbacks are properly scheduled when an event is triggered
callbacks = list()
self.loop.async = (lambda c, *args: callbacks.append(c))
cb = (lambda x: x)
self.manager.register(Event.Connected, cb)
self.manager.trigger(Event.Connected)
self.assertIn(cb, callbacks)
def test_003b_trigger_error(self):
# Ensure we can not trigger an event that does not exists
event = Mock()
self.assertRaises(ValueError, self.manager.trigger, event)
| from unittest import TestCase
from mock import Mock
from nyuki.events import EventManager, Event, on_event
class Loop(Mock):
STACK = list()
def async(self, cb, *args):
self.STACK.append(cb)
class TestEventManager(TestCase):
def setUp(self):
loop = Mock()
self.manager = EventManager(loop)
def test_001_init(self):
# Ensure callback tree has been properly setup.
self.assertCountEqual(self.manager._callbacks.keys(), list(Event))
def test_002a_register(self):
pass
def test_002b_register_error(self):
pass
def test_003a_trigger(self):
pass
def test_003b_trigger_error(self):
pass
def tearDown(self):
passAdd unit tests on events.from unittest import TestCase
from mock import Mock
from nyuki.events import EventManager, Event, on_event
class TestOnEvent(TestCase):
def test_001_call(self):
@on_event(Event.Connected, Event.Disconnected)
def test():
pass
self.assertIsInstance(test.on_event, set)
class TestEventManager(TestCase):
def setUp(self):
self.loop = Mock()
self.manager = EventManager(self.loop)
def test_001_init(self):
# Ensure callback tree has been properly setup
self.assertCountEqual(self.manager._callbacks.keys(), list(Event))
def test_002a_register(self):
# For all kind of event, we're ensure we can add a callback
for event in Event:
callback = (lambda x: x)
self.manager.register(event, callback)
self.assertIn(callback, self.manager._callbacks[event])
def test_002b_register_error(self):
# Here's what happens when the specified event does not exists
event = Mock()
callback = (lambda x: x)
self.assertRaises(ValueError, self.manager.register, event, callback)
def test_003a_trigger(self):
# Ensure callbacks are properly scheduled when an event is triggered
callbacks = list()
self.loop.async = (lambda c, *args: callbacks.append(c))
cb = (lambda x: x)
self.manager.register(Event.Connected, cb)
self.manager.trigger(Event.Connected)
self.assertIn(cb, callbacks)
def test_003b_trigger_error(self):
# Ensure we can not trigger an event that does not exists
event = Mock()
self.assertRaises(ValueError, self.manager.trigger, event)
| <commit_before>from unittest import TestCase
from mock import Mock
from nyuki.events import EventManager, Event, on_event
class Loop(Mock):
STACK = list()
def async(self, cb, *args):
self.STACK.append(cb)
class TestEventManager(TestCase):
def setUp(self):
loop = Mock()
self.manager = EventManager(loop)
def test_001_init(self):
# Ensure callback tree has been properly setup.
self.assertCountEqual(self.manager._callbacks.keys(), list(Event))
def test_002a_register(self):
pass
def test_002b_register_error(self):
pass
def test_003a_trigger(self):
pass
def test_003b_trigger_error(self):
pass
def tearDown(self):
pass<commit_msg>Add unit tests on events.<commit_after>from unittest import TestCase
from mock import Mock
from nyuki.events import EventManager, Event, on_event
class TestOnEvent(TestCase):
def test_001_call(self):
@on_event(Event.Connected, Event.Disconnected)
def test():
pass
self.assertIsInstance(test.on_event, set)
class TestEventManager(TestCase):
def setUp(self):
self.loop = Mock()
self.manager = EventManager(self.loop)
def test_001_init(self):
# Ensure callback tree has been properly setup
self.assertCountEqual(self.manager._callbacks.keys(), list(Event))
def test_002a_register(self):
# For all kind of event, we're ensure we can add a callback
for event in Event:
callback = (lambda x: x)
self.manager.register(event, callback)
self.assertIn(callback, self.manager._callbacks[event])
def test_002b_register_error(self):
# Here's what happens when the specified event does not exists
event = Mock()
callback = (lambda x: x)
self.assertRaises(ValueError, self.manager.register, event, callback)
def test_003a_trigger(self):
# Ensure callbacks are properly scheduled when an event is triggered
callbacks = list()
self.loop.async = (lambda c, *args: callbacks.append(c))
cb = (lambda x: x)
self.manager.register(Event.Connected, cb)
self.manager.trigger(Event.Connected)
self.assertIn(cb, callbacks)
def test_003b_trigger_error(self):
# Ensure we can not trigger an event that does not exists
event = Mock()
self.assertRaises(ValueError, self.manager.trigger, event)
|
6aa53f1fda74eb10051cb0bcc315f7db7dee1b57 | tests/test_propagation.py | tests/test_propagation.py | from opentracing import Format
from basictracer import BasicTracer
def test_propagation():
tracer = BasicTracer()
sp = tracer.start_span(operation_name="test")
sp.set_baggage_item("foo", "bar")
opname = 'op'
tests = [(Format.BINARY, bytearray()),
(Format.TEXT_MAP, {})]
for format, carrier in tests:
tracer.inject(sp, format, carrier)
child = tracer.join(opname, format, carrier)
assert child.context.trace_id == sp.context.trace_id
assert child.context.parent_id == sp.context.span_id
assert child.context.sampled == sp.context.sampled
assert child.context.baggage == sp.context.baggage
| import pytest
from opentracing import Format, UnsupportedFormatException
from basictracer import BasicTracer
def test_propagation():
tracer = BasicTracer()
sp = tracer.start_span(operation_name="test")
sp.context.sampled = False
sp.set_baggage_item("foo", "bar")
opname = 'op'
# Test invalid types
with pytest.raises(UnsupportedFormatException):
tracer.inject(sp, "invalid", {})
with pytest.raises(UnsupportedFormatException):
tracer.join("", "invalid", {})
tests = [(Format.BINARY, bytearray()),
(Format.TEXT_MAP, {})]
for format, carrier in tests:
tracer.inject(sp, format, carrier)
child = tracer.join(opname, format, carrier)
assert child.context.trace_id == sp.context.trace_id
assert child.context.parent_id == sp.context.span_id
assert child.context.sampled == sp.context.sampled
assert child.context.baggage == sp.context.baggage
def test_start_span():
""" Test in process child span creation."""
tracer = BasicTracer()
sp = tracer.start_span(operation_name="test")
sp.set_baggage_item("foo", "bar")
child = tracer.start_span(operation_name="child", parent=sp)
assert child.context.trace_id == sp.context.trace_id
assert child.context.parent_id == sp.context.span_id
assert child.context.sampled == sp.context.sampled
assert child.context.baggage == sp.context.baggage
| Add baggage and invalid carrier tests | Add baggage and invalid carrier tests
| Python | apache-2.0 | opentracing/basictracer-python | from opentracing import Format
from basictracer import BasicTracer
def test_propagation():
tracer = BasicTracer()
sp = tracer.start_span(operation_name="test")
sp.set_baggage_item("foo", "bar")
opname = 'op'
tests = [(Format.BINARY, bytearray()),
(Format.TEXT_MAP, {})]
for format, carrier in tests:
tracer.inject(sp, format, carrier)
child = tracer.join(opname, format, carrier)
assert child.context.trace_id == sp.context.trace_id
assert child.context.parent_id == sp.context.span_id
assert child.context.sampled == sp.context.sampled
assert child.context.baggage == sp.context.baggage
Add baggage and invalid carrier tests | import pytest
from opentracing import Format, UnsupportedFormatException
from basictracer import BasicTracer
def test_propagation():
tracer = BasicTracer()
sp = tracer.start_span(operation_name="test")
sp.context.sampled = False
sp.set_baggage_item("foo", "bar")
opname = 'op'
# Test invalid types
with pytest.raises(UnsupportedFormatException):
tracer.inject(sp, "invalid", {})
with pytest.raises(UnsupportedFormatException):
tracer.join("", "invalid", {})
tests = [(Format.BINARY, bytearray()),
(Format.TEXT_MAP, {})]
for format, carrier in tests:
tracer.inject(sp, format, carrier)
child = tracer.join(opname, format, carrier)
assert child.context.trace_id == sp.context.trace_id
assert child.context.parent_id == sp.context.span_id
assert child.context.sampled == sp.context.sampled
assert child.context.baggage == sp.context.baggage
def test_start_span():
""" Test in process child span creation."""
tracer = BasicTracer()
sp = tracer.start_span(operation_name="test")
sp.set_baggage_item("foo", "bar")
child = tracer.start_span(operation_name="child", parent=sp)
assert child.context.trace_id == sp.context.trace_id
assert child.context.parent_id == sp.context.span_id
assert child.context.sampled == sp.context.sampled
assert child.context.baggage == sp.context.baggage
| <commit_before>from opentracing import Format
from basictracer import BasicTracer
def test_propagation():
tracer = BasicTracer()
sp = tracer.start_span(operation_name="test")
sp.set_baggage_item("foo", "bar")
opname = 'op'
tests = [(Format.BINARY, bytearray()),
(Format.TEXT_MAP, {})]
for format, carrier in tests:
tracer.inject(sp, format, carrier)
child = tracer.join(opname, format, carrier)
assert child.context.trace_id == sp.context.trace_id
assert child.context.parent_id == sp.context.span_id
assert child.context.sampled == sp.context.sampled
assert child.context.baggage == sp.context.baggage
<commit_msg>Add baggage and invalid carrier tests<commit_after> | import pytest
from opentracing import Format, UnsupportedFormatException
from basictracer import BasicTracer
def test_propagation():
tracer = BasicTracer()
sp = tracer.start_span(operation_name="test")
sp.context.sampled = False
sp.set_baggage_item("foo", "bar")
opname = 'op'
# Test invalid types
with pytest.raises(UnsupportedFormatException):
tracer.inject(sp, "invalid", {})
with pytest.raises(UnsupportedFormatException):
tracer.join("", "invalid", {})
tests = [(Format.BINARY, bytearray()),
(Format.TEXT_MAP, {})]
for format, carrier in tests:
tracer.inject(sp, format, carrier)
child = tracer.join(opname, format, carrier)
assert child.context.trace_id == sp.context.trace_id
assert child.context.parent_id == sp.context.span_id
assert child.context.sampled == sp.context.sampled
assert child.context.baggage == sp.context.baggage
def test_start_span():
""" Test in process child span creation."""
tracer = BasicTracer()
sp = tracer.start_span(operation_name="test")
sp.set_baggage_item("foo", "bar")
child = tracer.start_span(operation_name="child", parent=sp)
assert child.context.trace_id == sp.context.trace_id
assert child.context.parent_id == sp.context.span_id
assert child.context.sampled == sp.context.sampled
assert child.context.baggage == sp.context.baggage
| from opentracing import Format
from basictracer import BasicTracer
def test_propagation():
tracer = BasicTracer()
sp = tracer.start_span(operation_name="test")
sp.set_baggage_item("foo", "bar")
opname = 'op'
tests = [(Format.BINARY, bytearray()),
(Format.TEXT_MAP, {})]
for format, carrier in tests:
tracer.inject(sp, format, carrier)
child = tracer.join(opname, format, carrier)
assert child.context.trace_id == sp.context.trace_id
assert child.context.parent_id == sp.context.span_id
assert child.context.sampled == sp.context.sampled
assert child.context.baggage == sp.context.baggage
Add baggage and invalid carrier testsimport pytest
from opentracing import Format, UnsupportedFormatException
from basictracer import BasicTracer
def test_propagation():
tracer = BasicTracer()
sp = tracer.start_span(operation_name="test")
sp.context.sampled = False
sp.set_baggage_item("foo", "bar")
opname = 'op'
# Test invalid types
with pytest.raises(UnsupportedFormatException):
tracer.inject(sp, "invalid", {})
with pytest.raises(UnsupportedFormatException):
tracer.join("", "invalid", {})
tests = [(Format.BINARY, bytearray()),
(Format.TEXT_MAP, {})]
for format, carrier in tests:
tracer.inject(sp, format, carrier)
child = tracer.join(opname, format, carrier)
assert child.context.trace_id == sp.context.trace_id
assert child.context.parent_id == sp.context.span_id
assert child.context.sampled == sp.context.sampled
assert child.context.baggage == sp.context.baggage
def test_start_span():
""" Test in process child span creation."""
tracer = BasicTracer()
sp = tracer.start_span(operation_name="test")
sp.set_baggage_item("foo", "bar")
child = tracer.start_span(operation_name="child", parent=sp)
assert child.context.trace_id == sp.context.trace_id
assert child.context.parent_id == sp.context.span_id
assert child.context.sampled == sp.context.sampled
assert child.context.baggage == sp.context.baggage
| <commit_before>from opentracing import Format
from basictracer import BasicTracer
def test_propagation():
tracer = BasicTracer()
sp = tracer.start_span(operation_name="test")
sp.set_baggage_item("foo", "bar")
opname = 'op'
tests = [(Format.BINARY, bytearray()),
(Format.TEXT_MAP, {})]
for format, carrier in tests:
tracer.inject(sp, format, carrier)
child = tracer.join(opname, format, carrier)
assert child.context.trace_id == sp.context.trace_id
assert child.context.parent_id == sp.context.span_id
assert child.context.sampled == sp.context.sampled
assert child.context.baggage == sp.context.baggage
<commit_msg>Add baggage and invalid carrier tests<commit_after>import pytest
from opentracing import Format, UnsupportedFormatException
from basictracer import BasicTracer
def test_propagation():
tracer = BasicTracer()
sp = tracer.start_span(operation_name="test")
sp.context.sampled = False
sp.set_baggage_item("foo", "bar")
opname = 'op'
# Test invalid types
with pytest.raises(UnsupportedFormatException):
tracer.inject(sp, "invalid", {})
with pytest.raises(UnsupportedFormatException):
tracer.join("", "invalid", {})
tests = [(Format.BINARY, bytearray()),
(Format.TEXT_MAP, {})]
for format, carrier in tests:
tracer.inject(sp, format, carrier)
child = tracer.join(opname, format, carrier)
assert child.context.trace_id == sp.context.trace_id
assert child.context.parent_id == sp.context.span_id
assert child.context.sampled == sp.context.sampled
assert child.context.baggage == sp.context.baggage
def test_start_span():
""" Test in process child span creation."""
tracer = BasicTracer()
sp = tracer.start_span(operation_name="test")
sp.set_baggage_item("foo", "bar")
child = tracer.start_span(operation_name="child", parent=sp)
assert child.context.trace_id == sp.context.trace_id
assert child.context.parent_id == sp.context.span_id
assert child.context.sampled == sp.context.sampled
assert child.context.baggage == sp.context.baggage
|
13a0c8b822582f84ff393298b13cf1e43642f825 | tests/test_stacks_file.py | tests/test_stacks_file.py | import json
from dmaws.stacks import Stack
from dmaws.context import Context
def is_true(x):
assert x
def is_in(a, b):
assert a in b
def valid_stack_json(stack):
text = stack.build('stage', 'env', {}).template_body
template = json.loads(text)
assert 'Parameters' in template
assert set(template['Parameters']) == set(stack.parameters)
assert 'Resources' in template
def test_stack_definitions():
ctx = Context()
ctx.load_stacks('stacks.yml')
yield('Found stacks in the stacks.yml',
is_true, any(isinstance(s, Stack) for s in ctx.stacks.values()))
yield('Found groups in stacks.yml',
is_true, any(isinstance(s, list) for s in ctx.stacks.values()))
for name, stack in ctx.stacks.items():
if isinstance(stack, list):
for s in stack:
yield('Stack "%s" in group %s is defined' % (s, name),
is_in, s, ctx.stacks)
else:
for s in stack.dependencies:
yield('%s dependency "%s" is defined' % (name, s),
is_in, s, ctx.stacks)
yield('Stack "%s" template_body is valid JSON' % name,
valid_stack_json, stack)
| import os
import json
from dmaws.stacks import Stack
from dmaws.context import Context
def is_true(x):
assert x
def is_in(a, b):
assert a in b
def valid_stack_json(ctx, stack):
text = stack.build('stage', 'env', ctx.variables).template_body
template = json.loads(text)
assert 'Parameters' in template
assert set(template['Parameters']) == set(stack.parameters)
assert 'Resources' in template
def _load_default_vars(ctx):
default_vars_files = [
'vars/common.yml',
]
if os.path.exists('vars/user.yml'):
default_vars_files.append('vars/user.yml')
ctx.load_variables(files=default_vars_files)
def test_stack_definitions():
ctx = Context()
_load_default_vars(ctx)
ctx.load_stacks('stacks.yml')
yield('Found stacks in the stacks.yml',
is_true, any(isinstance(s, Stack) for s in ctx.stacks.values()))
yield('Found groups in stacks.yml',
is_true, any(isinstance(s, list) for s in ctx.stacks.values()))
for name, stack in ctx.stacks.items():
if isinstance(stack, list):
for s in stack:
yield('Stack "%s" in group %s is defined' % (s, name),
is_in, s, ctx.stacks)
else:
for s in stack.dependencies:
yield('%s dependency "%s" is defined' % (name, s),
is_in, s, ctx.stacks)
yield('Stack "%s" template_body is valid JSON' % name,
valid_stack_json, ctx, stack)
| Load default var files when testing template JSON | Load default var files when testing template JSON
Since template Jinja processing has access to the template variables
we need to load the default files when testing the JSON output.
| Python | mit | alphagov/digitalmarketplace-aws,alphagov/digitalmarketplace-aws,alphagov/digitalmarketplace-aws | import json
from dmaws.stacks import Stack
from dmaws.context import Context
def is_true(x):
assert x
def is_in(a, b):
assert a in b
def valid_stack_json(stack):
text = stack.build('stage', 'env', {}).template_body
template = json.loads(text)
assert 'Parameters' in template
assert set(template['Parameters']) == set(stack.parameters)
assert 'Resources' in template
def test_stack_definitions():
ctx = Context()
ctx.load_stacks('stacks.yml')
yield('Found stacks in the stacks.yml',
is_true, any(isinstance(s, Stack) for s in ctx.stacks.values()))
yield('Found groups in stacks.yml',
is_true, any(isinstance(s, list) for s in ctx.stacks.values()))
for name, stack in ctx.stacks.items():
if isinstance(stack, list):
for s in stack:
yield('Stack "%s" in group %s is defined' % (s, name),
is_in, s, ctx.stacks)
else:
for s in stack.dependencies:
yield('%s dependency "%s" is defined' % (name, s),
is_in, s, ctx.stacks)
yield('Stack "%s" template_body is valid JSON' % name,
valid_stack_json, stack)
Load default var files when testing template JSON
Since template Jinja processing has access to the template variables
we need to load the default files when testing the JSON output. | import os
import json
from dmaws.stacks import Stack
from dmaws.context import Context
def is_true(x):
assert x
def is_in(a, b):
assert a in b
def valid_stack_json(ctx, stack):
text = stack.build('stage', 'env', ctx.variables).template_body
template = json.loads(text)
assert 'Parameters' in template
assert set(template['Parameters']) == set(stack.parameters)
assert 'Resources' in template
def _load_default_vars(ctx):
default_vars_files = [
'vars/common.yml',
]
if os.path.exists('vars/user.yml'):
default_vars_files.append('vars/user.yml')
ctx.load_variables(files=default_vars_files)
def test_stack_definitions():
ctx = Context()
_load_default_vars(ctx)
ctx.load_stacks('stacks.yml')
yield('Found stacks in the stacks.yml',
is_true, any(isinstance(s, Stack) for s in ctx.stacks.values()))
yield('Found groups in stacks.yml',
is_true, any(isinstance(s, list) for s in ctx.stacks.values()))
for name, stack in ctx.stacks.items():
if isinstance(stack, list):
for s in stack:
yield('Stack "%s" in group %s is defined' % (s, name),
is_in, s, ctx.stacks)
else:
for s in stack.dependencies:
yield('%s dependency "%s" is defined' % (name, s),
is_in, s, ctx.stacks)
yield('Stack "%s" template_body is valid JSON' % name,
valid_stack_json, ctx, stack)
| <commit_before>import json
from dmaws.stacks import Stack
from dmaws.context import Context
def is_true(x):
assert x
def is_in(a, b):
assert a in b
def valid_stack_json(stack):
text = stack.build('stage', 'env', {}).template_body
template = json.loads(text)
assert 'Parameters' in template
assert set(template['Parameters']) == set(stack.parameters)
assert 'Resources' in template
def test_stack_definitions():
ctx = Context()
ctx.load_stacks('stacks.yml')
yield('Found stacks in the stacks.yml',
is_true, any(isinstance(s, Stack) for s in ctx.stacks.values()))
yield('Found groups in stacks.yml',
is_true, any(isinstance(s, list) for s in ctx.stacks.values()))
for name, stack in ctx.stacks.items():
if isinstance(stack, list):
for s in stack:
yield('Stack "%s" in group %s is defined' % (s, name),
is_in, s, ctx.stacks)
else:
for s in stack.dependencies:
yield('%s dependency "%s" is defined' % (name, s),
is_in, s, ctx.stacks)
yield('Stack "%s" template_body is valid JSON' % name,
valid_stack_json, stack)
<commit_msg>Load default var files when testing template JSON
Since template Jinja processing has access to the template variables
we need to load the default files when testing the JSON output.<commit_after> | import os
import json
from dmaws.stacks import Stack
from dmaws.context import Context
def is_true(x):
assert x
def is_in(a, b):
assert a in b
def valid_stack_json(ctx, stack):
text = stack.build('stage', 'env', ctx.variables).template_body
template = json.loads(text)
assert 'Parameters' in template
assert set(template['Parameters']) == set(stack.parameters)
assert 'Resources' in template
def _load_default_vars(ctx):
default_vars_files = [
'vars/common.yml',
]
if os.path.exists('vars/user.yml'):
default_vars_files.append('vars/user.yml')
ctx.load_variables(files=default_vars_files)
def test_stack_definitions():
ctx = Context()
_load_default_vars(ctx)
ctx.load_stacks('stacks.yml')
yield('Found stacks in the stacks.yml',
is_true, any(isinstance(s, Stack) for s in ctx.stacks.values()))
yield('Found groups in stacks.yml',
is_true, any(isinstance(s, list) for s in ctx.stacks.values()))
for name, stack in ctx.stacks.items():
if isinstance(stack, list):
for s in stack:
yield('Stack "%s" in group %s is defined' % (s, name),
is_in, s, ctx.stacks)
else:
for s in stack.dependencies:
yield('%s dependency "%s" is defined' % (name, s),
is_in, s, ctx.stacks)
yield('Stack "%s" template_body is valid JSON' % name,
valid_stack_json, ctx, stack)
| import json
from dmaws.stacks import Stack
from dmaws.context import Context
def is_true(x):
assert x
def is_in(a, b):
assert a in b
def valid_stack_json(stack):
text = stack.build('stage', 'env', {}).template_body
template = json.loads(text)
assert 'Parameters' in template
assert set(template['Parameters']) == set(stack.parameters)
assert 'Resources' in template
def test_stack_definitions():
ctx = Context()
ctx.load_stacks('stacks.yml')
yield('Found stacks in the stacks.yml',
is_true, any(isinstance(s, Stack) for s in ctx.stacks.values()))
yield('Found groups in stacks.yml',
is_true, any(isinstance(s, list) for s in ctx.stacks.values()))
for name, stack in ctx.stacks.items():
if isinstance(stack, list):
for s in stack:
yield('Stack "%s" in group %s is defined' % (s, name),
is_in, s, ctx.stacks)
else:
for s in stack.dependencies:
yield('%s dependency "%s" is defined' % (name, s),
is_in, s, ctx.stacks)
yield('Stack "%s" template_body is valid JSON' % name,
valid_stack_json, stack)
Load default var files when testing template JSON
Since template Jinja processing has access to the template variables
we need to load the default files when testing the JSON output.import os
import json
from dmaws.stacks import Stack
from dmaws.context import Context
def is_true(x):
assert x
def is_in(a, b):
assert a in b
def valid_stack_json(ctx, stack):
text = stack.build('stage', 'env', ctx.variables).template_body
template = json.loads(text)
assert 'Parameters' in template
assert set(template['Parameters']) == set(stack.parameters)
assert 'Resources' in template
def _load_default_vars(ctx):
default_vars_files = [
'vars/common.yml',
]
if os.path.exists('vars/user.yml'):
default_vars_files.append('vars/user.yml')
ctx.load_variables(files=default_vars_files)
def test_stack_definitions():
ctx = Context()
_load_default_vars(ctx)
ctx.load_stacks('stacks.yml')
yield('Found stacks in the stacks.yml',
is_true, any(isinstance(s, Stack) for s in ctx.stacks.values()))
yield('Found groups in stacks.yml',
is_true, any(isinstance(s, list) for s in ctx.stacks.values()))
for name, stack in ctx.stacks.items():
if isinstance(stack, list):
for s in stack:
yield('Stack "%s" in group %s is defined' % (s, name),
is_in, s, ctx.stacks)
else:
for s in stack.dependencies:
yield('%s dependency "%s" is defined' % (name, s),
is_in, s, ctx.stacks)
yield('Stack "%s" template_body is valid JSON' % name,
valid_stack_json, ctx, stack)
| <commit_before>import json
from dmaws.stacks import Stack
from dmaws.context import Context
def is_true(x):
assert x
def is_in(a, b):
assert a in b
def valid_stack_json(stack):
text = stack.build('stage', 'env', {}).template_body
template = json.loads(text)
assert 'Parameters' in template
assert set(template['Parameters']) == set(stack.parameters)
assert 'Resources' in template
def test_stack_definitions():
ctx = Context()
ctx.load_stacks('stacks.yml')
yield('Found stacks in the stacks.yml',
is_true, any(isinstance(s, Stack) for s in ctx.stacks.values()))
yield('Found groups in stacks.yml',
is_true, any(isinstance(s, list) for s in ctx.stacks.values()))
for name, stack in ctx.stacks.items():
if isinstance(stack, list):
for s in stack:
yield('Stack "%s" in group %s is defined' % (s, name),
is_in, s, ctx.stacks)
else:
for s in stack.dependencies:
yield('%s dependency "%s" is defined' % (name, s),
is_in, s, ctx.stacks)
yield('Stack "%s" template_body is valid JSON' % name,
valid_stack_json, stack)
<commit_msg>Load default var files when testing template JSON
Since template Jinja processing has access to the template variables
we need to load the default files when testing the JSON output.<commit_after>import os
import json
from dmaws.stacks import Stack
from dmaws.context import Context
def is_true(x):
assert x
def is_in(a, b):
assert a in b
def valid_stack_json(ctx, stack):
text = stack.build('stage', 'env', ctx.variables).template_body
template = json.loads(text)
assert 'Parameters' in template
assert set(template['Parameters']) == set(stack.parameters)
assert 'Resources' in template
def _load_default_vars(ctx):
default_vars_files = [
'vars/common.yml',
]
if os.path.exists('vars/user.yml'):
default_vars_files.append('vars/user.yml')
ctx.load_variables(files=default_vars_files)
def test_stack_definitions():
ctx = Context()
_load_default_vars(ctx)
ctx.load_stacks('stacks.yml')
yield('Found stacks in the stacks.yml',
is_true, any(isinstance(s, Stack) for s in ctx.stacks.values()))
yield('Found groups in stacks.yml',
is_true, any(isinstance(s, list) for s in ctx.stacks.values()))
for name, stack in ctx.stacks.items():
if isinstance(stack, list):
for s in stack:
yield('Stack "%s" in group %s is defined' % (s, name),
is_in, s, ctx.stacks)
else:
for s in stack.dependencies:
yield('%s dependency "%s" is defined' % (name, s),
is_in, s, ctx.stacks)
yield('Stack "%s" template_body is valid JSON' % name,
valid_stack_json, ctx, stack)
|
6aabf31aeb6766677f805bd4c0d5e4fc26522e53 | tests/test_memory.py | tests/test_memory.py | import sys
import weakref
import pytest # type: ignore
from hypothesis import given
from ppb_vector import Vector2
from utils import floats, vectors
class DummyVector:
"""A naïve representation of vectors."""
x: float
y: float
def __init__(self, x, y):
self.x = float(x)
self.y = float(y)
@pytest.mark.skipif(sys.implementation.name != 'cpython',
reason="PyPy optimises __slots__ automatically.")
@given(x=floats(), y=floats())
def test_object_size(x, y):
"""Check that Vector2 is 2 times smaller than a naïve version."""
from pympler.asizeof import asizeof as sizeof # type: ignore
assert sizeof(Vector2(x, y)) < sizeof(DummyVector(x, y)) / 2
@given(v=vectors())
def test_weak_ref(v):
"""Check that weak references can be made to Vector2s."""
assert weakref.ref(v) is not None
| import sys
import weakref
import pytest # type: ignore
from hypothesis import given
from ppb_vector import Vector2
from utils import floats, vectors
class DummyVector:
"""A naïve representation of vectors."""
x: float
y: float
def __init__(self, x, y):
self.x = float(x)
self.y = float(y)
@pytest.mark.skipif(sys.implementation.name != 'cpython',
reason="PyPy optimises __slots__ automatically.")
@pytest.mark.skipif(sys.implementation.version.minor > 7,
reason="Pympler 0.6 is broken under Python 3.8. See pympler#74")
@given(x=floats(), y=floats())
def test_object_size(x, y):
"""Check that Vector2 is 2 times smaller than a naïve version."""
from pympler.asizeof import asizeof as sizeof # type: ignore
assert sizeof(Vector2(x, y)) < sizeof(DummyVector(x, y)) / 2
@given(v=vectors())
def test_weak_ref(v):
"""Check that weak references can be made to Vector2s."""
assert weakref.ref(v) is not None
| Disable test_object_size under CPython 3.8 | tests/memory: Disable test_object_size under CPython 3.8
| Python | artistic-2.0 | ppb/ppb-vector,ppb/ppb-vector | import sys
import weakref
import pytest # type: ignore
from hypothesis import given
from ppb_vector import Vector2
from utils import floats, vectors
class DummyVector:
"""A naïve representation of vectors."""
x: float
y: float
def __init__(self, x, y):
self.x = float(x)
self.y = float(y)
@pytest.mark.skipif(sys.implementation.name != 'cpython',
reason="PyPy optimises __slots__ automatically.")
@given(x=floats(), y=floats())
def test_object_size(x, y):
"""Check that Vector2 is 2 times smaller than a naïve version."""
from pympler.asizeof import asizeof as sizeof # type: ignore
assert sizeof(Vector2(x, y)) < sizeof(DummyVector(x, y)) / 2
@given(v=vectors())
def test_weak_ref(v):
"""Check that weak references can be made to Vector2s."""
assert weakref.ref(v) is not None
tests/memory: Disable test_object_size under CPython 3.8 | import sys
import weakref
import pytest # type: ignore
from hypothesis import given
from ppb_vector import Vector2
from utils import floats, vectors
class DummyVector:
"""A naïve representation of vectors."""
x: float
y: float
def __init__(self, x, y):
self.x = float(x)
self.y = float(y)
@pytest.mark.skipif(sys.implementation.name != 'cpython',
reason="PyPy optimises __slots__ automatically.")
@pytest.mark.skipif(sys.implementation.version.minor > 7,
reason="Pympler 0.6 is broken under Python 3.8. See pympler#74")
@given(x=floats(), y=floats())
def test_object_size(x, y):
"""Check that Vector2 is 2 times smaller than a naïve version."""
from pympler.asizeof import asizeof as sizeof # type: ignore
assert sizeof(Vector2(x, y)) < sizeof(DummyVector(x, y)) / 2
@given(v=vectors())
def test_weak_ref(v):
"""Check that weak references can be made to Vector2s."""
assert weakref.ref(v) is not None
| <commit_before>import sys
import weakref
import pytest # type: ignore
from hypothesis import given
from ppb_vector import Vector2
from utils import floats, vectors
class DummyVector:
"""A naïve representation of vectors."""
x: float
y: float
def __init__(self, x, y):
self.x = float(x)
self.y = float(y)
@pytest.mark.skipif(sys.implementation.name != 'cpython',
reason="PyPy optimises __slots__ automatically.")
@given(x=floats(), y=floats())
def test_object_size(x, y):
"""Check that Vector2 is 2 times smaller than a naïve version."""
from pympler.asizeof import asizeof as sizeof # type: ignore
assert sizeof(Vector2(x, y)) < sizeof(DummyVector(x, y)) / 2
@given(v=vectors())
def test_weak_ref(v):
"""Check that weak references can be made to Vector2s."""
assert weakref.ref(v) is not None
<commit_msg>tests/memory: Disable test_object_size under CPython 3.8<commit_after> | import sys
import weakref
import pytest # type: ignore
from hypothesis import given
from ppb_vector import Vector2
from utils import floats, vectors
class DummyVector:
"""A naïve representation of vectors."""
x: float
y: float
def __init__(self, x, y):
self.x = float(x)
self.y = float(y)
@pytest.mark.skipif(sys.implementation.name != 'cpython',
reason="PyPy optimises __slots__ automatically.")
@pytest.mark.skipif(sys.implementation.version.minor > 7,
reason="Pympler 0.6 is broken under Python 3.8. See pympler#74")
@given(x=floats(), y=floats())
def test_object_size(x, y):
"""Check that Vector2 is 2 times smaller than a naïve version."""
from pympler.asizeof import asizeof as sizeof # type: ignore
assert sizeof(Vector2(x, y)) < sizeof(DummyVector(x, y)) / 2
@given(v=vectors())
def test_weak_ref(v):
"""Check that weak references can be made to Vector2s."""
assert weakref.ref(v) is not None
| import sys
import weakref
import pytest # type: ignore
from hypothesis import given
from ppb_vector import Vector2
from utils import floats, vectors
class DummyVector:
"""A naïve representation of vectors."""
x: float
y: float
def __init__(self, x, y):
self.x = float(x)
self.y = float(y)
@pytest.mark.skipif(sys.implementation.name != 'cpython',
reason="PyPy optimises __slots__ automatically.")
@given(x=floats(), y=floats())
def test_object_size(x, y):
"""Check that Vector2 is 2 times smaller than a naïve version."""
from pympler.asizeof import asizeof as sizeof # type: ignore
assert sizeof(Vector2(x, y)) < sizeof(DummyVector(x, y)) / 2
@given(v=vectors())
def test_weak_ref(v):
"""Check that weak references can be made to Vector2s."""
assert weakref.ref(v) is not None
tests/memory: Disable test_object_size under CPython 3.8import sys
import weakref
import pytest # type: ignore
from hypothesis import given
from ppb_vector import Vector2
from utils import floats, vectors
class DummyVector:
"""A naïve representation of vectors."""
x: float
y: float
def __init__(self, x, y):
self.x = float(x)
self.y = float(y)
@pytest.mark.skipif(sys.implementation.name != 'cpython',
reason="PyPy optimises __slots__ automatically.")
@pytest.mark.skipif(sys.implementation.version.minor > 7,
reason="Pympler 0.6 is broken under Python 3.8. See pympler#74")
@given(x=floats(), y=floats())
def test_object_size(x, y):
"""Check that Vector2 is 2 times smaller than a naïve version."""
from pympler.asizeof import asizeof as sizeof # type: ignore
assert sizeof(Vector2(x, y)) < sizeof(DummyVector(x, y)) / 2
@given(v=vectors())
def test_weak_ref(v):
"""Check that weak references can be made to Vector2s."""
assert weakref.ref(v) is not None
| <commit_before>import sys
import weakref
import pytest # type: ignore
from hypothesis import given
from ppb_vector import Vector2
from utils import floats, vectors
class DummyVector:
"""A naïve representation of vectors."""
x: float
y: float
def __init__(self, x, y):
self.x = float(x)
self.y = float(y)
@pytest.mark.skipif(sys.implementation.name != 'cpython',
reason="PyPy optimises __slots__ automatically.")
@given(x=floats(), y=floats())
def test_object_size(x, y):
"""Check that Vector2 is 2 times smaller than a naïve version."""
from pympler.asizeof import asizeof as sizeof # type: ignore
assert sizeof(Vector2(x, y)) < sizeof(DummyVector(x, y)) / 2
@given(v=vectors())
def test_weak_ref(v):
"""Check that weak references can be made to Vector2s."""
assert weakref.ref(v) is not None
<commit_msg>tests/memory: Disable test_object_size under CPython 3.8<commit_after>import sys
import weakref
import pytest # type: ignore
from hypothesis import given
from ppb_vector import Vector2
from utils import floats, vectors
class DummyVector:
"""A naïve representation of vectors."""
x: float
y: float
def __init__(self, x, y):
self.x = float(x)
self.y = float(y)
@pytest.mark.skipif(sys.implementation.name != 'cpython',
reason="PyPy optimises __slots__ automatically.")
@pytest.mark.skipif(sys.implementation.version.minor > 7,
reason="Pympler 0.6 is broken under Python 3.8. See pympler#74")
@given(x=floats(), y=floats())
def test_object_size(x, y):
"""Check that Vector2 is 2 times smaller than a naïve version."""
from pympler.asizeof import asizeof as sizeof # type: ignore
assert sizeof(Vector2(x, y)) < sizeof(DummyVector(x, y)) / 2
@given(v=vectors())
def test_weak_ref(v):
"""Check that weak references can be made to Vector2s."""
assert weakref.ref(v) is not None
|
9712183d01ef95fcd28ed1632346371127ec8a3e | tests/window_test.py | tests/window_test.py | #!/usr/bin/env python
# encoding: utf-8
"""Tests window.py for vimiv's test suite."""
from unittest import main
from vimiv_testcase import VimivTestCase, refresh_gui
class WindowTest(VimivTestCase):
"""Window Tests."""
@classmethod
def setUpClass(cls):
cls.init_test(cls, ["vimiv/testimages/"])
def test_fullscreen(self):
"""Toggle fullscreen."""
# Start without fullscreen
self.assertFalse(self.vimiv["window"].is_fullscreen)
# Fullscreen
self.vimiv["window"].toggle_fullscreen()
refresh_gui(0.05)
# Still not reliable
# self.assertTrue(self.vimiv["window"].is_fullscreen)
# Unfullscreen
self.vimiv["window"].toggle_fullscreen()
refresh_gui(0.05)
# self.assertFalse(self.vimiv["window"].is_fullscreen)
self.vimiv["window"].fullscreen()
def test_scroll(self):
"""Scroll image or thumbnail."""
# Error message
self.vimiv["window"].scroll("m")
self.assertEqual(self.vimiv["statusbar"].left_label.get_text(),
"ERROR: Invalid scroll direction m")
if __name__ == '__main__':
main()
| #!/usr/bin/env python
# encoding: utf-8
"""Tests window.py for vimiv's test suite."""
import os
from unittest import main, skipUnless
from vimiv_testcase import VimivTestCase, refresh_gui
class WindowTest(VimivTestCase):
"""Window Tests."""
@classmethod
def setUpClass(cls):
cls.init_test(cls, ["vimiv/testimages/"])
def test_fullscreen(self):
"""Toggle fullscreen."""
# Start without fullscreen
self.assertFalse(self.vimiv["window"].is_fullscreen)
# Fullscreen
self.vimiv["window"].toggle_fullscreen()
refresh_gui(0.05)
# Still not reliable
# self.assertTrue(self.vimiv["window"].is_fullscreen)
# Unfullscreen
self.vimiv["window"].toggle_fullscreen()
refresh_gui(0.05)
# self.assertFalse(self.vimiv["window"].is_fullscreen)
self.vimiv["window"].fullscreen()
def test_scroll(self):
"""Scroll image or thumbnail."""
# Error message
self.vimiv["window"].scroll("m")
self.assertEqual(self.vimiv["statusbar"].left_label.get_text(),
"ERROR: Invalid scroll direction m")
@skipUnless(os.environ["DISPLAY"] == ":42", "Must run in Xvfb")
def test_check_resize(self):
"""Resize window and check winsize."""
self.assertEqual(self.vimiv["window"].winsize, (800, 600))
self.vimiv["window"].resize(400, 300)
refresh_gui()
self.assertEqual(self.vimiv["window"].winsize, (400, 300))
if __name__ == '__main__':
main()
| Add test for checking window resizing | Add test for checking window resizing
Test if the variable vimiv["window"].winsize is adjusted when resizing the
window. This is only guaranteed to work in Xvfb as e.g. tiling window managers
do not react to the resize from Gtk.
| Python | mit | karlch/vimiv,karlch/vimiv,karlch/vimiv | #!/usr/bin/env python
# encoding: utf-8
"""Tests window.py for vimiv's test suite."""
from unittest import main
from vimiv_testcase import VimivTestCase, refresh_gui
class WindowTest(VimivTestCase):
"""Window Tests."""
@classmethod
def setUpClass(cls):
cls.init_test(cls, ["vimiv/testimages/"])
def test_fullscreen(self):
"""Toggle fullscreen."""
# Start without fullscreen
self.assertFalse(self.vimiv["window"].is_fullscreen)
# Fullscreen
self.vimiv["window"].toggle_fullscreen()
refresh_gui(0.05)
# Still not reliable
# self.assertTrue(self.vimiv["window"].is_fullscreen)
# Unfullscreen
self.vimiv["window"].toggle_fullscreen()
refresh_gui(0.05)
# self.assertFalse(self.vimiv["window"].is_fullscreen)
self.vimiv["window"].fullscreen()
def test_scroll(self):
"""Scroll image or thumbnail."""
# Error message
self.vimiv["window"].scroll("m")
self.assertEqual(self.vimiv["statusbar"].left_label.get_text(),
"ERROR: Invalid scroll direction m")
if __name__ == '__main__':
main()
Add test for checking window resizing
Test if the variable vimiv["window"].winsize is adjusted when resizing the
window. This is only guaranteed to work in Xvfb as e.g. tiling window managers
do not react to the resize from Gtk. | #!/usr/bin/env python
# encoding: utf-8
"""Tests window.py for vimiv's test suite."""
import os
from unittest import main, skipUnless
from vimiv_testcase import VimivTestCase, refresh_gui
class WindowTest(VimivTestCase):
"""Window Tests."""
@classmethod
def setUpClass(cls):
cls.init_test(cls, ["vimiv/testimages/"])
def test_fullscreen(self):
"""Toggle fullscreen."""
# Start without fullscreen
self.assertFalse(self.vimiv["window"].is_fullscreen)
# Fullscreen
self.vimiv["window"].toggle_fullscreen()
refresh_gui(0.05)
# Still not reliable
# self.assertTrue(self.vimiv["window"].is_fullscreen)
# Unfullscreen
self.vimiv["window"].toggle_fullscreen()
refresh_gui(0.05)
# self.assertFalse(self.vimiv["window"].is_fullscreen)
self.vimiv["window"].fullscreen()
def test_scroll(self):
"""Scroll image or thumbnail."""
# Error message
self.vimiv["window"].scroll("m")
self.assertEqual(self.vimiv["statusbar"].left_label.get_text(),
"ERROR: Invalid scroll direction m")
@skipUnless(os.environ["DISPLAY"] == ":42", "Must run in Xvfb")
def test_check_resize(self):
"""Resize window and check winsize."""
self.assertEqual(self.vimiv["window"].winsize, (800, 600))
self.vimiv["window"].resize(400, 300)
refresh_gui()
self.assertEqual(self.vimiv["window"].winsize, (400, 300))
if __name__ == '__main__':
main()
| <commit_before>#!/usr/bin/env python
# encoding: utf-8
"""Tests window.py for vimiv's test suite."""
from unittest import main
from vimiv_testcase import VimivTestCase, refresh_gui
class WindowTest(VimivTestCase):
"""Window Tests."""
@classmethod
def setUpClass(cls):
cls.init_test(cls, ["vimiv/testimages/"])
def test_fullscreen(self):
"""Toggle fullscreen."""
# Start without fullscreen
self.assertFalse(self.vimiv["window"].is_fullscreen)
# Fullscreen
self.vimiv["window"].toggle_fullscreen()
refresh_gui(0.05)
# Still not reliable
# self.assertTrue(self.vimiv["window"].is_fullscreen)
# Unfullscreen
self.vimiv["window"].toggle_fullscreen()
refresh_gui(0.05)
# self.assertFalse(self.vimiv["window"].is_fullscreen)
self.vimiv["window"].fullscreen()
def test_scroll(self):
"""Scroll image or thumbnail."""
# Error message
self.vimiv["window"].scroll("m")
self.assertEqual(self.vimiv["statusbar"].left_label.get_text(),
"ERROR: Invalid scroll direction m")
if __name__ == '__main__':
main()
<commit_msg>Add test for checking window resizing
Test if the variable vimiv["window"].winsize is adjusted when resizing the
window. This is only guaranteed to work in Xvfb as e.g. tiling window managers
do not react to the resize from Gtk.<commit_after> | #!/usr/bin/env python
# encoding: utf-8
"""Tests window.py for vimiv's test suite."""
import os
from unittest import main, skipUnless
from vimiv_testcase import VimivTestCase, refresh_gui
class WindowTest(VimivTestCase):
"""Window Tests."""
@classmethod
def setUpClass(cls):
cls.init_test(cls, ["vimiv/testimages/"])
def test_fullscreen(self):
"""Toggle fullscreen."""
# Start without fullscreen
self.assertFalse(self.vimiv["window"].is_fullscreen)
# Fullscreen
self.vimiv["window"].toggle_fullscreen()
refresh_gui(0.05)
# Still not reliable
# self.assertTrue(self.vimiv["window"].is_fullscreen)
# Unfullscreen
self.vimiv["window"].toggle_fullscreen()
refresh_gui(0.05)
# self.assertFalse(self.vimiv["window"].is_fullscreen)
self.vimiv["window"].fullscreen()
def test_scroll(self):
"""Scroll image or thumbnail."""
# Error message
self.vimiv["window"].scroll("m")
self.assertEqual(self.vimiv["statusbar"].left_label.get_text(),
"ERROR: Invalid scroll direction m")
@skipUnless(os.environ["DISPLAY"] == ":42", "Must run in Xvfb")
def test_check_resize(self):
"""Resize window and check winsize."""
self.assertEqual(self.vimiv["window"].winsize, (800, 600))
self.vimiv["window"].resize(400, 300)
refresh_gui()
self.assertEqual(self.vimiv["window"].winsize, (400, 300))
if __name__ == '__main__':
main()
| #!/usr/bin/env python
# encoding: utf-8
"""Tests window.py for vimiv's test suite."""
from unittest import main
from vimiv_testcase import VimivTestCase, refresh_gui
class WindowTest(VimivTestCase):
"""Window Tests."""
@classmethod
def setUpClass(cls):
cls.init_test(cls, ["vimiv/testimages/"])
def test_fullscreen(self):
"""Toggle fullscreen."""
# Start without fullscreen
self.assertFalse(self.vimiv["window"].is_fullscreen)
# Fullscreen
self.vimiv["window"].toggle_fullscreen()
refresh_gui(0.05)
# Still not reliable
# self.assertTrue(self.vimiv["window"].is_fullscreen)
# Unfullscreen
self.vimiv["window"].toggle_fullscreen()
refresh_gui(0.05)
# self.assertFalse(self.vimiv["window"].is_fullscreen)
self.vimiv["window"].fullscreen()
def test_scroll(self):
"""Scroll image or thumbnail."""
# Error message
self.vimiv["window"].scroll("m")
self.assertEqual(self.vimiv["statusbar"].left_label.get_text(),
"ERROR: Invalid scroll direction m")
if __name__ == '__main__':
main()
Add test for checking window resizing
Test if the variable vimiv["window"].winsize is adjusted when resizing the
window. This is only guaranteed to work in Xvfb as e.g. tiling window managers
do not react to the resize from Gtk.#!/usr/bin/env python
# encoding: utf-8
"""Tests window.py for vimiv's test suite."""
import os
from unittest import main, skipUnless
from vimiv_testcase import VimivTestCase, refresh_gui
class WindowTest(VimivTestCase):
"""Window Tests."""
@classmethod
def setUpClass(cls):
cls.init_test(cls, ["vimiv/testimages/"])
def test_fullscreen(self):
"""Toggle fullscreen."""
# Start without fullscreen
self.assertFalse(self.vimiv["window"].is_fullscreen)
# Fullscreen
self.vimiv["window"].toggle_fullscreen()
refresh_gui(0.05)
# Still not reliable
# self.assertTrue(self.vimiv["window"].is_fullscreen)
# Unfullscreen
self.vimiv["window"].toggle_fullscreen()
refresh_gui(0.05)
# self.assertFalse(self.vimiv["window"].is_fullscreen)
self.vimiv["window"].fullscreen()
def test_scroll(self):
"""Scroll image or thumbnail."""
# Error message
self.vimiv["window"].scroll("m")
self.assertEqual(self.vimiv["statusbar"].left_label.get_text(),
"ERROR: Invalid scroll direction m")
@skipUnless(os.environ["DISPLAY"] == ":42", "Must run in Xvfb")
def test_check_resize(self):
"""Resize window and check winsize."""
self.assertEqual(self.vimiv["window"].winsize, (800, 600))
self.vimiv["window"].resize(400, 300)
refresh_gui()
self.assertEqual(self.vimiv["window"].winsize, (400, 300))
if __name__ == '__main__':
main()
| <commit_before>#!/usr/bin/env python
# encoding: utf-8
"""Tests window.py for vimiv's test suite."""
from unittest import main
from vimiv_testcase import VimivTestCase, refresh_gui
class WindowTest(VimivTestCase):
"""Window Tests."""
@classmethod
def setUpClass(cls):
cls.init_test(cls, ["vimiv/testimages/"])
def test_fullscreen(self):
"""Toggle fullscreen."""
# Start without fullscreen
self.assertFalse(self.vimiv["window"].is_fullscreen)
# Fullscreen
self.vimiv["window"].toggle_fullscreen()
refresh_gui(0.05)
# Still not reliable
# self.assertTrue(self.vimiv["window"].is_fullscreen)
# Unfullscreen
self.vimiv["window"].toggle_fullscreen()
refresh_gui(0.05)
# self.assertFalse(self.vimiv["window"].is_fullscreen)
self.vimiv["window"].fullscreen()
def test_scroll(self):
"""Scroll image or thumbnail."""
# Error message
self.vimiv["window"].scroll("m")
self.assertEqual(self.vimiv["statusbar"].left_label.get_text(),
"ERROR: Invalid scroll direction m")
if __name__ == '__main__':
main()
<commit_msg>Add test for checking window resizing
Test if the variable vimiv["window"].winsize is adjusted when resizing the
window. This is only guaranteed to work in Xvfb as e.g. tiling window managers
do not react to the resize from Gtk.<commit_after>#!/usr/bin/env python
# encoding: utf-8
"""Tests window.py for vimiv's test suite."""
import os
from unittest import main, skipUnless
from vimiv_testcase import VimivTestCase, refresh_gui
class WindowTest(VimivTestCase):
"""Window Tests."""
@classmethod
def setUpClass(cls):
cls.init_test(cls, ["vimiv/testimages/"])
def test_fullscreen(self):
"""Toggle fullscreen."""
# Start without fullscreen
self.assertFalse(self.vimiv["window"].is_fullscreen)
# Fullscreen
self.vimiv["window"].toggle_fullscreen()
refresh_gui(0.05)
# Still not reliable
# self.assertTrue(self.vimiv["window"].is_fullscreen)
# Unfullscreen
self.vimiv["window"].toggle_fullscreen()
refresh_gui(0.05)
# self.assertFalse(self.vimiv["window"].is_fullscreen)
self.vimiv["window"].fullscreen()
def test_scroll(self):
"""Scroll image or thumbnail."""
# Error message
self.vimiv["window"].scroll("m")
self.assertEqual(self.vimiv["statusbar"].left_label.get_text(),
"ERROR: Invalid scroll direction m")
@skipUnless(os.environ["DISPLAY"] == ":42", "Must run in Xvfb")
def test_check_resize(self):
"""Resize window and check winsize."""
self.assertEqual(self.vimiv["window"].winsize, (800, 600))
self.vimiv["window"].resize(400, 300)
refresh_gui()
self.assertEqual(self.vimiv["window"].winsize, (400, 300))
if __name__ == '__main__':
main()
|
7917716ebd11770c5d4d0634b39e32e4f577ab71 | tests/test_urls.py | tests/test_urls.py | from unittest import TestCase
class TestURLs(TestCase):
pass
| from unittest import TestCase
from django.contrib.auth import views
from django.core.urlresolvers import resolve, reverse
class URLsMixin(object):
"""
A TestCase Mixin with a check_url helper method for testing urls.
Pirated with slight modifications from incuna_test_utils
https://github.com/incuna/incuna-test-utils/blob/master/incuna_test_utils/testcases/urls.py
"""
def check_url(self, view_method, expected_url, url_name,
url_args=None, url_kwargs=None):
"""
Assert a view's url is correctly configured
Check the url_name reverses to give a correctly formated expected_url.
Check the expected_url resolves to the correct view.
"""
reversed_url = reverse(url_name, args=url_args, kwargs=url_kwargs)
self.assertEqual(reversed_url, expected_url)
# Look for a method rather than a class here
# (just because of what we're testing)
resolved_view_method = resolve(expected_url).func
self.assertEqual(resolved_view_method, view_method)
class TestURLs(URLsMixin, TestCase):
def test_login(self):
self.check_url(
views.login,
'/login/',
'login',
)
def test_logout(self):
self.check_url(
views.logout,
'/logout/',
'logout',
)
def test_password_change(self):
self.check_url(
views.password_change,
'/password/change/',
'password_change',
)
def test_password_change_done(self):
self.check_url(
views.password_change_done,
'/password/change/done/',
'password_change_done',
)
def test_password_reset(self):
self.check_url(
views.password_reset,
'/password/reset/',
'password_reset',
)
def test_password_reset_done(self):
self.check_url(
views.password_reset_done,
'/password/reset/done/',
'password_reset_done',
)
def test_password_reset_complete(self):
self.check_url(
views.password_reset_complete,
'/password/reset/complete/',
'password_reset_complete',
)
| Add lots of URL tests. | Add lots of URL tests.
* The URLsMixin from incuna_test_utils/testcases/urls.py
isn't quite doing what we want here, so rip it off and
make a small modification (resolve(...).func.cls ->
resolve(...).func).
* Add lots of tests for the django.contrib.auth views
that we're using (the others are more complex).
| Python | bsd-2-clause | incuna/incuna-auth,ghickman/incuna-auth,ghickman/incuna-auth,incuna/incuna-auth | from unittest import TestCase
class TestURLs(TestCase):
pass
Add lots of URL tests.
* The URLsMixin from incuna_test_utils/testcases/urls.py
isn't quite doing what we want here, so rip it off and
make a small modification (resolve(...).func.cls ->
resolve(...).func).
* Add lots of tests for the django.contrib.auth views
that we're using (the others are more complex). | from unittest import TestCase
from django.contrib.auth import views
from django.core.urlresolvers import resolve, reverse
class URLsMixin(object):
"""
A TestCase Mixin with a check_url helper method for testing urls.
Pirated with slight modifications from incuna_test_utils
https://github.com/incuna/incuna-test-utils/blob/master/incuna_test_utils/testcases/urls.py
"""
def check_url(self, view_method, expected_url, url_name,
url_args=None, url_kwargs=None):
"""
Assert a view's url is correctly configured
Check the url_name reverses to give a correctly formated expected_url.
Check the expected_url resolves to the correct view.
"""
reversed_url = reverse(url_name, args=url_args, kwargs=url_kwargs)
self.assertEqual(reversed_url, expected_url)
# Look for a method rather than a class here
# (just because of what we're testing)
resolved_view_method = resolve(expected_url).func
self.assertEqual(resolved_view_method, view_method)
class TestURLs(URLsMixin, TestCase):
def test_login(self):
self.check_url(
views.login,
'/login/',
'login',
)
def test_logout(self):
self.check_url(
views.logout,
'/logout/',
'logout',
)
def test_password_change(self):
self.check_url(
views.password_change,
'/password/change/',
'password_change',
)
def test_password_change_done(self):
self.check_url(
views.password_change_done,
'/password/change/done/',
'password_change_done',
)
def test_password_reset(self):
self.check_url(
views.password_reset,
'/password/reset/',
'password_reset',
)
def test_password_reset_done(self):
self.check_url(
views.password_reset_done,
'/password/reset/done/',
'password_reset_done',
)
def test_password_reset_complete(self):
self.check_url(
views.password_reset_complete,
'/password/reset/complete/',
'password_reset_complete',
)
| <commit_before>from unittest import TestCase
class TestURLs(TestCase):
pass
<commit_msg>Add lots of URL tests.
* The URLsMixin from incuna_test_utils/testcases/urls.py
isn't quite doing what we want here, so rip it off and
make a small modification (resolve(...).func.cls ->
resolve(...).func).
* Add lots of tests for the django.contrib.auth views
that we're using (the others are more complex).<commit_after> | from unittest import TestCase
from django.contrib.auth import views
from django.core.urlresolvers import resolve, reverse
class URLsMixin(object):
"""
A TestCase Mixin with a check_url helper method for testing urls.
Pirated with slight modifications from incuna_test_utils
https://github.com/incuna/incuna-test-utils/blob/master/incuna_test_utils/testcases/urls.py
"""
def check_url(self, view_method, expected_url, url_name,
url_args=None, url_kwargs=None):
"""
Assert a view's url is correctly configured
Check the url_name reverses to give a correctly formated expected_url.
Check the expected_url resolves to the correct view.
"""
reversed_url = reverse(url_name, args=url_args, kwargs=url_kwargs)
self.assertEqual(reversed_url, expected_url)
# Look for a method rather than a class here
# (just because of what we're testing)
resolved_view_method = resolve(expected_url).func
self.assertEqual(resolved_view_method, view_method)
class TestURLs(URLsMixin, TestCase):
def test_login(self):
self.check_url(
views.login,
'/login/',
'login',
)
def test_logout(self):
self.check_url(
views.logout,
'/logout/',
'logout',
)
def test_password_change(self):
self.check_url(
views.password_change,
'/password/change/',
'password_change',
)
def test_password_change_done(self):
self.check_url(
views.password_change_done,
'/password/change/done/',
'password_change_done',
)
def test_password_reset(self):
self.check_url(
views.password_reset,
'/password/reset/',
'password_reset',
)
def test_password_reset_done(self):
self.check_url(
views.password_reset_done,
'/password/reset/done/',
'password_reset_done',
)
def test_password_reset_complete(self):
self.check_url(
views.password_reset_complete,
'/password/reset/complete/',
'password_reset_complete',
)
| from unittest import TestCase
class TestURLs(TestCase):
pass
Add lots of URL tests.
* The URLsMixin from incuna_test_utils/testcases/urls.py
isn't quite doing what we want here, so rip it off and
make a small modification (resolve(...).func.cls ->
resolve(...).func).
* Add lots of tests for the django.contrib.auth views
that we're using (the others are more complex).from unittest import TestCase
from django.contrib.auth import views
from django.core.urlresolvers import resolve, reverse
class URLsMixin(object):
"""
A TestCase Mixin with a check_url helper method for testing urls.
Pirated with slight modifications from incuna_test_utils
https://github.com/incuna/incuna-test-utils/blob/master/incuna_test_utils/testcases/urls.py
"""
def check_url(self, view_method, expected_url, url_name,
url_args=None, url_kwargs=None):
"""
Assert a view's url is correctly configured
Check the url_name reverses to give a correctly formated expected_url.
Check the expected_url resolves to the correct view.
"""
reversed_url = reverse(url_name, args=url_args, kwargs=url_kwargs)
self.assertEqual(reversed_url, expected_url)
# Look for a method rather than a class here
# (just because of what we're testing)
resolved_view_method = resolve(expected_url).func
self.assertEqual(resolved_view_method, view_method)
class TestURLs(URLsMixin, TestCase):
def test_login(self):
self.check_url(
views.login,
'/login/',
'login',
)
def test_logout(self):
self.check_url(
views.logout,
'/logout/',
'logout',
)
def test_password_change(self):
self.check_url(
views.password_change,
'/password/change/',
'password_change',
)
def test_password_change_done(self):
self.check_url(
views.password_change_done,
'/password/change/done/',
'password_change_done',
)
def test_password_reset(self):
self.check_url(
views.password_reset,
'/password/reset/',
'password_reset',
)
def test_password_reset_done(self):
self.check_url(
views.password_reset_done,
'/password/reset/done/',
'password_reset_done',
)
def test_password_reset_complete(self):
self.check_url(
views.password_reset_complete,
'/password/reset/complete/',
'password_reset_complete',
)
| <commit_before>from unittest import TestCase
class TestURLs(TestCase):
pass
<commit_msg>Add lots of URL tests.
* The URLsMixin from incuna_test_utils/testcases/urls.py
isn't quite doing what we want here, so rip it off and
make a small modification (resolve(...).func.cls ->
resolve(...).func).
* Add lots of tests for the django.contrib.auth views
that we're using (the others are more complex).<commit_after>from unittest import TestCase
from django.contrib.auth import views
from django.core.urlresolvers import resolve, reverse
class URLsMixin(object):
"""
A TestCase Mixin with a check_url helper method for testing urls.
Pirated with slight modifications from incuna_test_utils
https://github.com/incuna/incuna-test-utils/blob/master/incuna_test_utils/testcases/urls.py
"""
def check_url(self, view_method, expected_url, url_name,
url_args=None, url_kwargs=None):
"""
Assert a view's url is correctly configured
Check the url_name reverses to give a correctly formated expected_url.
Check the expected_url resolves to the correct view.
"""
reversed_url = reverse(url_name, args=url_args, kwargs=url_kwargs)
self.assertEqual(reversed_url, expected_url)
# Look for a method rather than a class here
# (just because of what we're testing)
resolved_view_method = resolve(expected_url).func
self.assertEqual(resolved_view_method, view_method)
class TestURLs(URLsMixin, TestCase):
def test_login(self):
self.check_url(
views.login,
'/login/',
'login',
)
def test_logout(self):
self.check_url(
views.logout,
'/logout/',
'logout',
)
def test_password_change(self):
self.check_url(
views.password_change,
'/password/change/',
'password_change',
)
def test_password_change_done(self):
self.check_url(
views.password_change_done,
'/password/change/done/',
'password_change_done',
)
def test_password_reset(self):
self.check_url(
views.password_reset,
'/password/reset/',
'password_reset',
)
def test_password_reset_done(self):
self.check_url(
views.password_reset_done,
'/password/reset/done/',
'password_reset_done',
)
def test_password_reset_complete(self):
self.check_url(
views.password_reset_complete,
'/password/reset/complete/',
'password_reset_complete',
)
|
322997e229457bf43ee2281993ccdc30c8455244 | tests/test_util.py | tests/test_util.py | from archivebox import util
def test_download_url_downloads_content():
text = util.download_url("https://example.com")
assert "Example Domain" in text | from archivebox import util
def test_download_url_downloads_content():
text = util.download_url("http://localhost:8080/static/example.com.html")
assert "Example Domain" in text | Refactor util tests to use local webserver | test: Refactor util tests to use local webserver
| Python | mit | pirate/bookmark-archiver,pirate/bookmark-archiver,pirate/bookmark-archiver | from archivebox import util
def test_download_url_downloads_content():
text = util.download_url("https://example.com")
assert "Example Domain" in texttest: Refactor util tests to use local webserver | from archivebox import util
def test_download_url_downloads_content():
text = util.download_url("http://localhost:8080/static/example.com.html")
assert "Example Domain" in text | <commit_before>from archivebox import util
def test_download_url_downloads_content():
text = util.download_url("https://example.com")
assert "Example Domain" in text<commit_msg>test: Refactor util tests to use local webserver<commit_after> | from archivebox import util
def test_download_url_downloads_content():
text = util.download_url("http://localhost:8080/static/example.com.html")
assert "Example Domain" in text | from archivebox import util
def test_download_url_downloads_content():
text = util.download_url("https://example.com")
assert "Example Domain" in texttest: Refactor util tests to use local webserverfrom archivebox import util
def test_download_url_downloads_content():
text = util.download_url("http://localhost:8080/static/example.com.html")
assert "Example Domain" in text | <commit_before>from archivebox import util
def test_download_url_downloads_content():
text = util.download_url("https://example.com")
assert "Example Domain" in text<commit_msg>test: Refactor util tests to use local webserver<commit_after>from archivebox import util
def test_download_url_downloads_content():
text = util.download_url("http://localhost:8080/static/example.com.html")
assert "Example Domain" in text |
10554ed0c44f819985f9f6d1c97a265d281541a2 | test/test_types.py | test/test_types.py | """ Tests for the Types module """
import unittest
# pylint: disable=import-error
from res import types
class TestTypes(unittest.TestCase):
""" Tests for the Types module """
def test_getPieceAbbreviation_empty(self):
"Correctly convert a type to a character for display"
self.assertEqual('.', types.getPieceAbbreviation(types.EMPTY))
def test_getPieceAbbreviation_goose(self):
"Correctly convert a type to a character for display"
self.assertEqual('G', types.getPieceAbbreviation(types.GOOSE))
def test_getPieceAbbreviation_fox(self):
"Correctly convert a type to a character for display"
self.assertEqual('F', types.getPieceAbbreviation(types.FOX))
def test_getPieceAbbreviation_supergoose(self):
"Correctly convert a type to a character for display"
self.assertEqual('S', types.getPieceAbbreviation(types.SUPERGOOSE))
def test_getPieceAbbreviation_outside(self):
"Correctly convert a type to a character for display"
self.assertEqual(None, types.getPieceAbbreviation(types.OUTSIDE))
def test_getPieceAbbreviation_unknown(self):
"Correctly convert a type to a character for display"
self.assertEqual(None, types.getPieceAbbreviation(4567)) | """ Tests for the Types module """
import unittest
# pylint: disable=import-error
from res import types
class TestTypes(unittest.TestCase):
""" Tests for the Types module """
def test_getPieceAbbreviation_empty(self):
"Correctly convert a type to a character for display"
self.assertEqual('.', types.getPieceAbbreviation(types.EMPTY))
def test_getPieceAbbreviation_goose(self):
"Correctly convert a type to a character for display"
self.assertEqual('G', types.getPieceAbbreviation(types.GOOSE))
def test_getPieceAbbreviation_fox(self):
"Correctly convert a type to a character for display"
self.assertEqual('F', types.getPieceAbbreviation(types.FOX))
def test_getPieceAbbreviation_supergoose(self):
"Correctly convert a type to a character for display"
self.assertEqual('S', types.getPieceAbbreviation(types.SUPERGOOSE))
def test_getPieceAbbreviation_outside(self):
"Correctly convert a type to a character for display"
self.assertEqual(None, types.getPieceAbbreviation(types.OUTSIDE))
def test_getPieceAbbreviation_unknown(self):
"Correctly convert a type to a character for display"
self.assertRaises(ValueError,
types.getPieceAbbreviation,
'abcd')
| Update redundant test to check error handling | Update redundant test to check error handling
| Python | mit | blairck/jaeger | """ Tests for the Types module """
import unittest
# pylint: disable=import-error
from res import types
class TestTypes(unittest.TestCase):
""" Tests for the Types module """
def test_getPieceAbbreviation_empty(self):
"Correctly convert a type to a character for display"
self.assertEqual('.', types.getPieceAbbreviation(types.EMPTY))
def test_getPieceAbbreviation_goose(self):
"Correctly convert a type to a character for display"
self.assertEqual('G', types.getPieceAbbreviation(types.GOOSE))
def test_getPieceAbbreviation_fox(self):
"Correctly convert a type to a character for display"
self.assertEqual('F', types.getPieceAbbreviation(types.FOX))
def test_getPieceAbbreviation_supergoose(self):
"Correctly convert a type to a character for display"
self.assertEqual('S', types.getPieceAbbreviation(types.SUPERGOOSE))
def test_getPieceAbbreviation_outside(self):
"Correctly convert a type to a character for display"
self.assertEqual(None, types.getPieceAbbreviation(types.OUTSIDE))
def test_getPieceAbbreviation_unknown(self):
"Correctly convert a type to a character for display"
self.assertEqual(None, types.getPieceAbbreviation(4567))Update redundant test to check error handling | """ Tests for the Types module """
import unittest
# pylint: disable=import-error
from res import types
class TestTypes(unittest.TestCase):
""" Tests for the Types module """
def test_getPieceAbbreviation_empty(self):
"Correctly convert a type to a character for display"
self.assertEqual('.', types.getPieceAbbreviation(types.EMPTY))
def test_getPieceAbbreviation_goose(self):
"Correctly convert a type to a character for display"
self.assertEqual('G', types.getPieceAbbreviation(types.GOOSE))
def test_getPieceAbbreviation_fox(self):
"Correctly convert a type to a character for display"
self.assertEqual('F', types.getPieceAbbreviation(types.FOX))
def test_getPieceAbbreviation_supergoose(self):
"Correctly convert a type to a character for display"
self.assertEqual('S', types.getPieceAbbreviation(types.SUPERGOOSE))
def test_getPieceAbbreviation_outside(self):
"Correctly convert a type to a character for display"
self.assertEqual(None, types.getPieceAbbreviation(types.OUTSIDE))
def test_getPieceAbbreviation_unknown(self):
"Correctly convert a type to a character for display"
self.assertRaises(ValueError,
types.getPieceAbbreviation,
'abcd')
| <commit_before>""" Tests for the Types module """
import unittest
# pylint: disable=import-error
from res import types
class TestTypes(unittest.TestCase):
""" Tests for the Types module """
def test_getPieceAbbreviation_empty(self):
"Correctly convert a type to a character for display"
self.assertEqual('.', types.getPieceAbbreviation(types.EMPTY))
def test_getPieceAbbreviation_goose(self):
"Correctly convert a type to a character for display"
self.assertEqual('G', types.getPieceAbbreviation(types.GOOSE))
def test_getPieceAbbreviation_fox(self):
"Correctly convert a type to a character for display"
self.assertEqual('F', types.getPieceAbbreviation(types.FOX))
def test_getPieceAbbreviation_supergoose(self):
"Correctly convert a type to a character for display"
self.assertEqual('S', types.getPieceAbbreviation(types.SUPERGOOSE))
def test_getPieceAbbreviation_outside(self):
"Correctly convert a type to a character for display"
self.assertEqual(None, types.getPieceAbbreviation(types.OUTSIDE))
def test_getPieceAbbreviation_unknown(self):
"Correctly convert a type to a character for display"
self.assertEqual(None, types.getPieceAbbreviation(4567))<commit_msg>Update redundant test to check error handling<commit_after> | """ Tests for the Types module """
import unittest
# pylint: disable=import-error
from res import types
class TestTypes(unittest.TestCase):
""" Tests for the Types module """
def test_getPieceAbbreviation_empty(self):
"Correctly convert a type to a character for display"
self.assertEqual('.', types.getPieceAbbreviation(types.EMPTY))
def test_getPieceAbbreviation_goose(self):
"Correctly convert a type to a character for display"
self.assertEqual('G', types.getPieceAbbreviation(types.GOOSE))
def test_getPieceAbbreviation_fox(self):
"Correctly convert a type to a character for display"
self.assertEqual('F', types.getPieceAbbreviation(types.FOX))
def test_getPieceAbbreviation_supergoose(self):
"Correctly convert a type to a character for display"
self.assertEqual('S', types.getPieceAbbreviation(types.SUPERGOOSE))
def test_getPieceAbbreviation_outside(self):
"Correctly convert a type to a character for display"
self.assertEqual(None, types.getPieceAbbreviation(types.OUTSIDE))
def test_getPieceAbbreviation_unknown(self):
"Correctly convert a type to a character for display"
self.assertRaises(ValueError,
types.getPieceAbbreviation,
'abcd')
| """ Tests for the Types module """
import unittest
# pylint: disable=import-error
from res import types
class TestTypes(unittest.TestCase):
""" Tests for the Types module """
def test_getPieceAbbreviation_empty(self):
"Correctly convert a type to a character for display"
self.assertEqual('.', types.getPieceAbbreviation(types.EMPTY))
def test_getPieceAbbreviation_goose(self):
"Correctly convert a type to a character for display"
self.assertEqual('G', types.getPieceAbbreviation(types.GOOSE))
def test_getPieceAbbreviation_fox(self):
"Correctly convert a type to a character for display"
self.assertEqual('F', types.getPieceAbbreviation(types.FOX))
def test_getPieceAbbreviation_supergoose(self):
"Correctly convert a type to a character for display"
self.assertEqual('S', types.getPieceAbbreviation(types.SUPERGOOSE))
def test_getPieceAbbreviation_outside(self):
"Correctly convert a type to a character for display"
self.assertEqual(None, types.getPieceAbbreviation(types.OUTSIDE))
def test_getPieceAbbreviation_unknown(self):
"Correctly convert a type to a character for display"
self.assertEqual(None, types.getPieceAbbreviation(4567))Update redundant test to check error handling""" Tests for the Types module """
import unittest
# pylint: disable=import-error
from res import types
class TestTypes(unittest.TestCase):
""" Tests for the Types module """
def test_getPieceAbbreviation_empty(self):
"Correctly convert a type to a character for display"
self.assertEqual('.', types.getPieceAbbreviation(types.EMPTY))
def test_getPieceAbbreviation_goose(self):
"Correctly convert a type to a character for display"
self.assertEqual('G', types.getPieceAbbreviation(types.GOOSE))
def test_getPieceAbbreviation_fox(self):
"Correctly convert a type to a character for display"
self.assertEqual('F', types.getPieceAbbreviation(types.FOX))
def test_getPieceAbbreviation_supergoose(self):
"Correctly convert a type to a character for display"
self.assertEqual('S', types.getPieceAbbreviation(types.SUPERGOOSE))
def test_getPieceAbbreviation_outside(self):
"Correctly convert a type to a character for display"
self.assertEqual(None, types.getPieceAbbreviation(types.OUTSIDE))
def test_getPieceAbbreviation_unknown(self):
"Correctly convert a type to a character for display"
self.assertRaises(ValueError,
types.getPieceAbbreviation,
'abcd')
| <commit_before>""" Tests for the Types module """
import unittest
# pylint: disable=import-error
from res import types
class TestTypes(unittest.TestCase):
""" Tests for the Types module """
def test_getPieceAbbreviation_empty(self):
"Correctly convert a type to a character for display"
self.assertEqual('.', types.getPieceAbbreviation(types.EMPTY))
def test_getPieceAbbreviation_goose(self):
"Correctly convert a type to a character for display"
self.assertEqual('G', types.getPieceAbbreviation(types.GOOSE))
def test_getPieceAbbreviation_fox(self):
"Correctly convert a type to a character for display"
self.assertEqual('F', types.getPieceAbbreviation(types.FOX))
def test_getPieceAbbreviation_supergoose(self):
"Correctly convert a type to a character for display"
self.assertEqual('S', types.getPieceAbbreviation(types.SUPERGOOSE))
def test_getPieceAbbreviation_outside(self):
"Correctly convert a type to a character for display"
self.assertEqual(None, types.getPieceAbbreviation(types.OUTSIDE))
def test_getPieceAbbreviation_unknown(self):
"Correctly convert a type to a character for display"
self.assertEqual(None, types.getPieceAbbreviation(4567))<commit_msg>Update redundant test to check error handling<commit_after>""" Tests for the Types module """
import unittest
# pylint: disable=import-error
from res import types
class TestTypes(unittest.TestCase):
""" Tests for the Types module """
def test_getPieceAbbreviation_empty(self):
"Correctly convert a type to a character for display"
self.assertEqual('.', types.getPieceAbbreviation(types.EMPTY))
def test_getPieceAbbreviation_goose(self):
"Correctly convert a type to a character for display"
self.assertEqual('G', types.getPieceAbbreviation(types.GOOSE))
def test_getPieceAbbreviation_fox(self):
"Correctly convert a type to a character for display"
self.assertEqual('F', types.getPieceAbbreviation(types.FOX))
def test_getPieceAbbreviation_supergoose(self):
"Correctly convert a type to a character for display"
self.assertEqual('S', types.getPieceAbbreviation(types.SUPERGOOSE))
def test_getPieceAbbreviation_outside(self):
"Correctly convert a type to a character for display"
self.assertEqual(None, types.getPieceAbbreviation(types.OUTSIDE))
def test_getPieceAbbreviation_unknown(self):
"Correctly convert a type to a character for display"
self.assertRaises(ValueError,
types.getPieceAbbreviation,
'abcd')
|
d4f63a22df8bb7a866737150064d92ce7227c875 | pyshould/dsl.py | pyshould/dsl.py | """
Define the names making up the domain specific language
"""
from .expectation import (
Expectation, ExpectationNot,
ExpectationAll, ExpectationAny,
ExpectationNone, OPERATOR_OR
)
# Create instances to be used with the overloaded | operator
should = Expectation(deferred=True)
should_not = ExpectationNot(deferred=True)
should_all = ExpectationAll(deferred=True)
should_any = ExpectationAny(deferred=True)
should_none = ExpectationNone(deferred=True)
should_either = Expectation(deferred=True, def_op=OPERATOR_OR)
def it(value):
""" Wraps a value in an exepctation """
return Expectation(value)
def any_of(value):
""" At least one of the items in value should match """
return ExpectationAny(value)
def all_of(value):
""" All the items in value should match """
return ExpectationAll(value)
def none_of(value):
""" None of the items in value should match """
return ExpectationNone(value)
| """
Define the names making up the domain specific language
"""
from .expectation import (
Expectation, ExpectationNot,
ExpectationAll, ExpectationAny,
ExpectationNone, OPERATOR_OR
)
# Create instances to be used with the overloaded | operator
should = Expectation(deferred=True)
should_not = ExpectationNot(deferred=True)
should_all = ExpectationAll(deferred=True)
should_any = ExpectationAny(deferred=True)
should_none = ExpectationNone(deferred=True)
should_either = Expectation(deferred=True, def_op=OPERATOR_OR)
def it(value):
""" Wraps a value in an exepctation """
return Expectation(value)
def any_of(value, *args):
""" At least one of the items in value should match """
if len(args):
value = (value,) + args
return ExpectationAny(value)
def all_of(value, *args):
""" All the items in value should match """
if len(args):
value = (value,) + args
return ExpectationAll(value)
def none_of(value, *args):
""" None of the items in value should match """
if len(args):
value = (value,) + args
return ExpectationNone(value)
| Allow multiple arguments for quantifiers | Allow multiple arguments for quantifiers
| Python | mit | drslump/pyshould | """
Define the names making up the domain specific language
"""
from .expectation import (
Expectation, ExpectationNot,
ExpectationAll, ExpectationAny,
ExpectationNone, OPERATOR_OR
)
# Create instances to be used with the overloaded | operator
should = Expectation(deferred=True)
should_not = ExpectationNot(deferred=True)
should_all = ExpectationAll(deferred=True)
should_any = ExpectationAny(deferred=True)
should_none = ExpectationNone(deferred=True)
should_either = Expectation(deferred=True, def_op=OPERATOR_OR)
def it(value):
""" Wraps a value in an exepctation """
return Expectation(value)
def any_of(value):
""" At least one of the items in value should match """
return ExpectationAny(value)
def all_of(value):
""" All the items in value should match """
return ExpectationAll(value)
def none_of(value):
""" None of the items in value should match """
return ExpectationNone(value)
Allow multiple arguments for quantifiers | """
Define the names making up the domain specific language
"""
from .expectation import (
Expectation, ExpectationNot,
ExpectationAll, ExpectationAny,
ExpectationNone, OPERATOR_OR
)
# Create instances to be used with the overloaded | operator
should = Expectation(deferred=True)
should_not = ExpectationNot(deferred=True)
should_all = ExpectationAll(deferred=True)
should_any = ExpectationAny(deferred=True)
should_none = ExpectationNone(deferred=True)
should_either = Expectation(deferred=True, def_op=OPERATOR_OR)
def it(value):
""" Wraps a value in an exepctation """
return Expectation(value)
def any_of(value, *args):
""" At least one of the items in value should match """
if len(args):
value = (value,) + args
return ExpectationAny(value)
def all_of(value, *args):
""" All the items in value should match """
if len(args):
value = (value,) + args
return ExpectationAll(value)
def none_of(value, *args):
""" None of the items in value should match """
if len(args):
value = (value,) + args
return ExpectationNone(value)
| <commit_before>"""
Define the names making up the domain specific language
"""
from .expectation import (
Expectation, ExpectationNot,
ExpectationAll, ExpectationAny,
ExpectationNone, OPERATOR_OR
)
# Create instances to be used with the overloaded | operator
should = Expectation(deferred=True)
should_not = ExpectationNot(deferred=True)
should_all = ExpectationAll(deferred=True)
should_any = ExpectationAny(deferred=True)
should_none = ExpectationNone(deferred=True)
should_either = Expectation(deferred=True, def_op=OPERATOR_OR)
def it(value):
""" Wraps a value in an exepctation """
return Expectation(value)
def any_of(value):
""" At least one of the items in value should match """
return ExpectationAny(value)
def all_of(value):
""" All the items in value should match """
return ExpectationAll(value)
def none_of(value):
""" None of the items in value should match """
return ExpectationNone(value)
<commit_msg>Allow multiple arguments for quantifiers<commit_after> | """
Define the names making up the domain specific language
"""
from .expectation import (
Expectation, ExpectationNot,
ExpectationAll, ExpectationAny,
ExpectationNone, OPERATOR_OR
)
# Create instances to be used with the overloaded | operator
should = Expectation(deferred=True)
should_not = ExpectationNot(deferred=True)
should_all = ExpectationAll(deferred=True)
should_any = ExpectationAny(deferred=True)
should_none = ExpectationNone(deferred=True)
should_either = Expectation(deferred=True, def_op=OPERATOR_OR)
def it(value):
""" Wraps a value in an exepctation """
return Expectation(value)
def any_of(value, *args):
""" At least one of the items in value should match """
if len(args):
value = (value,) + args
return ExpectationAny(value)
def all_of(value, *args):
""" All the items in value should match """
if len(args):
value = (value,) + args
return ExpectationAll(value)
def none_of(value, *args):
""" None of the items in value should match """
if len(args):
value = (value,) + args
return ExpectationNone(value)
| """
Define the names making up the domain specific language
"""
from .expectation import (
Expectation, ExpectationNot,
ExpectationAll, ExpectationAny,
ExpectationNone, OPERATOR_OR
)
# Create instances to be used with the overloaded | operator
should = Expectation(deferred=True)
should_not = ExpectationNot(deferred=True)
should_all = ExpectationAll(deferred=True)
should_any = ExpectationAny(deferred=True)
should_none = ExpectationNone(deferred=True)
should_either = Expectation(deferred=True, def_op=OPERATOR_OR)
def it(value):
""" Wraps a value in an exepctation """
return Expectation(value)
def any_of(value):
""" At least one of the items in value should match """
return ExpectationAny(value)
def all_of(value):
""" All the items in value should match """
return ExpectationAll(value)
def none_of(value):
""" None of the items in value should match """
return ExpectationNone(value)
Allow multiple arguments for quantifiers"""
Define the names making up the domain specific language
"""
from .expectation import (
Expectation, ExpectationNot,
ExpectationAll, ExpectationAny,
ExpectationNone, OPERATOR_OR
)
# Create instances to be used with the overloaded | operator
should = Expectation(deferred=True)
should_not = ExpectationNot(deferred=True)
should_all = ExpectationAll(deferred=True)
should_any = ExpectationAny(deferred=True)
should_none = ExpectationNone(deferred=True)
should_either = Expectation(deferred=True, def_op=OPERATOR_OR)
def it(value):
""" Wraps a value in an exepctation """
return Expectation(value)
def any_of(value, *args):
""" At least one of the items in value should match """
if len(args):
value = (value,) + args
return ExpectationAny(value)
def all_of(value, *args):
""" All the items in value should match """
if len(args):
value = (value,) + args
return ExpectationAll(value)
def none_of(value, *args):
""" None of the items in value should match """
if len(args):
value = (value,) + args
return ExpectationNone(value)
| <commit_before>"""
Define the names making up the domain specific language
"""
from .expectation import (
Expectation, ExpectationNot,
ExpectationAll, ExpectationAny,
ExpectationNone, OPERATOR_OR
)
# Create instances to be used with the overloaded | operator
should = Expectation(deferred=True)
should_not = ExpectationNot(deferred=True)
should_all = ExpectationAll(deferred=True)
should_any = ExpectationAny(deferred=True)
should_none = ExpectationNone(deferred=True)
should_either = Expectation(deferred=True, def_op=OPERATOR_OR)
def it(value):
""" Wraps a value in an exepctation """
return Expectation(value)
def any_of(value):
""" At least one of the items in value should match """
return ExpectationAny(value)
def all_of(value):
""" All the items in value should match """
return ExpectationAll(value)
def none_of(value):
""" None of the items in value should match """
return ExpectationNone(value)
<commit_msg>Allow multiple arguments for quantifiers<commit_after>"""
Define the names making up the domain specific language
"""
from .expectation import (
Expectation, ExpectationNot,
ExpectationAll, ExpectationAny,
ExpectationNone, OPERATOR_OR
)
# Create instances to be used with the overloaded | operator
should = Expectation(deferred=True)
should_not = ExpectationNot(deferred=True)
should_all = ExpectationAll(deferred=True)
should_any = ExpectationAny(deferred=True)
should_none = ExpectationNone(deferred=True)
should_either = Expectation(deferred=True, def_op=OPERATOR_OR)
def it(value):
""" Wraps a value in an exepctation """
return Expectation(value)
def any_of(value, *args):
""" At least one of the items in value should match """
if len(args):
value = (value,) + args
return ExpectationAny(value)
def all_of(value, *args):
""" All the items in value should match """
if len(args):
value = (value,) + args
return ExpectationAll(value)
def none_of(value, *args):
""" None of the items in value should match """
if len(args):
value = (value,) + args
return ExpectationNone(value)
|
6d1b20bd047a47c46e3aa33a920e71f890f2b1fa | run.py | run.py | __author__ = 'matt'
import datetime
import blockbuster
blockbuster.app.debug = blockbuster.config.debug_mode
blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")
blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@ BlockBuster " + blockbuster.config.app_version + " "
"@@@@@@@@@@@@@@@@@@")
blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")
blockbuster.bb_logging.logger.info("=== Application startup - " + str(datetime.datetime.now()) + " ====")
blockbuster.bb_logging.logger.info(
'================Time restriction disabled================') \
if not blockbuster.config.timerestriction else blockbuster.bb_logging.logger.info(
'================Time restriction enabled================')
blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")
if blockbuster.config.debug_mode:
blockbuster.bb_logging.logger.info("========= APPLICATION IS RUNNING IN DEBUG MODE ==========")
# This section only applies when you are running run.py directly
if __name__ == '__main__':
blockbuster.bb_logging.logger.info("Running http on port 5000")
blockbuster.app.run(host='0.0.0.0', debug=True) | __author__ = 'matt'
import datetime
import blockbuster
blockbuster.app.debug = blockbuster.config.debug_mode
blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")
blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@ BlockBuster " + blockbuster.__version__ + " "
"@@@@@@@@@@@@@@@@@@")
blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")
blockbuster.bb_logging.logger.info("=== Application startup - " + str(datetime.datetime.now()) + " ====")
blockbuster.bb_logging.logger.info(
'================Time restriction disabled================') \
if not blockbuster.config.timerestriction else blockbuster.bb_logging.logger.info(
'================Time restriction enabled================')
blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")
if blockbuster.config.debug_mode:
blockbuster.bb_logging.logger.info("========= APPLICATION IS RUNNING IN DEBUG MODE ==========")
# This section only applies when you are running run.py directly
if __name__ == '__main__':
blockbuster.bb_logging.logger.info("Running http on port 5000")
blockbuster.app.run(host='0.0.0.0', debug=True) | Update reference to application version | Update reference to application version
| Python | mit | mattstibbs/blockbuster-server,mattstibbs/blockbuster-server | __author__ = 'matt'
import datetime
import blockbuster
blockbuster.app.debug = blockbuster.config.debug_mode
blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")
blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@ BlockBuster " + blockbuster.config.app_version + " "
"@@@@@@@@@@@@@@@@@@")
blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")
blockbuster.bb_logging.logger.info("=== Application startup - " + str(datetime.datetime.now()) + " ====")
blockbuster.bb_logging.logger.info(
'================Time restriction disabled================') \
if not blockbuster.config.timerestriction else blockbuster.bb_logging.logger.info(
'================Time restriction enabled================')
blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")
if blockbuster.config.debug_mode:
blockbuster.bb_logging.logger.info("========= APPLICATION IS RUNNING IN DEBUG MODE ==========")
# This section only applies when you are running run.py directly
if __name__ == '__main__':
blockbuster.bb_logging.logger.info("Running http on port 5000")
blockbuster.app.run(host='0.0.0.0', debug=True)Update reference to application version | __author__ = 'matt'
import datetime
import blockbuster
blockbuster.app.debug = blockbuster.config.debug_mode
blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")
blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@ BlockBuster " + blockbuster.__version__ + " "
"@@@@@@@@@@@@@@@@@@")
blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")
blockbuster.bb_logging.logger.info("=== Application startup - " + str(datetime.datetime.now()) + " ====")
blockbuster.bb_logging.logger.info(
'================Time restriction disabled================') \
if not blockbuster.config.timerestriction else blockbuster.bb_logging.logger.info(
'================Time restriction enabled================')
blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")
if blockbuster.config.debug_mode:
blockbuster.bb_logging.logger.info("========= APPLICATION IS RUNNING IN DEBUG MODE ==========")
# This section only applies when you are running run.py directly
if __name__ == '__main__':
blockbuster.bb_logging.logger.info("Running http on port 5000")
blockbuster.app.run(host='0.0.0.0', debug=True) | <commit_before>__author__ = 'matt'
import datetime
import blockbuster
blockbuster.app.debug = blockbuster.config.debug_mode
blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")
blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@ BlockBuster " + blockbuster.config.app_version + " "
"@@@@@@@@@@@@@@@@@@")
blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")
blockbuster.bb_logging.logger.info("=== Application startup - " + str(datetime.datetime.now()) + " ====")
blockbuster.bb_logging.logger.info(
'================Time restriction disabled================') \
if not blockbuster.config.timerestriction else blockbuster.bb_logging.logger.info(
'================Time restriction enabled================')
blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")
if blockbuster.config.debug_mode:
blockbuster.bb_logging.logger.info("========= APPLICATION IS RUNNING IN DEBUG MODE ==========")
# This section only applies when you are running run.py directly
if __name__ == '__main__':
blockbuster.bb_logging.logger.info("Running http on port 5000")
blockbuster.app.run(host='0.0.0.0', debug=True)<commit_msg>Update reference to application version<commit_after> | __author__ = 'matt'
import datetime
import blockbuster
blockbuster.app.debug = blockbuster.config.debug_mode
blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")
blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@ BlockBuster " + blockbuster.__version__ + " "
"@@@@@@@@@@@@@@@@@@")
blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")
blockbuster.bb_logging.logger.info("=== Application startup - " + str(datetime.datetime.now()) + " ====")
blockbuster.bb_logging.logger.info(
'================Time restriction disabled================') \
if not blockbuster.config.timerestriction else blockbuster.bb_logging.logger.info(
'================Time restriction enabled================')
blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")
if blockbuster.config.debug_mode:
blockbuster.bb_logging.logger.info("========= APPLICATION IS RUNNING IN DEBUG MODE ==========")
# This section only applies when you are running run.py directly
if __name__ == '__main__':
blockbuster.bb_logging.logger.info("Running http on port 5000")
blockbuster.app.run(host='0.0.0.0', debug=True) | __author__ = 'matt'
import datetime
import blockbuster
blockbuster.app.debug = blockbuster.config.debug_mode
blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")
blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@ BlockBuster " + blockbuster.config.app_version + " "
"@@@@@@@@@@@@@@@@@@")
blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")
blockbuster.bb_logging.logger.info("=== Application startup - " + str(datetime.datetime.now()) + " ====")
blockbuster.bb_logging.logger.info(
'================Time restriction disabled================') \
if not blockbuster.config.timerestriction else blockbuster.bb_logging.logger.info(
'================Time restriction enabled================')
blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")
if blockbuster.config.debug_mode:
blockbuster.bb_logging.logger.info("========= APPLICATION IS RUNNING IN DEBUG MODE ==========")
# This section only applies when you are running run.py directly
if __name__ == '__main__':
blockbuster.bb_logging.logger.info("Running http on port 5000")
blockbuster.app.run(host='0.0.0.0', debug=True)Update reference to application version__author__ = 'matt'
import datetime
import blockbuster
blockbuster.app.debug = blockbuster.config.debug_mode
blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")
blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@ BlockBuster " + blockbuster.__version__ + " "
"@@@@@@@@@@@@@@@@@@")
blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")
blockbuster.bb_logging.logger.info("=== Application startup - " + str(datetime.datetime.now()) + " ====")
blockbuster.bb_logging.logger.info(
'================Time restriction disabled================') \
if not blockbuster.config.timerestriction else blockbuster.bb_logging.logger.info(
'================Time restriction enabled================')
blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")
if blockbuster.config.debug_mode:
blockbuster.bb_logging.logger.info("========= APPLICATION IS RUNNING IN DEBUG MODE ==========")
# This section only applies when you are running run.py directly
if __name__ == '__main__':
blockbuster.bb_logging.logger.info("Running http on port 5000")
blockbuster.app.run(host='0.0.0.0', debug=True) | <commit_before>__author__ = 'matt'
import datetime
import blockbuster
blockbuster.app.debug = blockbuster.config.debug_mode
blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")
blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@ BlockBuster " + blockbuster.config.app_version + " "
"@@@@@@@@@@@@@@@@@@")
blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")
blockbuster.bb_logging.logger.info("=== Application startup - " + str(datetime.datetime.now()) + " ====")
blockbuster.bb_logging.logger.info(
'================Time restriction disabled================') \
if not blockbuster.config.timerestriction else blockbuster.bb_logging.logger.info(
'================Time restriction enabled================')
blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")
if blockbuster.config.debug_mode:
blockbuster.bb_logging.logger.info("========= APPLICATION IS RUNNING IN DEBUG MODE ==========")
# This section only applies when you are running run.py directly
if __name__ == '__main__':
blockbuster.bb_logging.logger.info("Running http on port 5000")
blockbuster.app.run(host='0.0.0.0', debug=True)<commit_msg>Update reference to application version<commit_after>__author__ = 'matt'
import datetime
import blockbuster
blockbuster.app.debug = blockbuster.config.debug_mode
blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")
blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@ BlockBuster " + blockbuster.__version__ + " "
"@@@@@@@@@@@@@@@@@@")
blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")
blockbuster.bb_logging.logger.info("=== Application startup - " + str(datetime.datetime.now()) + " ====")
blockbuster.bb_logging.logger.info(
'================Time restriction disabled================') \
if not blockbuster.config.timerestriction else blockbuster.bb_logging.logger.info(
'================Time restriction enabled================')
blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")
if blockbuster.config.debug_mode:
blockbuster.bb_logging.logger.info("========= APPLICATION IS RUNNING IN DEBUG MODE ==========")
# This section only applies when you are running run.py directly
if __name__ == '__main__':
blockbuster.bb_logging.logger.info("Running http on port 5000")
blockbuster.app.run(host='0.0.0.0', debug=True) |
3f99d7728714aed4bc19d68d2e2d410d792fe4e9 | iati/core/constants.py | iati/core/constants.py | """A module containing constants required throughout IATI library code.
Warning:
This contents of this module should currently be deemed private.
Todo:
Allow logging constants to be user-definable.
"""
STANDARD_VERSIONS = ['2.02']
"""Define all versions of the Standard.
Todo:
This constant to be populated by the values in the Version codelist, rather than hard-coded.
Consider if functionality should extend to working with development versions of the Standard (e.g. during an upgrade process).
"""
STANDARD_VERSION_LATEST = max(STANDARD_VERSIONS)
"""The latest version of the IATI Standard."""
LOG_FILE_NAME = 'iatilib.log'
"""The location of the primary IATI log file.
Warning:
Logging should be clearly user-definable.
"""
LOGGER_NAME = 'iati'
"""The name of the primary IATI Logger.
Warning:
This should be better based on specific packages.
"""
NAMESPACE = '{http://www.w3.org/2001/XMLSchema}'
"""The namespace that IATI Schema XSD files are specified within."""
NSMAP = {'xsd': 'http://www.w3.org/2001/XMLSchema'}
"""A dictionary for interpreting namespaces in IATI Schemas."""
| """A module containing constants required throughout IATI library code.
The contents of this file are not designed to be user-editable. Only edit if you know what you are doing!
Warning:
This contents of this module should currently be deemed private.
Todo:
Allow logging constants to be user-definable.
"""
STANDARD_VERSIONS = ['2.02']
"""Define all versions of the Standard.
Todo:
This constant to be populated by the values in the Version codelist, rather than hard-coded.
Consider if functionality should extend to working with development versions of the Standard (e.g. during an upgrade process).
"""
STANDARD_VERSION_LATEST = max(STANDARD_VERSIONS)
"""The latest version of the IATI Standard."""
LOG_FILE_NAME = 'iatilib.log'
"""The location of the primary IATI log file.
Warning:
Logging should be clearly user-definable.
"""
LOGGER_NAME = 'iati'
"""The name of the primary IATI Logger.
Warning:
This should be better based on specific packages.
"""
NAMESPACE = '{http://www.w3.org/2001/XMLSchema}'
"""The namespace that IATI Schema XSD files are specified within."""
NSMAP = {'xsd': 'http://www.w3.org/2001/XMLSchema'}
"""A dictionary for interpreting namespaces in IATI Schemas."""
| Add note that the file is not designed to be user-editable! | Add note that the file is not designed to be user-editable!
| Python | mit | IATI/iati.core,IATI/iati.core | """A module containing constants required throughout IATI library code.
Warning:
This contents of this module should currently be deemed private.
Todo:
Allow logging constants to be user-definable.
"""
STANDARD_VERSIONS = ['2.02']
"""Define all versions of the Standard.
Todo:
This constant to be populated by the values in the Version codelist, rather than hard-coded.
Consider if functionality should extend to working with development versions of the Standard (e.g. during an upgrade process).
"""
STANDARD_VERSION_LATEST = max(STANDARD_VERSIONS)
"""The latest version of the IATI Standard."""
LOG_FILE_NAME = 'iatilib.log'
"""The location of the primary IATI log file.
Warning:
Logging should be clearly user-definable.
"""
LOGGER_NAME = 'iati'
"""The name of the primary IATI Logger.
Warning:
This should be better based on specific packages.
"""
NAMESPACE = '{http://www.w3.org/2001/XMLSchema}'
"""The namespace that IATI Schema XSD files are specified within."""
NSMAP = {'xsd': 'http://www.w3.org/2001/XMLSchema'}
"""A dictionary for interpreting namespaces in IATI Schemas."""
Add note that the file is not designed to be user-editable! | """A module containing constants required throughout IATI library code.
The contents of this file are not designed to be user-editable. Only edit if you know what you are doing!
Warning:
This contents of this module should currently be deemed private.
Todo:
Allow logging constants to be user-definable.
"""
STANDARD_VERSIONS = ['2.02']
"""Define all versions of the Standard.
Todo:
This constant to be populated by the values in the Version codelist, rather than hard-coded.
Consider if functionality should extend to working with development versions of the Standard (e.g. during an upgrade process).
"""
STANDARD_VERSION_LATEST = max(STANDARD_VERSIONS)
"""The latest version of the IATI Standard."""
LOG_FILE_NAME = 'iatilib.log'
"""The location of the primary IATI log file.
Warning:
Logging should be clearly user-definable.
"""
LOGGER_NAME = 'iati'
"""The name of the primary IATI Logger.
Warning:
This should be better based on specific packages.
"""
NAMESPACE = '{http://www.w3.org/2001/XMLSchema}'
"""The namespace that IATI Schema XSD files are specified within."""
NSMAP = {'xsd': 'http://www.w3.org/2001/XMLSchema'}
"""A dictionary for interpreting namespaces in IATI Schemas."""
| <commit_before>"""A module containing constants required throughout IATI library code.
Warning:
This contents of this module should currently be deemed private.
Todo:
Allow logging constants to be user-definable.
"""
STANDARD_VERSIONS = ['2.02']
"""Define all versions of the Standard.
Todo:
This constant to be populated by the values in the Version codelist, rather than hard-coded.
Consider if functionality should extend to working with development versions of the Standard (e.g. during an upgrade process).
"""
STANDARD_VERSION_LATEST = max(STANDARD_VERSIONS)
"""The latest version of the IATI Standard."""
LOG_FILE_NAME = 'iatilib.log'
"""The location of the primary IATI log file.
Warning:
Logging should be clearly user-definable.
"""
LOGGER_NAME = 'iati'
"""The name of the primary IATI Logger.
Warning:
This should be better based on specific packages.
"""
NAMESPACE = '{http://www.w3.org/2001/XMLSchema}'
"""The namespace that IATI Schema XSD files are specified within."""
NSMAP = {'xsd': 'http://www.w3.org/2001/XMLSchema'}
"""A dictionary for interpreting namespaces in IATI Schemas."""
<commit_msg>Add note that the file is not designed to be user-editable!<commit_after> | """A module containing constants required throughout IATI library code.
The contents of this file are not designed to be user-editable. Only edit if you know what you are doing!
Warning:
This contents of this module should currently be deemed private.
Todo:
Allow logging constants to be user-definable.
"""
STANDARD_VERSIONS = ['2.02']
"""Define all versions of the Standard.
Todo:
This constant to be populated by the values in the Version codelist, rather than hard-coded.
Consider if functionality should extend to working with development versions of the Standard (e.g. during an upgrade process).
"""
STANDARD_VERSION_LATEST = max(STANDARD_VERSIONS)
"""The latest version of the IATI Standard."""
LOG_FILE_NAME = 'iatilib.log'
"""The location of the primary IATI log file.
Warning:
Logging should be clearly user-definable.
"""
LOGGER_NAME = 'iati'
"""The name of the primary IATI Logger.
Warning:
This should be better based on specific packages.
"""
NAMESPACE = '{http://www.w3.org/2001/XMLSchema}'
"""The namespace that IATI Schema XSD files are specified within."""
NSMAP = {'xsd': 'http://www.w3.org/2001/XMLSchema'}
"""A dictionary for interpreting namespaces in IATI Schemas."""
| """A module containing constants required throughout IATI library code.
Warning:
This contents of this module should currently be deemed private.
Todo:
Allow logging constants to be user-definable.
"""
STANDARD_VERSIONS = ['2.02']
"""Define all versions of the Standard.
Todo:
This constant to be populated by the values in the Version codelist, rather than hard-coded.
Consider if functionality should extend to working with development versions of the Standard (e.g. during an upgrade process).
"""
STANDARD_VERSION_LATEST = max(STANDARD_VERSIONS)
"""The latest version of the IATI Standard."""
LOG_FILE_NAME = 'iatilib.log'
"""The location of the primary IATI log file.
Warning:
Logging should be clearly user-definable.
"""
LOGGER_NAME = 'iati'
"""The name of the primary IATI Logger.
Warning:
This should be better based on specific packages.
"""
NAMESPACE = '{http://www.w3.org/2001/XMLSchema}'
"""The namespace that IATI Schema XSD files are specified within."""
NSMAP = {'xsd': 'http://www.w3.org/2001/XMLSchema'}
"""A dictionary for interpreting namespaces in IATI Schemas."""
Add note that the file is not designed to be user-editable!"""A module containing constants required throughout IATI library code.
The contents of this file are not designed to be user-editable. Only edit if you know what you are doing!
Warning:
This contents of this module should currently be deemed private.
Todo:
Allow logging constants to be user-definable.
"""
STANDARD_VERSIONS = ['2.02']
"""Define all versions of the Standard.
Todo:
This constant to be populated by the values in the Version codelist, rather than hard-coded.
Consider if functionality should extend to working with development versions of the Standard (e.g. during an upgrade process).
"""
STANDARD_VERSION_LATEST = max(STANDARD_VERSIONS)
"""The latest version of the IATI Standard."""
LOG_FILE_NAME = 'iatilib.log'
"""The location of the primary IATI log file.
Warning:
Logging should be clearly user-definable.
"""
LOGGER_NAME = 'iati'
"""The name of the primary IATI Logger.
Warning:
This should be better based on specific packages.
"""
NAMESPACE = '{http://www.w3.org/2001/XMLSchema}'
"""The namespace that IATI Schema XSD files are specified within."""
NSMAP = {'xsd': 'http://www.w3.org/2001/XMLSchema'}
"""A dictionary for interpreting namespaces in IATI Schemas."""
| <commit_before>"""A module containing constants required throughout IATI library code.
Warning:
This contents of this module should currently be deemed private.
Todo:
Allow logging constants to be user-definable.
"""
STANDARD_VERSIONS = ['2.02']
"""Define all versions of the Standard.
Todo:
This constant to be populated by the values in the Version codelist, rather than hard-coded.
Consider if functionality should extend to working with development versions of the Standard (e.g. during an upgrade process).
"""
STANDARD_VERSION_LATEST = max(STANDARD_VERSIONS)
"""The latest version of the IATI Standard."""
LOG_FILE_NAME = 'iatilib.log'
"""The location of the primary IATI log file.
Warning:
Logging should be clearly user-definable.
"""
LOGGER_NAME = 'iati'
"""The name of the primary IATI Logger.
Warning:
This should be better based on specific packages.
"""
NAMESPACE = '{http://www.w3.org/2001/XMLSchema}'
"""The namespace that IATI Schema XSD files are specified within."""
NSMAP = {'xsd': 'http://www.w3.org/2001/XMLSchema'}
"""A dictionary for interpreting namespaces in IATI Schemas."""
<commit_msg>Add note that the file is not designed to be user-editable!<commit_after>"""A module containing constants required throughout IATI library code.
The contents of this file are not designed to be user-editable. Only edit if you know what you are doing!
Warning:
This contents of this module should currently be deemed private.
Todo:
Allow logging constants to be user-definable.
"""
STANDARD_VERSIONS = ['2.02']
"""Define all versions of the Standard.
Todo:
This constant to be populated by the values in the Version codelist, rather than hard-coded.
Consider if functionality should extend to working with development versions of the Standard (e.g. during an upgrade process).
"""
STANDARD_VERSION_LATEST = max(STANDARD_VERSIONS)
"""The latest version of the IATI Standard."""
LOG_FILE_NAME = 'iatilib.log'
"""The location of the primary IATI log file.
Warning:
Logging should be clearly user-definable.
"""
LOGGER_NAME = 'iati'
"""The name of the primary IATI Logger.
Warning:
This should be better based on specific packages.
"""
NAMESPACE = '{http://www.w3.org/2001/XMLSchema}'
"""The namespace that IATI Schema XSD files are specified within."""
NSMAP = {'xsd': 'http://www.w3.org/2001/XMLSchema'}
"""A dictionary for interpreting namespaces in IATI Schemas."""
|
56a2848a131e411ed687eec4d6a68f1901d942dc | icforum/forum/forms.py | icforum/forum/forms.py | from django import forms
from django.contrib.auth import authenticate
from .models import *
class SignInForm(forms.Form):
username = forms.CharField(max_length=100, label='Username')
password = forms.CharField(max_length=100, label='Password', widget=forms.PasswordInput)
def clean(self):
cleaned_data = super(SignInForm, self).clean()
user = authenticate(username=cleaned_data.get('username'), password=cleaned_data.get('password'))
if user is None:
raise ValidationError('Invalid username or password')
class TopicForm(forms.ModelForm):
class Meta:
model = Topic
fields = ['title', 'tags']
tags = forms.ModelMultipleChoiceField(queryset=Tag.objects.all())
first_message = forms.CharField(widget=forms.Textarea)
class NewMessageForm(forms.ModelForm):
class Meta:
model = Message
fields = ['content']
content = forms.CharField(widget=forms.Textarea)
| from django import forms
from django.contrib.auth import authenticate
from .models import *
class SignInForm(forms.Form):
username = forms.CharField(max_length=100, label='Username')
password = forms.CharField(max_length=100, label='Password', widget=forms.PasswordInput)
def clean(self):
cleaned_data = super(SignInForm, self).clean()
user = authenticate(username=cleaned_data.get('username'), password=cleaned_data.get('password'))
if user is None:
raise ValidationError('Invalid username or password')
class TopicForm(forms.ModelForm):
class Meta:
model = Topic
fields = ['title', 'tags']
tags = forms.ModelMultipleChoiceField(queryset=Tag.objects.all())
first_message = forms.CharField(widget=forms.Textarea)
class NewMessageForm(forms.ModelForm):
class Meta:
model = Message
fields = ['content']
content = forms.CharField(label="New message", widget=forms.Textarea)
| Fix label on "new message" form | Fix label on "new message" form
| Python | apache-2.0 | rdujardin/icforum,rdujardin/icforum,rdujardin/icforum | from django import forms
from django.contrib.auth import authenticate
from .models import *
class SignInForm(forms.Form):
username = forms.CharField(max_length=100, label='Username')
password = forms.CharField(max_length=100, label='Password', widget=forms.PasswordInput)
def clean(self):
cleaned_data = super(SignInForm, self).clean()
user = authenticate(username=cleaned_data.get('username'), password=cleaned_data.get('password'))
if user is None:
raise ValidationError('Invalid username or password')
class TopicForm(forms.ModelForm):
class Meta:
model = Topic
fields = ['title', 'tags']
tags = forms.ModelMultipleChoiceField(queryset=Tag.objects.all())
first_message = forms.CharField(widget=forms.Textarea)
class NewMessageForm(forms.ModelForm):
class Meta:
model = Message
fields = ['content']
content = forms.CharField(widget=forms.Textarea)
Fix label on "new message" form | from django import forms
from django.contrib.auth import authenticate
from .models import *
class SignInForm(forms.Form):
username = forms.CharField(max_length=100, label='Username')
password = forms.CharField(max_length=100, label='Password', widget=forms.PasswordInput)
def clean(self):
cleaned_data = super(SignInForm, self).clean()
user = authenticate(username=cleaned_data.get('username'), password=cleaned_data.get('password'))
if user is None:
raise ValidationError('Invalid username or password')
class TopicForm(forms.ModelForm):
class Meta:
model = Topic
fields = ['title', 'tags']
tags = forms.ModelMultipleChoiceField(queryset=Tag.objects.all())
first_message = forms.CharField(widget=forms.Textarea)
class NewMessageForm(forms.ModelForm):
class Meta:
model = Message
fields = ['content']
content = forms.CharField(label="New message", widget=forms.Textarea)
| <commit_before>from django import forms
from django.contrib.auth import authenticate
from .models import *
class SignInForm(forms.Form):
username = forms.CharField(max_length=100, label='Username')
password = forms.CharField(max_length=100, label='Password', widget=forms.PasswordInput)
def clean(self):
cleaned_data = super(SignInForm, self).clean()
user = authenticate(username=cleaned_data.get('username'), password=cleaned_data.get('password'))
if user is None:
raise ValidationError('Invalid username or password')
class TopicForm(forms.ModelForm):
class Meta:
model = Topic
fields = ['title', 'tags']
tags = forms.ModelMultipleChoiceField(queryset=Tag.objects.all())
first_message = forms.CharField(widget=forms.Textarea)
class NewMessageForm(forms.ModelForm):
class Meta:
model = Message
fields = ['content']
content = forms.CharField(widget=forms.Textarea)
<commit_msg>Fix label on "new message" form<commit_after> | from django import forms
from django.contrib.auth import authenticate
from .models import *
class SignInForm(forms.Form):
username = forms.CharField(max_length=100, label='Username')
password = forms.CharField(max_length=100, label='Password', widget=forms.PasswordInput)
def clean(self):
cleaned_data = super(SignInForm, self).clean()
user = authenticate(username=cleaned_data.get('username'), password=cleaned_data.get('password'))
if user is None:
raise ValidationError('Invalid username or password')
class TopicForm(forms.ModelForm):
class Meta:
model = Topic
fields = ['title', 'tags']
tags = forms.ModelMultipleChoiceField(queryset=Tag.objects.all())
first_message = forms.CharField(widget=forms.Textarea)
class NewMessageForm(forms.ModelForm):
class Meta:
model = Message
fields = ['content']
content = forms.CharField(label="New message", widget=forms.Textarea)
| from django import forms
from django.contrib.auth import authenticate
from .models import *
class SignInForm(forms.Form):
username = forms.CharField(max_length=100, label='Username')
password = forms.CharField(max_length=100, label='Password', widget=forms.PasswordInput)
def clean(self):
cleaned_data = super(SignInForm, self).clean()
user = authenticate(username=cleaned_data.get('username'), password=cleaned_data.get('password'))
if user is None:
raise ValidationError('Invalid username or password')
class TopicForm(forms.ModelForm):
class Meta:
model = Topic
fields = ['title', 'tags']
tags = forms.ModelMultipleChoiceField(queryset=Tag.objects.all())
first_message = forms.CharField(widget=forms.Textarea)
class NewMessageForm(forms.ModelForm):
class Meta:
model = Message
fields = ['content']
content = forms.CharField(widget=forms.Textarea)
Fix label on "new message" formfrom django import forms
from django.contrib.auth import authenticate
from .models import *
class SignInForm(forms.Form):
username = forms.CharField(max_length=100, label='Username')
password = forms.CharField(max_length=100, label='Password', widget=forms.PasswordInput)
def clean(self):
cleaned_data = super(SignInForm, self).clean()
user = authenticate(username=cleaned_data.get('username'), password=cleaned_data.get('password'))
if user is None:
raise ValidationError('Invalid username or password')
class TopicForm(forms.ModelForm):
class Meta:
model = Topic
fields = ['title', 'tags']
tags = forms.ModelMultipleChoiceField(queryset=Tag.objects.all())
first_message = forms.CharField(widget=forms.Textarea)
class NewMessageForm(forms.ModelForm):
class Meta:
model = Message
fields = ['content']
content = forms.CharField(label="New message", widget=forms.Textarea)
| <commit_before>from django import forms
from django.contrib.auth import authenticate
from .models import *
class SignInForm(forms.Form):
username = forms.CharField(max_length=100, label='Username')
password = forms.CharField(max_length=100, label='Password', widget=forms.PasswordInput)
def clean(self):
cleaned_data = super(SignInForm, self).clean()
user = authenticate(username=cleaned_data.get('username'), password=cleaned_data.get('password'))
if user is None:
raise ValidationError('Invalid username or password')
class TopicForm(forms.ModelForm):
class Meta:
model = Topic
fields = ['title', 'tags']
tags = forms.ModelMultipleChoiceField(queryset=Tag.objects.all())
first_message = forms.CharField(widget=forms.Textarea)
class NewMessageForm(forms.ModelForm):
class Meta:
model = Message
fields = ['content']
content = forms.CharField(widget=forms.Textarea)
<commit_msg>Fix label on "new message" form<commit_after>from django import forms
from django.contrib.auth import authenticate
from .models import *
class SignInForm(forms.Form):
username = forms.CharField(max_length=100, label='Username')
password = forms.CharField(max_length=100, label='Password', widget=forms.PasswordInput)
def clean(self):
cleaned_data = super(SignInForm, self).clean()
user = authenticate(username=cleaned_data.get('username'), password=cleaned_data.get('password'))
if user is None:
raise ValidationError('Invalid username or password')
class TopicForm(forms.ModelForm):
class Meta:
model = Topic
fields = ['title', 'tags']
tags = forms.ModelMultipleChoiceField(queryset=Tag.objects.all())
first_message = forms.CharField(widget=forms.Textarea)
class NewMessageForm(forms.ModelForm):
class Meta:
model = Message
fields = ['content']
content = forms.CharField(label="New message", widget=forms.Textarea)
|
4bb72952c934dd6aea3db393226d37eb1b0eb72e | penelophant/models/auctions/DoubleBlindAuction.py | penelophant/models/auctions/DoubleBlindAuction.py | """ Double Blind Auction implementation """
from penelophant.models.Auction import Auction
class DoubleBlindAuction(Auction):
""" Double Blind Auction implementation """
__type__ = 'doubleblind'
__name__ = 'Double-Blind Auction'
__mapper_args__ = {'polymorphic_identity': __type__}
| """ Double Blind Auction implementation """
from penelophant.models.Auction import Auction
class DoubleBlindAuction(Auction):
""" Double Blind Auction implementation """
__type__ = 'doubleblind'
__name__ = 'Double-Blind Auction'
__mapper_args__ = {'polymorphic_identity': __type__}
show_highest_bid = False
| Add disallowing of double blind auction highest bids being disclosed | Add disallowing of double blind auction highest bids being disclosed
| Python | apache-2.0 | kevinoconnor7/penelophant,kevinoconnor7/penelophant | """ Double Blind Auction implementation """
from penelophant.models.Auction import Auction
class DoubleBlindAuction(Auction):
""" Double Blind Auction implementation """
__type__ = 'doubleblind'
__name__ = 'Double-Blind Auction'
__mapper_args__ = {'polymorphic_identity': __type__}
Add disallowing of double blind auction highest bids being disclosed | """ Double Blind Auction implementation """
from penelophant.models.Auction import Auction
class DoubleBlindAuction(Auction):
""" Double Blind Auction implementation """
__type__ = 'doubleblind'
__name__ = 'Double-Blind Auction'
__mapper_args__ = {'polymorphic_identity': __type__}
show_highest_bid = False
| <commit_before>""" Double Blind Auction implementation """
from penelophant.models.Auction import Auction
class DoubleBlindAuction(Auction):
""" Double Blind Auction implementation """
__type__ = 'doubleblind'
__name__ = 'Double-Blind Auction'
__mapper_args__ = {'polymorphic_identity': __type__}
<commit_msg>Add disallowing of double blind auction highest bids being disclosed<commit_after> | """ Double Blind Auction implementation """
from penelophant.models.Auction import Auction
class DoubleBlindAuction(Auction):
""" Double Blind Auction implementation """
__type__ = 'doubleblind'
__name__ = 'Double-Blind Auction'
__mapper_args__ = {'polymorphic_identity': __type__}
show_highest_bid = False
| """ Double Blind Auction implementation """
from penelophant.models.Auction import Auction
class DoubleBlindAuction(Auction):
""" Double Blind Auction implementation """
__type__ = 'doubleblind'
__name__ = 'Double-Blind Auction'
__mapper_args__ = {'polymorphic_identity': __type__}
Add disallowing of double blind auction highest bids being disclosed""" Double Blind Auction implementation """
from penelophant.models.Auction import Auction
class DoubleBlindAuction(Auction):
""" Double Blind Auction implementation """
__type__ = 'doubleblind'
__name__ = 'Double-Blind Auction'
__mapper_args__ = {'polymorphic_identity': __type__}
show_highest_bid = False
| <commit_before>""" Double Blind Auction implementation """
from penelophant.models.Auction import Auction
class DoubleBlindAuction(Auction):
""" Double Blind Auction implementation """
__type__ = 'doubleblind'
__name__ = 'Double-Blind Auction'
__mapper_args__ = {'polymorphic_identity': __type__}
<commit_msg>Add disallowing of double blind auction highest bids being disclosed<commit_after>""" Double Blind Auction implementation """
from penelophant.models.Auction import Auction
class DoubleBlindAuction(Auction):
""" Double Blind Auction implementation """
__type__ = 'doubleblind'
__name__ = 'Double-Blind Auction'
__mapper_args__ = {'polymorphic_identity': __type__}
show_highest_bid = False
|
9f43d877aed9eeca9fe1b2a8c3a19c034b5f3dfb | armstrong/apps/related_content/models.py | armstrong/apps/related_content/models.py | from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType
from django.db import models
from . import managers
class RelatedType(models.Model):
title = models.CharField(max_length=100)
def __unicode__(self):
return self.title
class RelatedContent(models.Model):
related_type = models.ForeignKey(RelatedType)
order = models.IntegerField(default=0)
source_type = models.ForeignKey(ContentType, related_name="from")
source_id = models.PositiveIntegerField()
source_object = generic.GenericForeignKey('source_type', 'source_id')
destination_type = models.ForeignKey(ContentType, related_name="to")
destination_id = models.PositiveIntegerField()
destination_object = generic.GenericForeignKey('destination_type',
'destination_id')
objects = managers.RelatedContentManager()
class Meta:
ordering = ["order"]
def __unicode__(self):
return u"%s (%d): %s" % (self.related_type, self.order,
self.destination_object)
| from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType
from django.db import models
from genericm2m.models import RelatedObjectsDescriptor
from . import managers
class RelatedObjectsField(RelatedObjectsDescriptor):
def __init__(self, model=None, from_field="source_object",
to_field="destination_object"):
if not model:
model = RelatedContent
super(RelatedObjectsField, self).__init__(model, from_field, to_field)
class RelatedType(models.Model):
title = models.CharField(max_length=100)
def __unicode__(self):
return self.title
class RelatedContent(models.Model):
related_type = models.ForeignKey(RelatedType)
order = models.IntegerField(default=0)
source_type = models.ForeignKey(ContentType, related_name="from")
source_id = models.PositiveIntegerField()
source_object = generic.GenericForeignKey('source_type', 'source_id')
destination_type = models.ForeignKey(ContentType, related_name="to")
destination_id = models.PositiveIntegerField()
destination_object = generic.GenericForeignKey('destination_type',
'destination_id')
objects = managers.RelatedContentManager()
class Meta:
ordering = ["order"]
def __unicode__(self):
return u"%s (%d): %s" % (self.related_type, self.order,
self.destination_object)
| Add in field for making a `related` field on objects. | Add in field for making a `related` field on objects.
Big thanks to @coleifer for his [django-generic-m2m][] project, we've
got a field for adding `related` to other objects with minimal new code.
[django-generic-m2m]: http://github.com/coleifer/django-generic-m2m
| Python | apache-2.0 | texastribune/armstrong.apps.related_content,armstrong/armstrong.apps.related_content,texastribune/armstrong.apps.related_content,armstrong/armstrong.apps.related_content | from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType
from django.db import models
from . import managers
class RelatedType(models.Model):
title = models.CharField(max_length=100)
def __unicode__(self):
return self.title
class RelatedContent(models.Model):
related_type = models.ForeignKey(RelatedType)
order = models.IntegerField(default=0)
source_type = models.ForeignKey(ContentType, related_name="from")
source_id = models.PositiveIntegerField()
source_object = generic.GenericForeignKey('source_type', 'source_id')
destination_type = models.ForeignKey(ContentType, related_name="to")
destination_id = models.PositiveIntegerField()
destination_object = generic.GenericForeignKey('destination_type',
'destination_id')
objects = managers.RelatedContentManager()
class Meta:
ordering = ["order"]
def __unicode__(self):
return u"%s (%d): %s" % (self.related_type, self.order,
self.destination_object)
Add in field for making a `related` field on objects.
Big thanks to @coleifer for his [django-generic-m2m][] project, we've
got a field for adding `related` to other objects with minimal new code.
[django-generic-m2m]: http://github.com/coleifer/django-generic-m2m | from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType
from django.db import models
from genericm2m.models import RelatedObjectsDescriptor
from . import managers
class RelatedObjectsField(RelatedObjectsDescriptor):
def __init__(self, model=None, from_field="source_object",
to_field="destination_object"):
if not model:
model = RelatedContent
super(RelatedObjectsField, self).__init__(model, from_field, to_field)
class RelatedType(models.Model):
title = models.CharField(max_length=100)
def __unicode__(self):
return self.title
class RelatedContent(models.Model):
related_type = models.ForeignKey(RelatedType)
order = models.IntegerField(default=0)
source_type = models.ForeignKey(ContentType, related_name="from")
source_id = models.PositiveIntegerField()
source_object = generic.GenericForeignKey('source_type', 'source_id')
destination_type = models.ForeignKey(ContentType, related_name="to")
destination_id = models.PositiveIntegerField()
destination_object = generic.GenericForeignKey('destination_type',
'destination_id')
objects = managers.RelatedContentManager()
class Meta:
ordering = ["order"]
def __unicode__(self):
return u"%s (%d): %s" % (self.related_type, self.order,
self.destination_object)
| <commit_before>from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType
from django.db import models
from . import managers
class RelatedType(models.Model):
title = models.CharField(max_length=100)
def __unicode__(self):
return self.title
class RelatedContent(models.Model):
related_type = models.ForeignKey(RelatedType)
order = models.IntegerField(default=0)
source_type = models.ForeignKey(ContentType, related_name="from")
source_id = models.PositiveIntegerField()
source_object = generic.GenericForeignKey('source_type', 'source_id')
destination_type = models.ForeignKey(ContentType, related_name="to")
destination_id = models.PositiveIntegerField()
destination_object = generic.GenericForeignKey('destination_type',
'destination_id')
objects = managers.RelatedContentManager()
class Meta:
ordering = ["order"]
def __unicode__(self):
return u"%s (%d): %s" % (self.related_type, self.order,
self.destination_object)
<commit_msg>Add in field for making a `related` field on objects.
Big thanks to @coleifer for his [django-generic-m2m][] project, we've
got a field for adding `related` to other objects with minimal new code.
[django-generic-m2m]: http://github.com/coleifer/django-generic-m2m<commit_after> | from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType
from django.db import models
from genericm2m.models import RelatedObjectsDescriptor
from . import managers
class RelatedObjectsField(RelatedObjectsDescriptor):
def __init__(self, model=None, from_field="source_object",
to_field="destination_object"):
if not model:
model = RelatedContent
super(RelatedObjectsField, self).__init__(model, from_field, to_field)
class RelatedType(models.Model):
title = models.CharField(max_length=100)
def __unicode__(self):
return self.title
class RelatedContent(models.Model):
related_type = models.ForeignKey(RelatedType)
order = models.IntegerField(default=0)
source_type = models.ForeignKey(ContentType, related_name="from")
source_id = models.PositiveIntegerField()
source_object = generic.GenericForeignKey('source_type', 'source_id')
destination_type = models.ForeignKey(ContentType, related_name="to")
destination_id = models.PositiveIntegerField()
destination_object = generic.GenericForeignKey('destination_type',
'destination_id')
objects = managers.RelatedContentManager()
class Meta:
ordering = ["order"]
def __unicode__(self):
return u"%s (%d): %s" % (self.related_type, self.order,
self.destination_object)
| from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType
from django.db import models
from . import managers
class RelatedType(models.Model):
title = models.CharField(max_length=100)
def __unicode__(self):
return self.title
class RelatedContent(models.Model):
related_type = models.ForeignKey(RelatedType)
order = models.IntegerField(default=0)
source_type = models.ForeignKey(ContentType, related_name="from")
source_id = models.PositiveIntegerField()
source_object = generic.GenericForeignKey('source_type', 'source_id')
destination_type = models.ForeignKey(ContentType, related_name="to")
destination_id = models.PositiveIntegerField()
destination_object = generic.GenericForeignKey('destination_type',
'destination_id')
objects = managers.RelatedContentManager()
class Meta:
ordering = ["order"]
def __unicode__(self):
return u"%s (%d): %s" % (self.related_type, self.order,
self.destination_object)
Add in field for making a `related` field on objects.
Big thanks to @coleifer for his [django-generic-m2m][] project, we've
got a field for adding `related` to other objects with minimal new code.
[django-generic-m2m]: http://github.com/coleifer/django-generic-m2mfrom django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType
from django.db import models
from genericm2m.models import RelatedObjectsDescriptor
from . import managers
class RelatedObjectsField(RelatedObjectsDescriptor):
def __init__(self, model=None, from_field="source_object",
to_field="destination_object"):
if not model:
model = RelatedContent
super(RelatedObjectsField, self).__init__(model, from_field, to_field)
class RelatedType(models.Model):
title = models.CharField(max_length=100)
def __unicode__(self):
return self.title
class RelatedContent(models.Model):
related_type = models.ForeignKey(RelatedType)
order = models.IntegerField(default=0)
source_type = models.ForeignKey(ContentType, related_name="from")
source_id = models.PositiveIntegerField()
source_object = generic.GenericForeignKey('source_type', 'source_id')
destination_type = models.ForeignKey(ContentType, related_name="to")
destination_id = models.PositiveIntegerField()
destination_object = generic.GenericForeignKey('destination_type',
'destination_id')
objects = managers.RelatedContentManager()
class Meta:
ordering = ["order"]
def __unicode__(self):
return u"%s (%d): %s" % (self.related_type, self.order,
self.destination_object)
| <commit_before>from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType
from django.db import models
from . import managers
class RelatedType(models.Model):
title = models.CharField(max_length=100)
def __unicode__(self):
return self.title
class RelatedContent(models.Model):
related_type = models.ForeignKey(RelatedType)
order = models.IntegerField(default=0)
source_type = models.ForeignKey(ContentType, related_name="from")
source_id = models.PositiveIntegerField()
source_object = generic.GenericForeignKey('source_type', 'source_id')
destination_type = models.ForeignKey(ContentType, related_name="to")
destination_id = models.PositiveIntegerField()
destination_object = generic.GenericForeignKey('destination_type',
'destination_id')
objects = managers.RelatedContentManager()
class Meta:
ordering = ["order"]
def __unicode__(self):
return u"%s (%d): %s" % (self.related_type, self.order,
self.destination_object)
<commit_msg>Add in field for making a `related` field on objects.
Big thanks to @coleifer for his [django-generic-m2m][] project, we've
got a field for adding `related` to other objects with minimal new code.
[django-generic-m2m]: http://github.com/coleifer/django-generic-m2m<commit_after>from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType
from django.db import models
from genericm2m.models import RelatedObjectsDescriptor
from . import managers
class RelatedObjectsField(RelatedObjectsDescriptor):
def __init__(self, model=None, from_field="source_object",
to_field="destination_object"):
if not model:
model = RelatedContent
super(RelatedObjectsField, self).__init__(model, from_field, to_field)
class RelatedType(models.Model):
title = models.CharField(max_length=100)
def __unicode__(self):
return self.title
class RelatedContent(models.Model):
related_type = models.ForeignKey(RelatedType)
order = models.IntegerField(default=0)
source_type = models.ForeignKey(ContentType, related_name="from")
source_id = models.PositiveIntegerField()
source_object = generic.GenericForeignKey('source_type', 'source_id')
destination_type = models.ForeignKey(ContentType, related_name="to")
destination_id = models.PositiveIntegerField()
destination_object = generic.GenericForeignKey('destination_type',
'destination_id')
objects = managers.RelatedContentManager()
class Meta:
ordering = ["order"]
def __unicode__(self):
return u"%s (%d): %s" % (self.related_type, self.order,
self.destination_object)
|
5cc9d99238c417ec010db44b3919873929fd1d7f | devtools/travis-ci/update_versions_json.py | devtools/travis-ci/update_versions_json.py | import json
try:
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen
from mdtraj import version
if not version.release:
print("This is not a release.")
exit(0)
URL = 'http://www.msmbuilder.org'
versions = json.load(urlopen(URL + '/versions.json'))
# new release so all the others are now old
for i in range(len(versions)):
versions[i]['latest'] = False
versions.append({
'version': version.short_version,
'url': "{base}/{version}".format(base=URL, version=version.short_version),
'latest': True})
with open("doc/_deploy/versions.json", 'w') as versionf:
json.dump(versions, versionf)
| import json
try:
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen
from mdtraj import version
if not version.release:
print("This is not a release.")
exit(0)
URL = 'http://www.msmbuilder.org'
versions = json.load(urlopen(URL + '/versions.json'))
# new release so all the others are now old
for i in range(len(versions)):
versions[i]['latest'] = False
versions.append({
'version': version.short_version,
'display': version.short_version,
'url': "{base}/{version}".format(base=URL, version=version.short_version),
'latest': True})
with open("doc/_deploy/versions.json", 'w') as versionf:
json.dump(versions, versionf)
| Add 'display' key to versions.json | Add 'display' key to versions.json
| Python | lgpl-2.1 | mattwthompson/mdtraj,leeping/mdtraj,ctk3b/mdtraj,msultan/mdtraj,mattwthompson/mdtraj,rmcgibbo/mdtraj,dwhswenson/mdtraj,rmcgibbo/mdtraj,ctk3b/mdtraj,leeping/mdtraj,leeping/mdtraj,gph82/mdtraj,tcmoore3/mdtraj,gph82/mdtraj,ctk3b/mdtraj,msultan/mdtraj,tcmoore3/mdtraj,gph82/mdtraj,msultan/mdtraj,mdtraj/mdtraj,mattwthompson/mdtraj,mattwthompson/mdtraj,swails/mdtraj,dwhswenson/mdtraj,jchodera/mdtraj,mdtraj/mdtraj,jchodera/mdtraj,leeping/mdtraj,jchodera/mdtraj,swails/mdtraj,tcmoore3/mdtraj,swails/mdtraj,mdtraj/mdtraj,swails/mdtraj,ctk3b/mdtraj,jchodera/mdtraj,msultan/mdtraj,tcmoore3/mdtraj,rmcgibbo/mdtraj,dwhswenson/mdtraj,swails/mdtraj,ctk3b/mdtraj | import json
try:
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen
from mdtraj import version
if not version.release:
print("This is not a release.")
exit(0)
URL = 'http://www.msmbuilder.org'
versions = json.load(urlopen(URL + '/versions.json'))
# new release so all the others are now old
for i in range(len(versions)):
versions[i]['latest'] = False
versions.append({
'version': version.short_version,
'url': "{base}/{version}".format(base=URL, version=version.short_version),
'latest': True})
with open("doc/_deploy/versions.json", 'w') as versionf:
json.dump(versions, versionf)
Add 'display' key to versions.json | import json
try:
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen
from mdtraj import version
if not version.release:
print("This is not a release.")
exit(0)
URL = 'http://www.msmbuilder.org'
versions = json.load(urlopen(URL + '/versions.json'))
# new release so all the others are now old
for i in range(len(versions)):
versions[i]['latest'] = False
versions.append({
'version': version.short_version,
'display': version.short_version,
'url': "{base}/{version}".format(base=URL, version=version.short_version),
'latest': True})
with open("doc/_deploy/versions.json", 'w') as versionf:
json.dump(versions, versionf)
| <commit_before>import json
try:
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen
from mdtraj import version
if not version.release:
print("This is not a release.")
exit(0)
URL = 'http://www.msmbuilder.org'
versions = json.load(urlopen(URL + '/versions.json'))
# new release so all the others are now old
for i in range(len(versions)):
versions[i]['latest'] = False
versions.append({
'version': version.short_version,
'url': "{base}/{version}".format(base=URL, version=version.short_version),
'latest': True})
with open("doc/_deploy/versions.json", 'w') as versionf:
json.dump(versions, versionf)
<commit_msg>Add 'display' key to versions.json<commit_after> | import json
try:
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen
from mdtraj import version
if not version.release:
print("This is not a release.")
exit(0)
URL = 'http://www.msmbuilder.org'
versions = json.load(urlopen(URL + '/versions.json'))
# new release so all the others are now old
for i in range(len(versions)):
versions[i]['latest'] = False
versions.append({
'version': version.short_version,
'display': version.short_version,
'url': "{base}/{version}".format(base=URL, version=version.short_version),
'latest': True})
with open("doc/_deploy/versions.json", 'w') as versionf:
json.dump(versions, versionf)
| import json
try:
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen
from mdtraj import version
if not version.release:
print("This is not a release.")
exit(0)
URL = 'http://www.msmbuilder.org'
versions = json.load(urlopen(URL + '/versions.json'))
# new release so all the others are now old
for i in range(len(versions)):
versions[i]['latest'] = False
versions.append({
'version': version.short_version,
'url': "{base}/{version}".format(base=URL, version=version.short_version),
'latest': True})
with open("doc/_deploy/versions.json", 'w') as versionf:
json.dump(versions, versionf)
Add 'display' key to versions.jsonimport json
try:
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen
from mdtraj import version
if not version.release:
print("This is not a release.")
exit(0)
URL = 'http://www.msmbuilder.org'
versions = json.load(urlopen(URL + '/versions.json'))
# new release so all the others are now old
for i in range(len(versions)):
versions[i]['latest'] = False
versions.append({
'version': version.short_version,
'display': version.short_version,
'url': "{base}/{version}".format(base=URL, version=version.short_version),
'latest': True})
with open("doc/_deploy/versions.json", 'w') as versionf:
json.dump(versions, versionf)
| <commit_before>import json
try:
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen
from mdtraj import version
if not version.release:
print("This is not a release.")
exit(0)
URL = 'http://www.msmbuilder.org'
versions = json.load(urlopen(URL + '/versions.json'))
# new release so all the others are now old
for i in range(len(versions)):
versions[i]['latest'] = False
versions.append({
'version': version.short_version,
'url': "{base}/{version}".format(base=URL, version=version.short_version),
'latest': True})
with open("doc/_deploy/versions.json", 'w') as versionf:
json.dump(versions, versionf)
<commit_msg>Add 'display' key to versions.json<commit_after>import json
try:
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen
from mdtraj import version
if not version.release:
print("This is not a release.")
exit(0)
URL = 'http://www.msmbuilder.org'
versions = json.load(urlopen(URL + '/versions.json'))
# new release so all the others are now old
for i in range(len(versions)):
versions[i]['latest'] = False
versions.append({
'version': version.short_version,
'display': version.short_version,
'url': "{base}/{version}".format(base=URL, version=version.short_version),
'latest': True})
with open("doc/_deploy/versions.json", 'w') as versionf:
json.dump(versions, versionf)
|
8258c451de6d94936d15d772fcbf3da24f6fb4b2 | byceps/services/email/transfer/models.py | byceps/services/email/transfer/models.py | """
byceps.services.email.transfer.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from __future__ import annotations
from dataclasses import dataclass
from email.utils import formataddr
from ....typing import BrandID
@dataclass(frozen=True)
class Sender:
address: str
name: str
def format(self):
"""Format the sender as a string value suitable for an e-mail header."""
realname = self.name if self.name else False
return formataddr((realname, self.address))
@dataclass(frozen=True)
class EmailConfig:
brand_id: BrandID
sender: Sender
contact_address: str
@dataclass(frozen=True)
class Message:
sender: Sender
recipients: list[str]
subject: str
body: str
| """
byceps.services.email.transfer.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from __future__ import annotations
from dataclasses import dataclass
from email.utils import formataddr
from typing import Optional
from ....typing import BrandID
@dataclass(frozen=True)
class Sender:
address: str
name: Optional[str]
def format(self):
"""Format the sender as a string value suitable for an e-mail header."""
return formataddr((self.name, self.address))
@dataclass(frozen=True)
class EmailConfig:
brand_id: BrandID
sender: Sender
contact_address: str
@dataclass(frozen=True)
class Message:
sender: Sender
recipients: list[str]
subject: str
body: str
| Make sender address name field optional | Make sender address name field optional
| Python | bsd-3-clause | homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps | """
byceps.services.email.transfer.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from __future__ import annotations
from dataclasses import dataclass
from email.utils import formataddr
from ....typing import BrandID
@dataclass(frozen=True)
class Sender:
address: str
name: str
def format(self):
"""Format the sender as a string value suitable for an e-mail header."""
realname = self.name if self.name else False
return formataddr((realname, self.address))
@dataclass(frozen=True)
class EmailConfig:
brand_id: BrandID
sender: Sender
contact_address: str
@dataclass(frozen=True)
class Message:
sender: Sender
recipients: list[str]
subject: str
body: str
Make sender address name field optional | """
byceps.services.email.transfer.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from __future__ import annotations
from dataclasses import dataclass
from email.utils import formataddr
from typing import Optional
from ....typing import BrandID
@dataclass(frozen=True)
class Sender:
address: str
name: Optional[str]
def format(self):
"""Format the sender as a string value suitable for an e-mail header."""
return formataddr((self.name, self.address))
@dataclass(frozen=True)
class EmailConfig:
brand_id: BrandID
sender: Sender
contact_address: str
@dataclass(frozen=True)
class Message:
sender: Sender
recipients: list[str]
subject: str
body: str
| <commit_before>"""
byceps.services.email.transfer.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from __future__ import annotations
from dataclasses import dataclass
from email.utils import formataddr
from ....typing import BrandID
@dataclass(frozen=True)
class Sender:
address: str
name: str
def format(self):
"""Format the sender as a string value suitable for an e-mail header."""
realname = self.name if self.name else False
return formataddr((realname, self.address))
@dataclass(frozen=True)
class EmailConfig:
brand_id: BrandID
sender: Sender
contact_address: str
@dataclass(frozen=True)
class Message:
sender: Sender
recipients: list[str]
subject: str
body: str
<commit_msg>Make sender address name field optional<commit_after> | """
byceps.services.email.transfer.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from __future__ import annotations
from dataclasses import dataclass
from email.utils import formataddr
from typing import Optional
from ....typing import BrandID
@dataclass(frozen=True)
class Sender:
address: str
name: Optional[str]
def format(self):
"""Format the sender as a string value suitable for an e-mail header."""
return formataddr((self.name, self.address))
@dataclass(frozen=True)
class EmailConfig:
brand_id: BrandID
sender: Sender
contact_address: str
@dataclass(frozen=True)
class Message:
sender: Sender
recipients: list[str]
subject: str
body: str
| """
byceps.services.email.transfer.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from __future__ import annotations
from dataclasses import dataclass
from email.utils import formataddr
from ....typing import BrandID
@dataclass(frozen=True)
class Sender:
address: str
name: str
def format(self):
"""Format the sender as a string value suitable for an e-mail header."""
realname = self.name if self.name else False
return formataddr((realname, self.address))
@dataclass(frozen=True)
class EmailConfig:
brand_id: BrandID
sender: Sender
contact_address: str
@dataclass(frozen=True)
class Message:
sender: Sender
recipients: list[str]
subject: str
body: str
Make sender address name field optional"""
byceps.services.email.transfer.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from __future__ import annotations
from dataclasses import dataclass
from email.utils import formataddr
from typing import Optional
from ....typing import BrandID
@dataclass(frozen=True)
class Sender:
address: str
name: Optional[str]
def format(self):
"""Format the sender as a string value suitable for an e-mail header."""
return formataddr((self.name, self.address))
@dataclass(frozen=True)
class EmailConfig:
brand_id: BrandID
sender: Sender
contact_address: str
@dataclass(frozen=True)
class Message:
sender: Sender
recipients: list[str]
subject: str
body: str
| <commit_before>"""
byceps.services.email.transfer.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from __future__ import annotations
from dataclasses import dataclass
from email.utils import formataddr
from ....typing import BrandID
@dataclass(frozen=True)
class Sender:
address: str
name: str
def format(self):
"""Format the sender as a string value suitable for an e-mail header."""
realname = self.name if self.name else False
return formataddr((realname, self.address))
@dataclass(frozen=True)
class EmailConfig:
brand_id: BrandID
sender: Sender
contact_address: str
@dataclass(frozen=True)
class Message:
sender: Sender
recipients: list[str]
subject: str
body: str
<commit_msg>Make sender address name field optional<commit_after>"""
byceps.services.email.transfer.models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from __future__ import annotations
from dataclasses import dataclass
from email.utils import formataddr
from typing import Optional
from ....typing import BrandID
@dataclass(frozen=True)
class Sender:
address: str
name: Optional[str]
def format(self):
"""Format the sender as a string value suitable for an e-mail header."""
return formataddr((self.name, self.address))
@dataclass(frozen=True)
class EmailConfig:
brand_id: BrandID
sender: Sender
contact_address: str
@dataclass(frozen=True)
class Message:
sender: Sender
recipients: list[str]
subject: str
body: str
|
791e03258c53379dde587a4bf0c05e0d2bc053ad | test_tbselenium.py | test_tbselenium.py | #!/usr/bin/env python2.7
import os
import site
import sys
sys.path.append(os.path.join(os.getcwd(), 'tor-browser-selenium'))
# site.addsitedir(path.join(getcwd(), 'tor-browser-selenium'))
from tbselenium.tbdriver import TorBrowserDriver
with TorBrowserDriver('~/.tb-stable/tor-browser_en-US/') as driver:
driver.get('https://check.torproject.org')
sleep(1) # stay one second in the page
| #!/usr/bin/env python
# NOTICE: this is only working right now because I'm working from a dirty
# submodule where I've implemented this
# https://github.com/fowlslegs/tor-browser-selenium/commit/8f7c88871735fc86ee0209595e718ea03841ffee
# commit
import os
import site
site.addsitedir(os.path.join(os.getcwd(), 'tor-browser-selenium'))
from tbselenium.tbdriver import TorBrowserDriver
home_dir = os.path.expanduser('~')
tbb_path = os.path.join(home_dir, 'tbb', 'tor-browser_en-US')
tbb_fx_path = os.path.join(tbb_path, 'Browser', 'firefox')
tbb_profile_path = os.path.join(tbb_path, 'Browser', 'TorBrowser', 'Data',
'Browser')
logfile_path = os.path.join(home_dir, 'FingerprintSecureDrop', 'logging',
'firefox.log')
with TorBrowserDriver(tbb_path=tbb_path,
tbb_logfile_path=logfile_path) as driver:
driver.get('https://check.torproject.org')
time.sleep(1) # stay one second in the page
| Fix test to work with patched tbdriver.py (see NOTICE in diff) | Fix test to work with patched tbdriver.py (see NOTICE in diff)
| Python | agpl-3.0 | freedomofpress/fingerprint-securedrop,freedomofpress/FingerprintSecureDrop,freedomofpress/fingerprint-securedrop,freedomofpress/FingerprintSecureDrop,freedomofpress/fingerprint-securedrop | #!/usr/bin/env python2.7
import os
import site
import sys
sys.path.append(os.path.join(os.getcwd(), 'tor-browser-selenium'))
# site.addsitedir(path.join(getcwd(), 'tor-browser-selenium'))
from tbselenium.tbdriver import TorBrowserDriver
with TorBrowserDriver('~/.tb-stable/tor-browser_en-US/') as driver:
driver.get('https://check.torproject.org')
sleep(1) # stay one second in the page
Fix test to work with patched tbdriver.py (see NOTICE in diff) | #!/usr/bin/env python
# NOTICE: this is only working right now because I'm working from a dirty
# submodule where I've implemented this
# https://github.com/fowlslegs/tor-browser-selenium/commit/8f7c88871735fc86ee0209595e718ea03841ffee
# commit
import os
import site
site.addsitedir(os.path.join(os.getcwd(), 'tor-browser-selenium'))
from tbselenium.tbdriver import TorBrowserDriver
home_dir = os.path.expanduser('~')
tbb_path = os.path.join(home_dir, 'tbb', 'tor-browser_en-US')
tbb_fx_path = os.path.join(tbb_path, 'Browser', 'firefox')
tbb_profile_path = os.path.join(tbb_path, 'Browser', 'TorBrowser', 'Data',
'Browser')
logfile_path = os.path.join(home_dir, 'FingerprintSecureDrop', 'logging',
'firefox.log')
with TorBrowserDriver(tbb_path=tbb_path,
tbb_logfile_path=logfile_path) as driver:
driver.get('https://check.torproject.org')
time.sleep(1) # stay one second in the page
| <commit_before>#!/usr/bin/env python2.7
import os
import site
import sys
sys.path.append(os.path.join(os.getcwd(), 'tor-browser-selenium'))
# site.addsitedir(path.join(getcwd(), 'tor-browser-selenium'))
from tbselenium.tbdriver import TorBrowserDriver
with TorBrowserDriver('~/.tb-stable/tor-browser_en-US/') as driver:
driver.get('https://check.torproject.org')
sleep(1) # stay one second in the page
<commit_msg>Fix test to work with patched tbdriver.py (see NOTICE in diff)<commit_after> | #!/usr/bin/env python
# NOTICE: this is only working right now because I'm working from a dirty
# submodule where I've implemented this
# https://github.com/fowlslegs/tor-browser-selenium/commit/8f7c88871735fc86ee0209595e718ea03841ffee
# commit
import os
import site
site.addsitedir(os.path.join(os.getcwd(), 'tor-browser-selenium'))
from tbselenium.tbdriver import TorBrowserDriver
home_dir = os.path.expanduser('~')
tbb_path = os.path.join(home_dir, 'tbb', 'tor-browser_en-US')
tbb_fx_path = os.path.join(tbb_path, 'Browser', 'firefox')
tbb_profile_path = os.path.join(tbb_path, 'Browser', 'TorBrowser', 'Data',
'Browser')
logfile_path = os.path.join(home_dir, 'FingerprintSecureDrop', 'logging',
'firefox.log')
with TorBrowserDriver(tbb_path=tbb_path,
tbb_logfile_path=logfile_path) as driver:
driver.get('https://check.torproject.org')
time.sleep(1) # stay one second in the page
| #!/usr/bin/env python2.7
import os
import site
import sys
sys.path.append(os.path.join(os.getcwd(), 'tor-browser-selenium'))
# site.addsitedir(path.join(getcwd(), 'tor-browser-selenium'))
from tbselenium.tbdriver import TorBrowserDriver
with TorBrowserDriver('~/.tb-stable/tor-browser_en-US/') as driver:
driver.get('https://check.torproject.org')
sleep(1) # stay one second in the page
Fix test to work with patched tbdriver.py (see NOTICE in diff)#!/usr/bin/env python
# NOTICE: this is only working right now because I'm working from a dirty
# submodule where I've implemented this
# https://github.com/fowlslegs/tor-browser-selenium/commit/8f7c88871735fc86ee0209595e718ea03841ffee
# commit
import os
import site
site.addsitedir(os.path.join(os.getcwd(), 'tor-browser-selenium'))
from tbselenium.tbdriver import TorBrowserDriver
home_dir = os.path.expanduser('~')
tbb_path = os.path.join(home_dir, 'tbb', 'tor-browser_en-US')
tbb_fx_path = os.path.join(tbb_path, 'Browser', 'firefox')
tbb_profile_path = os.path.join(tbb_path, 'Browser', 'TorBrowser', 'Data',
'Browser')
logfile_path = os.path.join(home_dir, 'FingerprintSecureDrop', 'logging',
'firefox.log')
with TorBrowserDriver(tbb_path=tbb_path,
tbb_logfile_path=logfile_path) as driver:
driver.get('https://check.torproject.org')
time.sleep(1) # stay one second in the page
| <commit_before>#!/usr/bin/env python2.7
import os
import site
import sys
sys.path.append(os.path.join(os.getcwd(), 'tor-browser-selenium'))
# site.addsitedir(path.join(getcwd(), 'tor-browser-selenium'))
from tbselenium.tbdriver import TorBrowserDriver
with TorBrowserDriver('~/.tb-stable/tor-browser_en-US/') as driver:
driver.get('https://check.torproject.org')
sleep(1) # stay one second in the page
<commit_msg>Fix test to work with patched tbdriver.py (see NOTICE in diff)<commit_after>#!/usr/bin/env python
# NOTICE: this is only working right now because I'm working from a dirty
# submodule where I've implemented this
# https://github.com/fowlslegs/tor-browser-selenium/commit/8f7c88871735fc86ee0209595e718ea03841ffee
# commit
import os
import site
site.addsitedir(os.path.join(os.getcwd(), 'tor-browser-selenium'))
from tbselenium.tbdriver import TorBrowserDriver
home_dir = os.path.expanduser('~')
tbb_path = os.path.join(home_dir, 'tbb', 'tor-browser_en-US')
tbb_fx_path = os.path.join(tbb_path, 'Browser', 'firefox')
tbb_profile_path = os.path.join(tbb_path, 'Browser', 'TorBrowser', 'Data',
'Browser')
logfile_path = os.path.join(home_dir, 'FingerprintSecureDrop', 'logging',
'firefox.log')
with TorBrowserDriver(tbb_path=tbb_path,
tbb_logfile_path=logfile_path) as driver:
driver.get('https://check.torproject.org')
time.sleep(1) # stay one second in the page
|
e525a819724f149186b5b156520afe2549e5902a | UliEngineering/Electronics/Power.py | UliEngineering/Electronics/Power.py | #!/usr/bin/env python3
"""
Utilities to compute the power of a device
"""
from UliEngineering.EngineerIO import normalize_numeric
from UliEngineering.Units import Unit
import numpy as np
__all__ = ["current_by_power", "power_by_current_and_voltage"]
def current_by_power(power="25 W", voltage="230 V") -> Unit("A"):
"""
Given a device's power (or RMS power) and the voltage (or RMS voltage)
it runs on, compute how much current it will draw.
"""
power = normalize_numeric(power)
voltage = normalize_numeric(voltage)
return power / voltage
def power_by_current_and_voltage(current="1.0 A", voltage="230 V") -> Unit("W"):
"""
Given a device's current (or RMS current) and the voltage (or RMS current)
it runs on, compute its power
"""
current = normalize_numeric(current)
voltage = normalize_numeric(voltage)
return current * voltage
| #!/usr/bin/env python3
"""
Utilities to compute the power of a device
"""
from UliEngineering.EngineerIO import normalize_numeric
from UliEngineering.Units import Unit
__all__ = ["current_by_power", "power_by_current_and_voltage"]
def current_by_power(power="25 W", voltage="230 V") -> Unit("A"):
"""
Given a device's power (or RMS power) and the voltage (or RMS voltage)
it runs on, compute how much current it will draw.
"""
power = normalize_numeric(power)
voltage = normalize_numeric(voltage)
return power / voltage
def power_by_current_and_voltage(current="1.0 A", voltage="230 V") -> Unit("W"):
"""
Given a device's current (or RMS current) and the voltage (or RMS current)
it runs on, compute its power
"""
current = normalize_numeric(current)
voltage = normalize_numeric(voltage)
return current * voltage
| Remove unused numpy input (codacy) | Remove unused numpy input (codacy)
| Python | apache-2.0 | ulikoehler/UliEngineering | #!/usr/bin/env python3
"""
Utilities to compute the power of a device
"""
from UliEngineering.EngineerIO import normalize_numeric
from UliEngineering.Units import Unit
import numpy as np
__all__ = ["current_by_power", "power_by_current_and_voltage"]
def current_by_power(power="25 W", voltage="230 V") -> Unit("A"):
"""
Given a device's power (or RMS power) and the voltage (or RMS voltage)
it runs on, compute how much current it will draw.
"""
power = normalize_numeric(power)
voltage = normalize_numeric(voltage)
return power / voltage
def power_by_current_and_voltage(current="1.0 A", voltage="230 V") -> Unit("W"):
"""
Given a device's current (or RMS current) and the voltage (or RMS current)
it runs on, compute its power
"""
current = normalize_numeric(current)
voltage = normalize_numeric(voltage)
return current * voltage
Remove unused numpy input (codacy) | #!/usr/bin/env python3
"""
Utilities to compute the power of a device
"""
from UliEngineering.EngineerIO import normalize_numeric
from UliEngineering.Units import Unit
__all__ = ["current_by_power", "power_by_current_and_voltage"]
def current_by_power(power="25 W", voltage="230 V") -> Unit("A"):
"""
Given a device's power (or RMS power) and the voltage (or RMS voltage)
it runs on, compute how much current it will draw.
"""
power = normalize_numeric(power)
voltage = normalize_numeric(voltage)
return power / voltage
def power_by_current_and_voltage(current="1.0 A", voltage="230 V") -> Unit("W"):
"""
Given a device's current (or RMS current) and the voltage (or RMS current)
it runs on, compute its power
"""
current = normalize_numeric(current)
voltage = normalize_numeric(voltage)
return current * voltage
| <commit_before>#!/usr/bin/env python3
"""
Utilities to compute the power of a device
"""
from UliEngineering.EngineerIO import normalize_numeric
from UliEngineering.Units import Unit
import numpy as np
__all__ = ["current_by_power", "power_by_current_and_voltage"]
def current_by_power(power="25 W", voltage="230 V") -> Unit("A"):
"""
Given a device's power (or RMS power) and the voltage (or RMS voltage)
it runs on, compute how much current it will draw.
"""
power = normalize_numeric(power)
voltage = normalize_numeric(voltage)
return power / voltage
def power_by_current_and_voltage(current="1.0 A", voltage="230 V") -> Unit("W"):
"""
Given a device's current (or RMS current) and the voltage (or RMS current)
it runs on, compute its power
"""
current = normalize_numeric(current)
voltage = normalize_numeric(voltage)
return current * voltage
<commit_msg>Remove unused numpy input (codacy)<commit_after> | #!/usr/bin/env python3
"""
Utilities to compute the power of a device
"""
from UliEngineering.EngineerIO import normalize_numeric
from UliEngineering.Units import Unit
__all__ = ["current_by_power", "power_by_current_and_voltage"]
def current_by_power(power="25 W", voltage="230 V") -> Unit("A"):
"""
Given a device's power (or RMS power) and the voltage (or RMS voltage)
it runs on, compute how much current it will draw.
"""
power = normalize_numeric(power)
voltage = normalize_numeric(voltage)
return power / voltage
def power_by_current_and_voltage(current="1.0 A", voltage="230 V") -> Unit("W"):
"""
Given a device's current (or RMS current) and the voltage (or RMS current)
it runs on, compute its power
"""
current = normalize_numeric(current)
voltage = normalize_numeric(voltage)
return current * voltage
| #!/usr/bin/env python3
"""
Utilities to compute the power of a device
"""
from UliEngineering.EngineerIO import normalize_numeric
from UliEngineering.Units import Unit
import numpy as np
__all__ = ["current_by_power", "power_by_current_and_voltage"]
def current_by_power(power="25 W", voltage="230 V") -> Unit("A"):
"""
Given a device's power (or RMS power) and the voltage (or RMS voltage)
it runs on, compute how much current it will draw.
"""
power = normalize_numeric(power)
voltage = normalize_numeric(voltage)
return power / voltage
def power_by_current_and_voltage(current="1.0 A", voltage="230 V") -> Unit("W"):
"""
Given a device's current (or RMS current) and the voltage (or RMS current)
it runs on, compute its power
"""
current = normalize_numeric(current)
voltage = normalize_numeric(voltage)
return current * voltage
Remove unused numpy input (codacy)#!/usr/bin/env python3
"""
Utilities to compute the power of a device
"""
from UliEngineering.EngineerIO import normalize_numeric
from UliEngineering.Units import Unit
__all__ = ["current_by_power", "power_by_current_and_voltage"]
def current_by_power(power="25 W", voltage="230 V") -> Unit("A"):
"""
Given a device's power (or RMS power) and the voltage (or RMS voltage)
it runs on, compute how much current it will draw.
"""
power = normalize_numeric(power)
voltage = normalize_numeric(voltage)
return power / voltage
def power_by_current_and_voltage(current="1.0 A", voltage="230 V") -> Unit("W"):
"""
Given a device's current (or RMS current) and the voltage (or RMS current)
it runs on, compute its power
"""
current = normalize_numeric(current)
voltage = normalize_numeric(voltage)
return current * voltage
| <commit_before>#!/usr/bin/env python3
"""
Utilities to compute the power of a device
"""
from UliEngineering.EngineerIO import normalize_numeric
from UliEngineering.Units import Unit
import numpy as np
__all__ = ["current_by_power", "power_by_current_and_voltage"]
def current_by_power(power="25 W", voltage="230 V") -> Unit("A"):
"""
Given a device's power (or RMS power) and the voltage (or RMS voltage)
it runs on, compute how much current it will draw.
"""
power = normalize_numeric(power)
voltage = normalize_numeric(voltage)
return power / voltage
def power_by_current_and_voltage(current="1.0 A", voltage="230 V") -> Unit("W"):
"""
Given a device's current (or RMS current) and the voltage (or RMS current)
it runs on, compute its power
"""
current = normalize_numeric(current)
voltage = normalize_numeric(voltage)
return current * voltage
<commit_msg>Remove unused numpy input (codacy)<commit_after>#!/usr/bin/env python3
"""
Utilities to compute the power of a device
"""
from UliEngineering.EngineerIO import normalize_numeric
from UliEngineering.Units import Unit
__all__ = ["current_by_power", "power_by_current_and_voltage"]
def current_by_power(power="25 W", voltage="230 V") -> Unit("A"):
"""
Given a device's power (or RMS power) and the voltage (or RMS voltage)
it runs on, compute how much current it will draw.
"""
power = normalize_numeric(power)
voltage = normalize_numeric(voltage)
return power / voltage
def power_by_current_and_voltage(current="1.0 A", voltage="230 V") -> Unit("W"):
"""
Given a device's current (or RMS current) and the voltage (or RMS current)
it runs on, compute its power
"""
current = normalize_numeric(current)
voltage = normalize_numeric(voltage)
return current * voltage
|
79f7d8052333fcace914fa27ea2deb5f0d7cdbfc | readers/models.py | readers/models.py | from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.db import models
from model_utils.models import TimeStampedModel
class Reader(TimeStampedModel):
IBOOKS = 'iBooks'
KINDLE = 'Kindle'
TYPES = (
(IBOOKS, IBOOKS),
(KINDLE, KINDLE),
)
name = models.CharField(max_length=100, null=True)
user = models.ForeignKey(User)
kind = models.CharField(max_length=10, choices=TYPES)
email = models.EmailField()
def __str__(self):
return "{}'s {}".format(self.user, self.kind)
def get_absolute_url(self):
return reverse("reader-detail", kwargs={'pk': self.id})
| from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.db import models
from model_utils.models import TimeStampedModel
class Reader(TimeStampedModel):
IBOOKS = 'iBooks'
KINDLE = 'Kindle'
TYPES = (
(IBOOKS, 'iBooks (.epub, .pdf)'),
(KINDLE, 'Kindle (.mobi, .pdf)'),
)
name = models.CharField(max_length=100, null=True)
user = models.ForeignKey(User)
kind = models.CharField(max_length=10, choices=TYPES)
email = models.EmailField()
def __str__(self):
return "{}'s {}".format(self.user, self.kind)
def get_absolute_url(self):
return reverse("reader-detail", kwargs={'pk': self.id})
| Make what reader can handle what clearer | Make what reader can handle what clearer
| Python | mit | phildini/bockus,phildini/bockus,phildini/bockus | from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.db import models
from model_utils.models import TimeStampedModel
class Reader(TimeStampedModel):
IBOOKS = 'iBooks'
KINDLE = 'Kindle'
TYPES = (
(IBOOKS, IBOOKS),
(KINDLE, KINDLE),
)
name = models.CharField(max_length=100, null=True)
user = models.ForeignKey(User)
kind = models.CharField(max_length=10, choices=TYPES)
email = models.EmailField()
def __str__(self):
return "{}'s {}".format(self.user, self.kind)
def get_absolute_url(self):
return reverse("reader-detail", kwargs={'pk': self.id})
Make what reader can handle what clearer | from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.db import models
from model_utils.models import TimeStampedModel
class Reader(TimeStampedModel):
IBOOKS = 'iBooks'
KINDLE = 'Kindle'
TYPES = (
(IBOOKS, 'iBooks (.epub, .pdf)'),
(KINDLE, 'Kindle (.mobi, .pdf)'),
)
name = models.CharField(max_length=100, null=True)
user = models.ForeignKey(User)
kind = models.CharField(max_length=10, choices=TYPES)
email = models.EmailField()
def __str__(self):
return "{}'s {}".format(self.user, self.kind)
def get_absolute_url(self):
return reverse("reader-detail", kwargs={'pk': self.id})
| <commit_before>from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.db import models
from model_utils.models import TimeStampedModel
class Reader(TimeStampedModel):
IBOOKS = 'iBooks'
KINDLE = 'Kindle'
TYPES = (
(IBOOKS, IBOOKS),
(KINDLE, KINDLE),
)
name = models.CharField(max_length=100, null=True)
user = models.ForeignKey(User)
kind = models.CharField(max_length=10, choices=TYPES)
email = models.EmailField()
def __str__(self):
return "{}'s {}".format(self.user, self.kind)
def get_absolute_url(self):
return reverse("reader-detail", kwargs={'pk': self.id})
<commit_msg>Make what reader can handle what clearer<commit_after> | from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.db import models
from model_utils.models import TimeStampedModel
class Reader(TimeStampedModel):
IBOOKS = 'iBooks'
KINDLE = 'Kindle'
TYPES = (
(IBOOKS, 'iBooks (.epub, .pdf)'),
(KINDLE, 'Kindle (.mobi, .pdf)'),
)
name = models.CharField(max_length=100, null=True)
user = models.ForeignKey(User)
kind = models.CharField(max_length=10, choices=TYPES)
email = models.EmailField()
def __str__(self):
return "{}'s {}".format(self.user, self.kind)
def get_absolute_url(self):
return reverse("reader-detail", kwargs={'pk': self.id})
| from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.db import models
from model_utils.models import TimeStampedModel
class Reader(TimeStampedModel):
IBOOKS = 'iBooks'
KINDLE = 'Kindle'
TYPES = (
(IBOOKS, IBOOKS),
(KINDLE, KINDLE),
)
name = models.CharField(max_length=100, null=True)
user = models.ForeignKey(User)
kind = models.CharField(max_length=10, choices=TYPES)
email = models.EmailField()
def __str__(self):
return "{}'s {}".format(self.user, self.kind)
def get_absolute_url(self):
return reverse("reader-detail", kwargs={'pk': self.id})
Make what reader can handle what clearerfrom django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.db import models
from model_utils.models import TimeStampedModel
class Reader(TimeStampedModel):
IBOOKS = 'iBooks'
KINDLE = 'Kindle'
TYPES = (
(IBOOKS, 'iBooks (.epub, .pdf)'),
(KINDLE, 'Kindle (.mobi, .pdf)'),
)
name = models.CharField(max_length=100, null=True)
user = models.ForeignKey(User)
kind = models.CharField(max_length=10, choices=TYPES)
email = models.EmailField()
def __str__(self):
return "{}'s {}".format(self.user, self.kind)
def get_absolute_url(self):
return reverse("reader-detail", kwargs={'pk': self.id})
| <commit_before>from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.db import models
from model_utils.models import TimeStampedModel
class Reader(TimeStampedModel):
IBOOKS = 'iBooks'
KINDLE = 'Kindle'
TYPES = (
(IBOOKS, IBOOKS),
(KINDLE, KINDLE),
)
name = models.CharField(max_length=100, null=True)
user = models.ForeignKey(User)
kind = models.CharField(max_length=10, choices=TYPES)
email = models.EmailField()
def __str__(self):
return "{}'s {}".format(self.user, self.kind)
def get_absolute_url(self):
return reverse("reader-detail", kwargs={'pk': self.id})
<commit_msg>Make what reader can handle what clearer<commit_after>from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.db import models
from model_utils.models import TimeStampedModel
class Reader(TimeStampedModel):
IBOOKS = 'iBooks'
KINDLE = 'Kindle'
TYPES = (
(IBOOKS, 'iBooks (.epub, .pdf)'),
(KINDLE, 'Kindle (.mobi, .pdf)'),
)
name = models.CharField(max_length=100, null=True)
user = models.ForeignKey(User)
kind = models.CharField(max_length=10, choices=TYPES)
email = models.EmailField()
def __str__(self):
return "{}'s {}".format(self.user, self.kind)
def get_absolute_url(self):
return reverse("reader-detail", kwargs={'pk': self.id})
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.