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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4d3d00559dbb3a5aed2b58053f0d7471ef538a1c
|
src/python/condor/examples/squares.py
|
src/python/condor/examples/squares.py
|
import condor
def square(x):
return x**2
def main():
jobs = [(square, [x]) for x in range(16)]
def finished(task, result):
print task.args, result
condor.do(jobs, 4, finished)
if __name__ == "__main__":
condor.enable_default_logging() # XXX
main()
|
import condor
def square(x):
return x**2
def main():
jobs = [(square, [x]) for x in range(16)]
def done(task, result):
print task.args, result
condor.do(jobs, 4, done)
if __name__ == "__main__":
main()
|
Remove logging setup from example.
|
Remove logging setup from example.
|
Python
|
mit
|
borg-project/utcondor,borg-project/utcondor
|
import condor
def square(x):
return x**2
def main():
jobs = [(square, [x]) for x in range(16)]
def finished(task, result):
print task.args, result
condor.do(jobs, 4, finished)
if __name__ == "__main__":
condor.enable_default_logging() # XXX
main()
Remove logging setup from example.
|
import condor
def square(x):
return x**2
def main():
jobs = [(square, [x]) for x in range(16)]
def done(task, result):
print task.args, result
condor.do(jobs, 4, done)
if __name__ == "__main__":
main()
|
<commit_before>import condor
def square(x):
return x**2
def main():
jobs = [(square, [x]) for x in range(16)]
def finished(task, result):
print task.args, result
condor.do(jobs, 4, finished)
if __name__ == "__main__":
condor.enable_default_logging() # XXX
main()
<commit_msg>Remove logging setup from example.<commit_after>
|
import condor
def square(x):
return x**2
def main():
jobs = [(square, [x]) for x in range(16)]
def done(task, result):
print task.args, result
condor.do(jobs, 4, done)
if __name__ == "__main__":
main()
|
import condor
def square(x):
return x**2
def main():
jobs = [(square, [x]) for x in range(16)]
def finished(task, result):
print task.args, result
condor.do(jobs, 4, finished)
if __name__ == "__main__":
condor.enable_default_logging() # XXX
main()
Remove logging setup from example.import condor
def square(x):
return x**2
def main():
jobs = [(square, [x]) for x in range(16)]
def done(task, result):
print task.args, result
condor.do(jobs, 4, done)
if __name__ == "__main__":
main()
|
<commit_before>import condor
def square(x):
return x**2
def main():
jobs = [(square, [x]) for x in range(16)]
def finished(task, result):
print task.args, result
condor.do(jobs, 4, finished)
if __name__ == "__main__":
condor.enable_default_logging() # XXX
main()
<commit_msg>Remove logging setup from example.<commit_after>import condor
def square(x):
return x**2
def main():
jobs = [(square, [x]) for x in range(16)]
def done(task, result):
print task.args, result
condor.do(jobs, 4, done)
if __name__ == "__main__":
main()
|
be17c81115549f0f7ec69b0cf023165d88fea6d4
|
sql/tests/__init__.py
|
sql/tests/__init__.py
|
#This file is part of python-sql. The COPYRIGHT file at the top level of
#this repository contains the full copyright notices and license terms.
import sys
import os
import unittest
import doctest
import sql
here = os.path.dirname(__file__)
def test_suite():
suite = additional_tests()
loader = unittest.TestLoader()
for fn in os.listdir(here):
if fn.startswith('test') and fn.endswith('.py'):
modname = 'sql.tests.' + fn[:-3]
__import__(modname)
module = sys.modules[modname]
suite.addTests(loader.loadTestsFromModule(module))
return suite
def additional_tests():
suite = unittest.TestSuite()
for mod in (sql,):
suite.addTest(doctest.DocTestSuite(mod))
return suite
def main():
suite = test_suite()
runner = unittest.TextTestRunner()
runner.run(suite)
if __name__ == '__main__':
sys.path.insert(0, os.path.dirname(os.path.dirname(
os.path.dirname(os.path.abspath(__file__)))))
main()
|
#This file is part of python-sql. The COPYRIGHT file at the top level of
#this repository contains the full copyright notices and license terms.
import sys
import os
import unittest
import doctest
import sql
here = os.path.dirname(__file__)
readme = os.path.normpath(os.path.join(here, '..', '..', 'README'))
def test_suite():
suite = additional_tests()
loader = unittest.TestLoader()
for fn in os.listdir(here):
if fn.startswith('test') and fn.endswith('.py'):
modname = 'sql.tests.' + fn[:-3]
__import__(modname)
module = sys.modules[modname]
suite.addTests(loader.loadTestsFromModule(module))
return suite
def additional_tests():
suite = unittest.TestSuite()
for mod in (sql,):
suite.addTest(doctest.DocTestSuite(mod))
if os.path.isfile(readme):
suite.addTest(doctest.DocFileSuite(readme, module_relative=False,
tearDown=lambda t: sql.Flavor.set(sql.Flavor())))
return suite
def main():
suite = test_suite()
runner = unittest.TextTestRunner()
runner.run(suite)
if __name__ == '__main__':
sys.path.insert(0, os.path.dirname(os.path.dirname(
os.path.dirname(os.path.abspath(__file__)))))
main()
|
Add README to test suite
|
Add README to test suite
|
Python
|
bsd-3-clause
|
vmuriart/python-sql
|
#This file is part of python-sql. The COPYRIGHT file at the top level of
#this repository contains the full copyright notices and license terms.
import sys
import os
import unittest
import doctest
import sql
here = os.path.dirname(__file__)
def test_suite():
suite = additional_tests()
loader = unittest.TestLoader()
for fn in os.listdir(here):
if fn.startswith('test') and fn.endswith('.py'):
modname = 'sql.tests.' + fn[:-3]
__import__(modname)
module = sys.modules[modname]
suite.addTests(loader.loadTestsFromModule(module))
return suite
def additional_tests():
suite = unittest.TestSuite()
for mod in (sql,):
suite.addTest(doctest.DocTestSuite(mod))
return suite
def main():
suite = test_suite()
runner = unittest.TextTestRunner()
runner.run(suite)
if __name__ == '__main__':
sys.path.insert(0, os.path.dirname(os.path.dirname(
os.path.dirname(os.path.abspath(__file__)))))
main()
Add README to test suite
|
#This file is part of python-sql. The COPYRIGHT file at the top level of
#this repository contains the full copyright notices and license terms.
import sys
import os
import unittest
import doctest
import sql
here = os.path.dirname(__file__)
readme = os.path.normpath(os.path.join(here, '..', '..', 'README'))
def test_suite():
suite = additional_tests()
loader = unittest.TestLoader()
for fn in os.listdir(here):
if fn.startswith('test') and fn.endswith('.py'):
modname = 'sql.tests.' + fn[:-3]
__import__(modname)
module = sys.modules[modname]
suite.addTests(loader.loadTestsFromModule(module))
return suite
def additional_tests():
suite = unittest.TestSuite()
for mod in (sql,):
suite.addTest(doctest.DocTestSuite(mod))
if os.path.isfile(readme):
suite.addTest(doctest.DocFileSuite(readme, module_relative=False,
tearDown=lambda t: sql.Flavor.set(sql.Flavor())))
return suite
def main():
suite = test_suite()
runner = unittest.TextTestRunner()
runner.run(suite)
if __name__ == '__main__':
sys.path.insert(0, os.path.dirname(os.path.dirname(
os.path.dirname(os.path.abspath(__file__)))))
main()
|
<commit_before>#This file is part of python-sql. The COPYRIGHT file at the top level of
#this repository contains the full copyright notices and license terms.
import sys
import os
import unittest
import doctest
import sql
here = os.path.dirname(__file__)
def test_suite():
suite = additional_tests()
loader = unittest.TestLoader()
for fn in os.listdir(here):
if fn.startswith('test') and fn.endswith('.py'):
modname = 'sql.tests.' + fn[:-3]
__import__(modname)
module = sys.modules[modname]
suite.addTests(loader.loadTestsFromModule(module))
return suite
def additional_tests():
suite = unittest.TestSuite()
for mod in (sql,):
suite.addTest(doctest.DocTestSuite(mod))
return suite
def main():
suite = test_suite()
runner = unittest.TextTestRunner()
runner.run(suite)
if __name__ == '__main__':
sys.path.insert(0, os.path.dirname(os.path.dirname(
os.path.dirname(os.path.abspath(__file__)))))
main()
<commit_msg>Add README to test suite<commit_after>
|
#This file is part of python-sql. The COPYRIGHT file at the top level of
#this repository contains the full copyright notices and license terms.
import sys
import os
import unittest
import doctest
import sql
here = os.path.dirname(__file__)
readme = os.path.normpath(os.path.join(here, '..', '..', 'README'))
def test_suite():
suite = additional_tests()
loader = unittest.TestLoader()
for fn in os.listdir(here):
if fn.startswith('test') and fn.endswith('.py'):
modname = 'sql.tests.' + fn[:-3]
__import__(modname)
module = sys.modules[modname]
suite.addTests(loader.loadTestsFromModule(module))
return suite
def additional_tests():
suite = unittest.TestSuite()
for mod in (sql,):
suite.addTest(doctest.DocTestSuite(mod))
if os.path.isfile(readme):
suite.addTest(doctest.DocFileSuite(readme, module_relative=False,
tearDown=lambda t: sql.Flavor.set(sql.Flavor())))
return suite
def main():
suite = test_suite()
runner = unittest.TextTestRunner()
runner.run(suite)
if __name__ == '__main__':
sys.path.insert(0, os.path.dirname(os.path.dirname(
os.path.dirname(os.path.abspath(__file__)))))
main()
|
#This file is part of python-sql. The COPYRIGHT file at the top level of
#this repository contains the full copyright notices and license terms.
import sys
import os
import unittest
import doctest
import sql
here = os.path.dirname(__file__)
def test_suite():
suite = additional_tests()
loader = unittest.TestLoader()
for fn in os.listdir(here):
if fn.startswith('test') and fn.endswith('.py'):
modname = 'sql.tests.' + fn[:-3]
__import__(modname)
module = sys.modules[modname]
suite.addTests(loader.loadTestsFromModule(module))
return suite
def additional_tests():
suite = unittest.TestSuite()
for mod in (sql,):
suite.addTest(doctest.DocTestSuite(mod))
return suite
def main():
suite = test_suite()
runner = unittest.TextTestRunner()
runner.run(suite)
if __name__ == '__main__':
sys.path.insert(0, os.path.dirname(os.path.dirname(
os.path.dirname(os.path.abspath(__file__)))))
main()
Add README to test suite#This file is part of python-sql. The COPYRIGHT file at the top level of
#this repository contains the full copyright notices and license terms.
import sys
import os
import unittest
import doctest
import sql
here = os.path.dirname(__file__)
readme = os.path.normpath(os.path.join(here, '..', '..', 'README'))
def test_suite():
suite = additional_tests()
loader = unittest.TestLoader()
for fn in os.listdir(here):
if fn.startswith('test') and fn.endswith('.py'):
modname = 'sql.tests.' + fn[:-3]
__import__(modname)
module = sys.modules[modname]
suite.addTests(loader.loadTestsFromModule(module))
return suite
def additional_tests():
suite = unittest.TestSuite()
for mod in (sql,):
suite.addTest(doctest.DocTestSuite(mod))
if os.path.isfile(readme):
suite.addTest(doctest.DocFileSuite(readme, module_relative=False,
tearDown=lambda t: sql.Flavor.set(sql.Flavor())))
return suite
def main():
suite = test_suite()
runner = unittest.TextTestRunner()
runner.run(suite)
if __name__ == '__main__':
sys.path.insert(0, os.path.dirname(os.path.dirname(
os.path.dirname(os.path.abspath(__file__)))))
main()
|
<commit_before>#This file is part of python-sql. The COPYRIGHT file at the top level of
#this repository contains the full copyright notices and license terms.
import sys
import os
import unittest
import doctest
import sql
here = os.path.dirname(__file__)
def test_suite():
suite = additional_tests()
loader = unittest.TestLoader()
for fn in os.listdir(here):
if fn.startswith('test') and fn.endswith('.py'):
modname = 'sql.tests.' + fn[:-3]
__import__(modname)
module = sys.modules[modname]
suite.addTests(loader.loadTestsFromModule(module))
return suite
def additional_tests():
suite = unittest.TestSuite()
for mod in (sql,):
suite.addTest(doctest.DocTestSuite(mod))
return suite
def main():
suite = test_suite()
runner = unittest.TextTestRunner()
runner.run(suite)
if __name__ == '__main__':
sys.path.insert(0, os.path.dirname(os.path.dirname(
os.path.dirname(os.path.abspath(__file__)))))
main()
<commit_msg>Add README to test suite<commit_after>#This file is part of python-sql. The COPYRIGHT file at the top level of
#this repository contains the full copyright notices and license terms.
import sys
import os
import unittest
import doctest
import sql
here = os.path.dirname(__file__)
readme = os.path.normpath(os.path.join(here, '..', '..', 'README'))
def test_suite():
suite = additional_tests()
loader = unittest.TestLoader()
for fn in os.listdir(here):
if fn.startswith('test') and fn.endswith('.py'):
modname = 'sql.tests.' + fn[:-3]
__import__(modname)
module = sys.modules[modname]
suite.addTests(loader.loadTestsFromModule(module))
return suite
def additional_tests():
suite = unittest.TestSuite()
for mod in (sql,):
suite.addTest(doctest.DocTestSuite(mod))
if os.path.isfile(readme):
suite.addTest(doctest.DocFileSuite(readme, module_relative=False,
tearDown=lambda t: sql.Flavor.set(sql.Flavor())))
return suite
def main():
suite = test_suite()
runner = unittest.TextTestRunner()
runner.run(suite)
if __name__ == '__main__':
sys.path.insert(0, os.path.dirname(os.path.dirname(
os.path.dirname(os.path.abspath(__file__)))))
main()
|
ee726835fd0431f211b7c3f298568e56065a2951
|
provider/constants.py
|
provider/constants.py
|
from datetime import timedelta
from django.conf import settings
CONFIDENTIAL = 0
PUBLIC = 1
CLIENT_TYPES = (
(CONFIDENTIAL, "Confidential (Web applications)"),
(PUBLIC, "Public (Native and JS applications)")
)
RESPONSE_TYPE_CHOICES = getattr(settings, 'OAUTH_RESPONSE_TYPE_CHOICES', ("code", "token"))
READ = 1 << 1
WRITE = 1 << 2
READ_WRITE = READ | WRITE
DEFAULT_SCOPES = (
(READ, 'read'),
(WRITE, 'write'),
(READ_WRITE, 'read-write'),
)
SCOPES = getattr(settings, 'OAUTH_SCOPES', DEFAULT_SCOPES)
EXPIRE_DELTA = getattr(settings, 'OAUTH_EXPIRE_DELTA', timedelta(days=365))
EXPIRE_CODE_DELTA = getattr(settings, 'OAUTH_EXPIRE_CODE_DELTA', timedelta(seconds=10 * 60))
ENFORCE_SECURE = getattr(settings, 'OAUTH_ENFORCE_SECURE', False)
ENFORCE_CLIENT_SECURE = getattr(settings, 'OAUTH_ENFORCE_CLIENT_SECURE', True)
SESSION_KEY = getattr(settings, 'OAUTH_SESSION_KEY', 'oauth')
|
from datetime import timedelta
from django.conf import settings
CONFIDENTIAL = 0
PUBLIC = 1
CLIENT_TYPES = (
(CONFIDENTIAL, "Confidential (Web applications)"),
(PUBLIC, "Public (Native and JS applications)")
)
RESPONSE_TYPE_CHOICES = getattr(settings, 'OAUTH_RESPONSE_TYPE_CHOICES', ("code", "token"))
READ = 1 << 1
WRITE = 1 << 2
READ_WRITE = READ | WRITE
DEFAULT_SCOPES = (
(READ, 'read'),
(WRITE, 'write'),
(READ_WRITE, 'read+write'),
)
SCOPES = getattr(settings, 'OAUTH_SCOPES', DEFAULT_SCOPES)
EXPIRE_DELTA = getattr(settings, 'OAUTH_EXPIRE_DELTA', timedelta(days=365))
EXPIRE_CODE_DELTA = getattr(settings, 'OAUTH_EXPIRE_CODE_DELTA', timedelta(seconds=10 * 60))
ENFORCE_SECURE = getattr(settings, 'OAUTH_ENFORCE_SECURE', False)
ENFORCE_CLIENT_SECURE = getattr(settings, 'OAUTH_ENFORCE_CLIENT_SECURE', True)
SESSION_KEY = getattr(settings, 'OAUTH_SESSION_KEY', 'oauth')
|
Change 'read-write' scope to 'read+write'.
|
Change 'read-write' scope to 'read+write'.
|
Python
|
mit
|
archen/django-oauth2-provider,sprintly/django-oauth2-provider,ifanrx/django-oauth2-provider,ifanrx/django-oauth2-provider,aschem/django-oauth2-provider,opbeat/django-oauth2-provider,epyx-src/django-oauth2-provider,ministryofjustice/django-oauth2-provider,glassfordm/django-oauth2-provider,bleib1dj/django-oauth2-provider,glassfordm/django-oauth2-provider,caffeinehit/django-oauth2-provider,maroux/django-oauth2-provider,fyber/django-oauth2-provider,tutumcloud/django-oauth2-provider,bleib1dj/django-oauth2-provider,maroux/django-oauth2-provider,stormsherpa/django-oauth2-provider,depop/django-oauth2-provider,stormsherpa/django-oauth2-provider,numan/django-oauth2-provider,glassfordm/django-oauth2-provider,stormsherpa/django-oauth2-provider,tutumcloud/django-oauth2-provider,archen/django-oauth2-provider,edx/django-oauth2-provider,numan/django-oauth2-provider,Kalyzee/django-oauth2-provider,sprintly/django-oauth2-provider,maroux/django-oauth2-provider,edx/django-oauth2-provider,fyber/django-oauth2-provider,caffeinehit/django-oauth2-provider,bleib1dj/django-oauth2-provider,opbeat/django-oauth2-provider,Kalyzee/django-oauth2-provider,depop/django-oauth2-provider,depop/django-oauth2-provider,aschem/django-oauth2-provider,Kalyzee/django-oauth2-provider,ifanrx/django-oauth2-provider,aschem/django-oauth2-provider,ministryofjustice/django-oauth2-provider,epyx-src/django-oauth2-provider
|
from datetime import timedelta
from django.conf import settings
CONFIDENTIAL = 0
PUBLIC = 1
CLIENT_TYPES = (
(CONFIDENTIAL, "Confidential (Web applications)"),
(PUBLIC, "Public (Native and JS applications)")
)
RESPONSE_TYPE_CHOICES = getattr(settings, 'OAUTH_RESPONSE_TYPE_CHOICES', ("code", "token"))
READ = 1 << 1
WRITE = 1 << 2
READ_WRITE = READ | WRITE
DEFAULT_SCOPES = (
(READ, 'read'),
(WRITE, 'write'),
(READ_WRITE, 'read-write'),
)
SCOPES = getattr(settings, 'OAUTH_SCOPES', DEFAULT_SCOPES)
EXPIRE_DELTA = getattr(settings, 'OAUTH_EXPIRE_DELTA', timedelta(days=365))
EXPIRE_CODE_DELTA = getattr(settings, 'OAUTH_EXPIRE_CODE_DELTA', timedelta(seconds=10 * 60))
ENFORCE_SECURE = getattr(settings, 'OAUTH_ENFORCE_SECURE', False)
ENFORCE_CLIENT_SECURE = getattr(settings, 'OAUTH_ENFORCE_CLIENT_SECURE', True)
SESSION_KEY = getattr(settings, 'OAUTH_SESSION_KEY', 'oauth')
Change 'read-write' scope to 'read+write'.
|
from datetime import timedelta
from django.conf import settings
CONFIDENTIAL = 0
PUBLIC = 1
CLIENT_TYPES = (
(CONFIDENTIAL, "Confidential (Web applications)"),
(PUBLIC, "Public (Native and JS applications)")
)
RESPONSE_TYPE_CHOICES = getattr(settings, 'OAUTH_RESPONSE_TYPE_CHOICES', ("code", "token"))
READ = 1 << 1
WRITE = 1 << 2
READ_WRITE = READ | WRITE
DEFAULT_SCOPES = (
(READ, 'read'),
(WRITE, 'write'),
(READ_WRITE, 'read+write'),
)
SCOPES = getattr(settings, 'OAUTH_SCOPES', DEFAULT_SCOPES)
EXPIRE_DELTA = getattr(settings, 'OAUTH_EXPIRE_DELTA', timedelta(days=365))
EXPIRE_CODE_DELTA = getattr(settings, 'OAUTH_EXPIRE_CODE_DELTA', timedelta(seconds=10 * 60))
ENFORCE_SECURE = getattr(settings, 'OAUTH_ENFORCE_SECURE', False)
ENFORCE_CLIENT_SECURE = getattr(settings, 'OAUTH_ENFORCE_CLIENT_SECURE', True)
SESSION_KEY = getattr(settings, 'OAUTH_SESSION_KEY', 'oauth')
|
<commit_before>from datetime import timedelta
from django.conf import settings
CONFIDENTIAL = 0
PUBLIC = 1
CLIENT_TYPES = (
(CONFIDENTIAL, "Confidential (Web applications)"),
(PUBLIC, "Public (Native and JS applications)")
)
RESPONSE_TYPE_CHOICES = getattr(settings, 'OAUTH_RESPONSE_TYPE_CHOICES', ("code", "token"))
READ = 1 << 1
WRITE = 1 << 2
READ_WRITE = READ | WRITE
DEFAULT_SCOPES = (
(READ, 'read'),
(WRITE, 'write'),
(READ_WRITE, 'read-write'),
)
SCOPES = getattr(settings, 'OAUTH_SCOPES', DEFAULT_SCOPES)
EXPIRE_DELTA = getattr(settings, 'OAUTH_EXPIRE_DELTA', timedelta(days=365))
EXPIRE_CODE_DELTA = getattr(settings, 'OAUTH_EXPIRE_CODE_DELTA', timedelta(seconds=10 * 60))
ENFORCE_SECURE = getattr(settings, 'OAUTH_ENFORCE_SECURE', False)
ENFORCE_CLIENT_SECURE = getattr(settings, 'OAUTH_ENFORCE_CLIENT_SECURE', True)
SESSION_KEY = getattr(settings, 'OAUTH_SESSION_KEY', 'oauth')
<commit_msg>Change 'read-write' scope to 'read+write'.<commit_after>
|
from datetime import timedelta
from django.conf import settings
CONFIDENTIAL = 0
PUBLIC = 1
CLIENT_TYPES = (
(CONFIDENTIAL, "Confidential (Web applications)"),
(PUBLIC, "Public (Native and JS applications)")
)
RESPONSE_TYPE_CHOICES = getattr(settings, 'OAUTH_RESPONSE_TYPE_CHOICES', ("code", "token"))
READ = 1 << 1
WRITE = 1 << 2
READ_WRITE = READ | WRITE
DEFAULT_SCOPES = (
(READ, 'read'),
(WRITE, 'write'),
(READ_WRITE, 'read+write'),
)
SCOPES = getattr(settings, 'OAUTH_SCOPES', DEFAULT_SCOPES)
EXPIRE_DELTA = getattr(settings, 'OAUTH_EXPIRE_DELTA', timedelta(days=365))
EXPIRE_CODE_DELTA = getattr(settings, 'OAUTH_EXPIRE_CODE_DELTA', timedelta(seconds=10 * 60))
ENFORCE_SECURE = getattr(settings, 'OAUTH_ENFORCE_SECURE', False)
ENFORCE_CLIENT_SECURE = getattr(settings, 'OAUTH_ENFORCE_CLIENT_SECURE', True)
SESSION_KEY = getattr(settings, 'OAUTH_SESSION_KEY', 'oauth')
|
from datetime import timedelta
from django.conf import settings
CONFIDENTIAL = 0
PUBLIC = 1
CLIENT_TYPES = (
(CONFIDENTIAL, "Confidential (Web applications)"),
(PUBLIC, "Public (Native and JS applications)")
)
RESPONSE_TYPE_CHOICES = getattr(settings, 'OAUTH_RESPONSE_TYPE_CHOICES', ("code", "token"))
READ = 1 << 1
WRITE = 1 << 2
READ_WRITE = READ | WRITE
DEFAULT_SCOPES = (
(READ, 'read'),
(WRITE, 'write'),
(READ_WRITE, 'read-write'),
)
SCOPES = getattr(settings, 'OAUTH_SCOPES', DEFAULT_SCOPES)
EXPIRE_DELTA = getattr(settings, 'OAUTH_EXPIRE_DELTA', timedelta(days=365))
EXPIRE_CODE_DELTA = getattr(settings, 'OAUTH_EXPIRE_CODE_DELTA', timedelta(seconds=10 * 60))
ENFORCE_SECURE = getattr(settings, 'OAUTH_ENFORCE_SECURE', False)
ENFORCE_CLIENT_SECURE = getattr(settings, 'OAUTH_ENFORCE_CLIENT_SECURE', True)
SESSION_KEY = getattr(settings, 'OAUTH_SESSION_KEY', 'oauth')
Change 'read-write' scope to 'read+write'.from datetime import timedelta
from django.conf import settings
CONFIDENTIAL = 0
PUBLIC = 1
CLIENT_TYPES = (
(CONFIDENTIAL, "Confidential (Web applications)"),
(PUBLIC, "Public (Native and JS applications)")
)
RESPONSE_TYPE_CHOICES = getattr(settings, 'OAUTH_RESPONSE_TYPE_CHOICES', ("code", "token"))
READ = 1 << 1
WRITE = 1 << 2
READ_WRITE = READ | WRITE
DEFAULT_SCOPES = (
(READ, 'read'),
(WRITE, 'write'),
(READ_WRITE, 'read+write'),
)
SCOPES = getattr(settings, 'OAUTH_SCOPES', DEFAULT_SCOPES)
EXPIRE_DELTA = getattr(settings, 'OAUTH_EXPIRE_DELTA', timedelta(days=365))
EXPIRE_CODE_DELTA = getattr(settings, 'OAUTH_EXPIRE_CODE_DELTA', timedelta(seconds=10 * 60))
ENFORCE_SECURE = getattr(settings, 'OAUTH_ENFORCE_SECURE', False)
ENFORCE_CLIENT_SECURE = getattr(settings, 'OAUTH_ENFORCE_CLIENT_SECURE', True)
SESSION_KEY = getattr(settings, 'OAUTH_SESSION_KEY', 'oauth')
|
<commit_before>from datetime import timedelta
from django.conf import settings
CONFIDENTIAL = 0
PUBLIC = 1
CLIENT_TYPES = (
(CONFIDENTIAL, "Confidential (Web applications)"),
(PUBLIC, "Public (Native and JS applications)")
)
RESPONSE_TYPE_CHOICES = getattr(settings, 'OAUTH_RESPONSE_TYPE_CHOICES', ("code", "token"))
READ = 1 << 1
WRITE = 1 << 2
READ_WRITE = READ | WRITE
DEFAULT_SCOPES = (
(READ, 'read'),
(WRITE, 'write'),
(READ_WRITE, 'read-write'),
)
SCOPES = getattr(settings, 'OAUTH_SCOPES', DEFAULT_SCOPES)
EXPIRE_DELTA = getattr(settings, 'OAUTH_EXPIRE_DELTA', timedelta(days=365))
EXPIRE_CODE_DELTA = getattr(settings, 'OAUTH_EXPIRE_CODE_DELTA', timedelta(seconds=10 * 60))
ENFORCE_SECURE = getattr(settings, 'OAUTH_ENFORCE_SECURE', False)
ENFORCE_CLIENT_SECURE = getattr(settings, 'OAUTH_ENFORCE_CLIENT_SECURE', True)
SESSION_KEY = getattr(settings, 'OAUTH_SESSION_KEY', 'oauth')
<commit_msg>Change 'read-write' scope to 'read+write'.<commit_after>from datetime import timedelta
from django.conf import settings
CONFIDENTIAL = 0
PUBLIC = 1
CLIENT_TYPES = (
(CONFIDENTIAL, "Confidential (Web applications)"),
(PUBLIC, "Public (Native and JS applications)")
)
RESPONSE_TYPE_CHOICES = getattr(settings, 'OAUTH_RESPONSE_TYPE_CHOICES', ("code", "token"))
READ = 1 << 1
WRITE = 1 << 2
READ_WRITE = READ | WRITE
DEFAULT_SCOPES = (
(READ, 'read'),
(WRITE, 'write'),
(READ_WRITE, 'read+write'),
)
SCOPES = getattr(settings, 'OAUTH_SCOPES', DEFAULT_SCOPES)
EXPIRE_DELTA = getattr(settings, 'OAUTH_EXPIRE_DELTA', timedelta(days=365))
EXPIRE_CODE_DELTA = getattr(settings, 'OAUTH_EXPIRE_CODE_DELTA', timedelta(seconds=10 * 60))
ENFORCE_SECURE = getattr(settings, 'OAUTH_ENFORCE_SECURE', False)
ENFORCE_CLIENT_SECURE = getattr(settings, 'OAUTH_ENFORCE_CLIENT_SECURE', True)
SESSION_KEY = getattr(settings, 'OAUTH_SESSION_KEY', 'oauth')
|
185e8db639f7f74702f9d741f7c01eeebce73d50
|
comics/aggregator/feedparser.py
|
comics/aggregator/feedparser.py
|
from __future__ import absolute_import
import datetime as dt
import feedparser
from types import StringTypes
from comics.aggregator.lxmlparser import LxmlParser
class FeedParser(object):
def __init__(self, url):
self.raw_feed = feedparser.parse(url)
def for_date(self, date):
return [Entry(e) for e in self.raw_feed.entries
if e.updated_parsed and dt.date(*e.updated_parsed[:3]) == date]
def all(self):
return [Entry(e) for e in self.raw_feed.entries]
class Entry(object):
def __init__(self, entry):
self.raw_entry = entry
if 'summary' in entry:
self.summary = self.html(entry.summary)
if 'content' in entry:
self.content0 = self.html(entry.content[0].value)
def __getattr__(self, name):
return getattr(self.raw_entry, name)
def html(self, string):
return LxmlParser(string=string)
def has_tag(self, tag):
def matches_tag(item):
return item.term == tag
if ('tags' in self.raw_entry and
len(filter(matches_tag, self.raw_entry['tags']))):
return True
return False
|
from __future__ import absolute_import
import datetime as dt
import feedparser
from types import StringTypes
from comics.aggregator.lxmlparser import LxmlParser
class FeedParser(object):
def __init__(self, url):
self.raw_feed = feedparser.parse(url)
def for_date(self, date):
return [Entry(e) for e in self.raw_feed.entries
if e.updated_parsed and dt.date(*e.updated_parsed[:3]) == date]
def all(self):
return [Entry(e) for e in self.raw_feed.entries]
class Entry(object):
def __init__(self, entry):
self.raw_entry = entry
if 'summary' in entry:
self.summary = self.html(entry.summary)
if 'content' in entry:
self.content0 = self.html(entry.content[0].value)
def __getattr__(self, name):
return getattr(self.raw_entry, name)
def html(self, string):
return LxmlParser(string=string)
def has_tag(self, tag):
if ('tags' in self.raw_entry and
len(filter(lambda t: t.term == tag, self.raw_entry.tags))):
return True
return False
|
Replace inner function with lambda in FeedParser.has_tag()
|
Replace inner function with lambda in FeedParser.has_tag()
|
Python
|
agpl-3.0
|
datagutten/comics,klette/comics,jodal/comics,datagutten/comics,datagutten/comics,jodal/comics,klette/comics,klette/comics,jodal/comics,datagutten/comics,jodal/comics
|
from __future__ import absolute_import
import datetime as dt
import feedparser
from types import StringTypes
from comics.aggregator.lxmlparser import LxmlParser
class FeedParser(object):
def __init__(self, url):
self.raw_feed = feedparser.parse(url)
def for_date(self, date):
return [Entry(e) for e in self.raw_feed.entries
if e.updated_parsed and dt.date(*e.updated_parsed[:3]) == date]
def all(self):
return [Entry(e) for e in self.raw_feed.entries]
class Entry(object):
def __init__(self, entry):
self.raw_entry = entry
if 'summary' in entry:
self.summary = self.html(entry.summary)
if 'content' in entry:
self.content0 = self.html(entry.content[0].value)
def __getattr__(self, name):
return getattr(self.raw_entry, name)
def html(self, string):
return LxmlParser(string=string)
def has_tag(self, tag):
def matches_tag(item):
return item.term == tag
if ('tags' in self.raw_entry and
len(filter(matches_tag, self.raw_entry['tags']))):
return True
return False
Replace inner function with lambda in FeedParser.has_tag()
|
from __future__ import absolute_import
import datetime as dt
import feedparser
from types import StringTypes
from comics.aggregator.lxmlparser import LxmlParser
class FeedParser(object):
def __init__(self, url):
self.raw_feed = feedparser.parse(url)
def for_date(self, date):
return [Entry(e) for e in self.raw_feed.entries
if e.updated_parsed and dt.date(*e.updated_parsed[:3]) == date]
def all(self):
return [Entry(e) for e in self.raw_feed.entries]
class Entry(object):
def __init__(self, entry):
self.raw_entry = entry
if 'summary' in entry:
self.summary = self.html(entry.summary)
if 'content' in entry:
self.content0 = self.html(entry.content[0].value)
def __getattr__(self, name):
return getattr(self.raw_entry, name)
def html(self, string):
return LxmlParser(string=string)
def has_tag(self, tag):
if ('tags' in self.raw_entry and
len(filter(lambda t: t.term == tag, self.raw_entry.tags))):
return True
return False
|
<commit_before>from __future__ import absolute_import
import datetime as dt
import feedparser
from types import StringTypes
from comics.aggregator.lxmlparser import LxmlParser
class FeedParser(object):
def __init__(self, url):
self.raw_feed = feedparser.parse(url)
def for_date(self, date):
return [Entry(e) for e in self.raw_feed.entries
if e.updated_parsed and dt.date(*e.updated_parsed[:3]) == date]
def all(self):
return [Entry(e) for e in self.raw_feed.entries]
class Entry(object):
def __init__(self, entry):
self.raw_entry = entry
if 'summary' in entry:
self.summary = self.html(entry.summary)
if 'content' in entry:
self.content0 = self.html(entry.content[0].value)
def __getattr__(self, name):
return getattr(self.raw_entry, name)
def html(self, string):
return LxmlParser(string=string)
def has_tag(self, tag):
def matches_tag(item):
return item.term == tag
if ('tags' in self.raw_entry and
len(filter(matches_tag, self.raw_entry['tags']))):
return True
return False
<commit_msg>Replace inner function with lambda in FeedParser.has_tag()<commit_after>
|
from __future__ import absolute_import
import datetime as dt
import feedparser
from types import StringTypes
from comics.aggregator.lxmlparser import LxmlParser
class FeedParser(object):
def __init__(self, url):
self.raw_feed = feedparser.parse(url)
def for_date(self, date):
return [Entry(e) for e in self.raw_feed.entries
if e.updated_parsed and dt.date(*e.updated_parsed[:3]) == date]
def all(self):
return [Entry(e) for e in self.raw_feed.entries]
class Entry(object):
def __init__(self, entry):
self.raw_entry = entry
if 'summary' in entry:
self.summary = self.html(entry.summary)
if 'content' in entry:
self.content0 = self.html(entry.content[0].value)
def __getattr__(self, name):
return getattr(self.raw_entry, name)
def html(self, string):
return LxmlParser(string=string)
def has_tag(self, tag):
if ('tags' in self.raw_entry and
len(filter(lambda t: t.term == tag, self.raw_entry.tags))):
return True
return False
|
from __future__ import absolute_import
import datetime as dt
import feedparser
from types import StringTypes
from comics.aggregator.lxmlparser import LxmlParser
class FeedParser(object):
def __init__(self, url):
self.raw_feed = feedparser.parse(url)
def for_date(self, date):
return [Entry(e) for e in self.raw_feed.entries
if e.updated_parsed and dt.date(*e.updated_parsed[:3]) == date]
def all(self):
return [Entry(e) for e in self.raw_feed.entries]
class Entry(object):
def __init__(self, entry):
self.raw_entry = entry
if 'summary' in entry:
self.summary = self.html(entry.summary)
if 'content' in entry:
self.content0 = self.html(entry.content[0].value)
def __getattr__(self, name):
return getattr(self.raw_entry, name)
def html(self, string):
return LxmlParser(string=string)
def has_tag(self, tag):
def matches_tag(item):
return item.term == tag
if ('tags' in self.raw_entry and
len(filter(matches_tag, self.raw_entry['tags']))):
return True
return False
Replace inner function with lambda in FeedParser.has_tag()from __future__ import absolute_import
import datetime as dt
import feedparser
from types import StringTypes
from comics.aggregator.lxmlparser import LxmlParser
class FeedParser(object):
def __init__(self, url):
self.raw_feed = feedparser.parse(url)
def for_date(self, date):
return [Entry(e) for e in self.raw_feed.entries
if e.updated_parsed and dt.date(*e.updated_parsed[:3]) == date]
def all(self):
return [Entry(e) for e in self.raw_feed.entries]
class Entry(object):
def __init__(self, entry):
self.raw_entry = entry
if 'summary' in entry:
self.summary = self.html(entry.summary)
if 'content' in entry:
self.content0 = self.html(entry.content[0].value)
def __getattr__(self, name):
return getattr(self.raw_entry, name)
def html(self, string):
return LxmlParser(string=string)
def has_tag(self, tag):
if ('tags' in self.raw_entry and
len(filter(lambda t: t.term == tag, self.raw_entry.tags))):
return True
return False
|
<commit_before>from __future__ import absolute_import
import datetime as dt
import feedparser
from types import StringTypes
from comics.aggregator.lxmlparser import LxmlParser
class FeedParser(object):
def __init__(self, url):
self.raw_feed = feedparser.parse(url)
def for_date(self, date):
return [Entry(e) for e in self.raw_feed.entries
if e.updated_parsed and dt.date(*e.updated_parsed[:3]) == date]
def all(self):
return [Entry(e) for e in self.raw_feed.entries]
class Entry(object):
def __init__(self, entry):
self.raw_entry = entry
if 'summary' in entry:
self.summary = self.html(entry.summary)
if 'content' in entry:
self.content0 = self.html(entry.content[0].value)
def __getattr__(self, name):
return getattr(self.raw_entry, name)
def html(self, string):
return LxmlParser(string=string)
def has_tag(self, tag):
def matches_tag(item):
return item.term == tag
if ('tags' in self.raw_entry and
len(filter(matches_tag, self.raw_entry['tags']))):
return True
return False
<commit_msg>Replace inner function with lambda in FeedParser.has_tag()<commit_after>from __future__ import absolute_import
import datetime as dt
import feedparser
from types import StringTypes
from comics.aggregator.lxmlparser import LxmlParser
class FeedParser(object):
def __init__(self, url):
self.raw_feed = feedparser.parse(url)
def for_date(self, date):
return [Entry(e) for e in self.raw_feed.entries
if e.updated_parsed and dt.date(*e.updated_parsed[:3]) == date]
def all(self):
return [Entry(e) for e in self.raw_feed.entries]
class Entry(object):
def __init__(self, entry):
self.raw_entry = entry
if 'summary' in entry:
self.summary = self.html(entry.summary)
if 'content' in entry:
self.content0 = self.html(entry.content[0].value)
def __getattr__(self, name):
return getattr(self.raw_entry, name)
def html(self, string):
return LxmlParser(string=string)
def has_tag(self, tag):
if ('tags' in self.raw_entry and
len(filter(lambda t: t.term == tag, self.raw_entry.tags))):
return True
return False
|
bdec8d649863d09e04f763038dde0230c715abfe
|
bot/action/core/command/usagemessage.py
|
bot/action/core/command/usagemessage.py
|
from bot.action.util.textformat import FormattedText
class CommandUsageMessage:
@classmethod
def get_formatted_usage_text(cls, command, args=None, description=""):
text = FormattedText().bold("Usage").newline()
if type(args) is list:
text.concat(FormattedText().newline().join((cls.__get_command_with_args(command, arg) for arg in args)))
else:
text.concat(cls.__get_command_with_args(command, args))
if description:
if not isinstance(description, FormattedText):
description = FormattedText().normal(description)
text.newline().newline().concat(description)
return text
@classmethod
def get_usage_message(cls, command, args=None, description=""):
return cls.get_formatted_usage_text(command, args, description).build_message()
@staticmethod
def __get_command_with_args(command, args):
text = command
if args:
text += " " + args
return FormattedText().code_inline(text)
|
from bot.action.util.textformat import FormattedText, FormattedTextFactory
class CommandUsageMessage:
@classmethod
def get_formatted_usage_text(cls, command, args=None, description=""):
text = FormattedTextFactory.get_new_markdown().bold("Usage").newline()
if type(args) is list:
text.concat(
FormattedTextFactory.get_new_markdown().newline().join(
(cls.__get_command_with_args(command, arg) for arg in args)
)
)
else:
text.concat(cls.__get_command_with_args(command, args))
if description:
if not isinstance(description, FormattedText):
description = FormattedTextFactory.get_new_markdown().raw(description)
text.newline().newline().concat(description)
return text
@classmethod
def get_usage_message(cls, command, args=None, description=""):
return cls.get_formatted_usage_text(command, args, description).build_message()
@staticmethod
def __get_command_with_args(command, args):
text = command
if args:
text += " " + args
return FormattedTextFactory.get_new_markdown().code_inline(text)
|
Fix CommandUsageMessage to allow backward compatibility with already existing raw Markdown formatted text
|
Fix CommandUsageMessage to allow backward compatibility with already existing raw Markdown formatted text
|
Python
|
agpl-3.0
|
alvarogzp/telegram-bot,alvarogzp/telegram-bot
|
from bot.action.util.textformat import FormattedText
class CommandUsageMessage:
@classmethod
def get_formatted_usage_text(cls, command, args=None, description=""):
text = FormattedText().bold("Usage").newline()
if type(args) is list:
text.concat(FormattedText().newline().join((cls.__get_command_with_args(command, arg) for arg in args)))
else:
text.concat(cls.__get_command_with_args(command, args))
if description:
if not isinstance(description, FormattedText):
description = FormattedText().normal(description)
text.newline().newline().concat(description)
return text
@classmethod
def get_usage_message(cls, command, args=None, description=""):
return cls.get_formatted_usage_text(command, args, description).build_message()
@staticmethod
def __get_command_with_args(command, args):
text = command
if args:
text += " " + args
return FormattedText().code_inline(text)
Fix CommandUsageMessage to allow backward compatibility with already existing raw Markdown formatted text
|
from bot.action.util.textformat import FormattedText, FormattedTextFactory
class CommandUsageMessage:
@classmethod
def get_formatted_usage_text(cls, command, args=None, description=""):
text = FormattedTextFactory.get_new_markdown().bold("Usage").newline()
if type(args) is list:
text.concat(
FormattedTextFactory.get_new_markdown().newline().join(
(cls.__get_command_with_args(command, arg) for arg in args)
)
)
else:
text.concat(cls.__get_command_with_args(command, args))
if description:
if not isinstance(description, FormattedText):
description = FormattedTextFactory.get_new_markdown().raw(description)
text.newline().newline().concat(description)
return text
@classmethod
def get_usage_message(cls, command, args=None, description=""):
return cls.get_formatted_usage_text(command, args, description).build_message()
@staticmethod
def __get_command_with_args(command, args):
text = command
if args:
text += " " + args
return FormattedTextFactory.get_new_markdown().code_inline(text)
|
<commit_before>from bot.action.util.textformat import FormattedText
class CommandUsageMessage:
@classmethod
def get_formatted_usage_text(cls, command, args=None, description=""):
text = FormattedText().bold("Usage").newline()
if type(args) is list:
text.concat(FormattedText().newline().join((cls.__get_command_with_args(command, arg) for arg in args)))
else:
text.concat(cls.__get_command_with_args(command, args))
if description:
if not isinstance(description, FormattedText):
description = FormattedText().normal(description)
text.newline().newline().concat(description)
return text
@classmethod
def get_usage_message(cls, command, args=None, description=""):
return cls.get_formatted_usage_text(command, args, description).build_message()
@staticmethod
def __get_command_with_args(command, args):
text = command
if args:
text += " " + args
return FormattedText().code_inline(text)
<commit_msg>Fix CommandUsageMessage to allow backward compatibility with already existing raw Markdown formatted text<commit_after>
|
from bot.action.util.textformat import FormattedText, FormattedTextFactory
class CommandUsageMessage:
@classmethod
def get_formatted_usage_text(cls, command, args=None, description=""):
text = FormattedTextFactory.get_new_markdown().bold("Usage").newline()
if type(args) is list:
text.concat(
FormattedTextFactory.get_new_markdown().newline().join(
(cls.__get_command_with_args(command, arg) for arg in args)
)
)
else:
text.concat(cls.__get_command_with_args(command, args))
if description:
if not isinstance(description, FormattedText):
description = FormattedTextFactory.get_new_markdown().raw(description)
text.newline().newline().concat(description)
return text
@classmethod
def get_usage_message(cls, command, args=None, description=""):
return cls.get_formatted_usage_text(command, args, description).build_message()
@staticmethod
def __get_command_with_args(command, args):
text = command
if args:
text += " " + args
return FormattedTextFactory.get_new_markdown().code_inline(text)
|
from bot.action.util.textformat import FormattedText
class CommandUsageMessage:
@classmethod
def get_formatted_usage_text(cls, command, args=None, description=""):
text = FormattedText().bold("Usage").newline()
if type(args) is list:
text.concat(FormattedText().newline().join((cls.__get_command_with_args(command, arg) for arg in args)))
else:
text.concat(cls.__get_command_with_args(command, args))
if description:
if not isinstance(description, FormattedText):
description = FormattedText().normal(description)
text.newline().newline().concat(description)
return text
@classmethod
def get_usage_message(cls, command, args=None, description=""):
return cls.get_formatted_usage_text(command, args, description).build_message()
@staticmethod
def __get_command_with_args(command, args):
text = command
if args:
text += " " + args
return FormattedText().code_inline(text)
Fix CommandUsageMessage to allow backward compatibility with already existing raw Markdown formatted textfrom bot.action.util.textformat import FormattedText, FormattedTextFactory
class CommandUsageMessage:
@classmethod
def get_formatted_usage_text(cls, command, args=None, description=""):
text = FormattedTextFactory.get_new_markdown().bold("Usage").newline()
if type(args) is list:
text.concat(
FormattedTextFactory.get_new_markdown().newline().join(
(cls.__get_command_with_args(command, arg) for arg in args)
)
)
else:
text.concat(cls.__get_command_with_args(command, args))
if description:
if not isinstance(description, FormattedText):
description = FormattedTextFactory.get_new_markdown().raw(description)
text.newline().newline().concat(description)
return text
@classmethod
def get_usage_message(cls, command, args=None, description=""):
return cls.get_formatted_usage_text(command, args, description).build_message()
@staticmethod
def __get_command_with_args(command, args):
text = command
if args:
text += " " + args
return FormattedTextFactory.get_new_markdown().code_inline(text)
|
<commit_before>from bot.action.util.textformat import FormattedText
class CommandUsageMessage:
@classmethod
def get_formatted_usage_text(cls, command, args=None, description=""):
text = FormattedText().bold("Usage").newline()
if type(args) is list:
text.concat(FormattedText().newline().join((cls.__get_command_with_args(command, arg) for arg in args)))
else:
text.concat(cls.__get_command_with_args(command, args))
if description:
if not isinstance(description, FormattedText):
description = FormattedText().normal(description)
text.newline().newline().concat(description)
return text
@classmethod
def get_usage_message(cls, command, args=None, description=""):
return cls.get_formatted_usage_text(command, args, description).build_message()
@staticmethod
def __get_command_with_args(command, args):
text = command
if args:
text += " " + args
return FormattedText().code_inline(text)
<commit_msg>Fix CommandUsageMessage to allow backward compatibility with already existing raw Markdown formatted text<commit_after>from bot.action.util.textformat import FormattedText, FormattedTextFactory
class CommandUsageMessage:
@classmethod
def get_formatted_usage_text(cls, command, args=None, description=""):
text = FormattedTextFactory.get_new_markdown().bold("Usage").newline()
if type(args) is list:
text.concat(
FormattedTextFactory.get_new_markdown().newline().join(
(cls.__get_command_with_args(command, arg) for arg in args)
)
)
else:
text.concat(cls.__get_command_with_args(command, args))
if description:
if not isinstance(description, FormattedText):
description = FormattedTextFactory.get_new_markdown().raw(description)
text.newline().newline().concat(description)
return text
@classmethod
def get_usage_message(cls, command, args=None, description=""):
return cls.get_formatted_usage_text(command, args, description).build_message()
@staticmethod
def __get_command_with_args(command, args):
text = command
if args:
text += " " + args
return FormattedTextFactory.get_new_markdown().code_inline(text)
|
bfe4d4e5c9952f8064789ebf48d0ed28bb27c152
|
vpython/gs_version.py
|
vpython/gs_version.py
|
from __future__ import print_function
import os
import re
def glowscript_version():
"""
Extract the Glowscript version from the javascript in the data directory.
"""
data_name = 'data'
glowscript_name = 'glow.2.1.min.js'
this_dir = os.path.dirname(os.path.abspath(__file__))
data_dir = os.path.join(this_dir, data_name)
with open(os.path.join(data_dir, glowscript_name)) as f:
contents = f.read()
# Use the non-greedy form of "+" below to ensure we get the shortest
# possible match.
result = re.search('var glowscript=\{version:"(.+?)"\}', contents)
if result:
gs_version = result.group(1)
else:
raise RuntimeError("Could not determine glowscript version.")
return gs_version
|
from __future__ import print_function
import os
from glob import glob
import re
def glowscript_version():
"""
Extract the Glowscript version from the javascript in the data directory.
"""
data_name = 'data'
this_dir = os.path.dirname(os.path.abspath(__file__))
data_dir = os.path.join(this_dir, data_name)
glowscript_file = glob(os.path.join(data_dir, 'glow.*.min.js'))
glowscript_name = glowscript_file[0]
# Use the non-greedy form of "+" below to ensure we get the shortest
# possible match.
result = re.search('glow\.(.+?)\.min\.js', glowscript_name)
if result:
gs_version = result.group(1)
else:
raise RuntimeError("Could not determine glowscript version.")
return gs_version
|
Determine glowscript version from file name
|
Determine glowscript version from file name
|
Python
|
mit
|
BruceSherwood/vpython-jupyter,BruceSherwood/vpython-jupyter,mwcraig/vpython-jupyter,mwcraig/vpython-jupyter,mwcraig/vpython-jupyter,mwcraig/vpython-jupyter,BruceSherwood/vpython-jupyter,BruceSherwood/vpython-jupyter
|
from __future__ import print_function
import os
import re
def glowscript_version():
"""
Extract the Glowscript version from the javascript in the data directory.
"""
data_name = 'data'
glowscript_name = 'glow.2.1.min.js'
this_dir = os.path.dirname(os.path.abspath(__file__))
data_dir = os.path.join(this_dir, data_name)
with open(os.path.join(data_dir, glowscript_name)) as f:
contents = f.read()
# Use the non-greedy form of "+" below to ensure we get the shortest
# possible match.
result = re.search('var glowscript=\{version:"(.+?)"\}', contents)
if result:
gs_version = result.group(1)
else:
raise RuntimeError("Could not determine glowscript version.")
return gs_version
Determine glowscript version from file name
|
from __future__ import print_function
import os
from glob import glob
import re
def glowscript_version():
"""
Extract the Glowscript version from the javascript in the data directory.
"""
data_name = 'data'
this_dir = os.path.dirname(os.path.abspath(__file__))
data_dir = os.path.join(this_dir, data_name)
glowscript_file = glob(os.path.join(data_dir, 'glow.*.min.js'))
glowscript_name = glowscript_file[0]
# Use the non-greedy form of "+" below to ensure we get the shortest
# possible match.
result = re.search('glow\.(.+?)\.min\.js', glowscript_name)
if result:
gs_version = result.group(1)
else:
raise RuntimeError("Could not determine glowscript version.")
return gs_version
|
<commit_before>from __future__ import print_function
import os
import re
def glowscript_version():
"""
Extract the Glowscript version from the javascript in the data directory.
"""
data_name = 'data'
glowscript_name = 'glow.2.1.min.js'
this_dir = os.path.dirname(os.path.abspath(__file__))
data_dir = os.path.join(this_dir, data_name)
with open(os.path.join(data_dir, glowscript_name)) as f:
contents = f.read()
# Use the non-greedy form of "+" below to ensure we get the shortest
# possible match.
result = re.search('var glowscript=\{version:"(.+?)"\}', contents)
if result:
gs_version = result.group(1)
else:
raise RuntimeError("Could not determine glowscript version.")
return gs_version
<commit_msg>Determine glowscript version from file name<commit_after>
|
from __future__ import print_function
import os
from glob import glob
import re
def glowscript_version():
"""
Extract the Glowscript version from the javascript in the data directory.
"""
data_name = 'data'
this_dir = os.path.dirname(os.path.abspath(__file__))
data_dir = os.path.join(this_dir, data_name)
glowscript_file = glob(os.path.join(data_dir, 'glow.*.min.js'))
glowscript_name = glowscript_file[0]
# Use the non-greedy form of "+" below to ensure we get the shortest
# possible match.
result = re.search('glow\.(.+?)\.min\.js', glowscript_name)
if result:
gs_version = result.group(1)
else:
raise RuntimeError("Could not determine glowscript version.")
return gs_version
|
from __future__ import print_function
import os
import re
def glowscript_version():
"""
Extract the Glowscript version from the javascript in the data directory.
"""
data_name = 'data'
glowscript_name = 'glow.2.1.min.js'
this_dir = os.path.dirname(os.path.abspath(__file__))
data_dir = os.path.join(this_dir, data_name)
with open(os.path.join(data_dir, glowscript_name)) as f:
contents = f.read()
# Use the non-greedy form of "+" below to ensure we get the shortest
# possible match.
result = re.search('var glowscript=\{version:"(.+?)"\}', contents)
if result:
gs_version = result.group(1)
else:
raise RuntimeError("Could not determine glowscript version.")
return gs_version
Determine glowscript version from file namefrom __future__ import print_function
import os
from glob import glob
import re
def glowscript_version():
"""
Extract the Glowscript version from the javascript in the data directory.
"""
data_name = 'data'
this_dir = os.path.dirname(os.path.abspath(__file__))
data_dir = os.path.join(this_dir, data_name)
glowscript_file = glob(os.path.join(data_dir, 'glow.*.min.js'))
glowscript_name = glowscript_file[0]
# Use the non-greedy form of "+" below to ensure we get the shortest
# possible match.
result = re.search('glow\.(.+?)\.min\.js', glowscript_name)
if result:
gs_version = result.group(1)
else:
raise RuntimeError("Could not determine glowscript version.")
return gs_version
|
<commit_before>from __future__ import print_function
import os
import re
def glowscript_version():
"""
Extract the Glowscript version from the javascript in the data directory.
"""
data_name = 'data'
glowscript_name = 'glow.2.1.min.js'
this_dir = os.path.dirname(os.path.abspath(__file__))
data_dir = os.path.join(this_dir, data_name)
with open(os.path.join(data_dir, glowscript_name)) as f:
contents = f.read()
# Use the non-greedy form of "+" below to ensure we get the shortest
# possible match.
result = re.search('var glowscript=\{version:"(.+?)"\}', contents)
if result:
gs_version = result.group(1)
else:
raise RuntimeError("Could not determine glowscript version.")
return gs_version
<commit_msg>Determine glowscript version from file name<commit_after>from __future__ import print_function
import os
from glob import glob
import re
def glowscript_version():
"""
Extract the Glowscript version from the javascript in the data directory.
"""
data_name = 'data'
this_dir = os.path.dirname(os.path.abspath(__file__))
data_dir = os.path.join(this_dir, data_name)
glowscript_file = glob(os.path.join(data_dir, 'glow.*.min.js'))
glowscript_name = glowscript_file[0]
# Use the non-greedy form of "+" below to ensure we get the shortest
# possible match.
result = re.search('glow\.(.+?)\.min\.js', glowscript_name)
if result:
gs_version = result.group(1)
else:
raise RuntimeError("Could not determine glowscript version.")
return gs_version
|
66c07964112aab37d56cf61e0a12c9ab3c9bd54e
|
wcontrol/src/forms.py
|
wcontrol/src/forms.py
|
from flask_wtf import FlaskForm
from wtforms import StringField, IntegerField, DecimalField
from wtforms.validators import DataRequired
from app.models import User
class EditForm(FlaskForm):
nickname = StringField('nickname', validators=[DataRequired()])
name = StringField('name', validators=[DataRequired()])
age = IntegerField('age')
height = DecimalField('heighti', places=2)
def __init__(self, original_nickname, *args, **kwargs):
FlaskForm.__init__(self, *args, **kwargs)
self.original_nickname = original_nickname
def validate(self):
if not FlaskForm.validate(self):
return False
if self.nickname.data == self.original_nickname:
return True
user = User.query.filter_by(nickname=self.nickname.data).first()
if user != None:
self.nickname.errors.append('This nickname is already in use. Please chose another one.')
return False
return True
|
from flask_wtf import FlaskForm
from wtforms import StringField, IntegerField, DecimalField
from wtforms.validators import DataRequired
from app.models import User
class EditForm(FlaskForm):
nickname = StringField('nickname', validators=[DataRequired()])
name = StringField('name', validators=[DataRequired()])
age = IntegerField('age')
height = DecimalField('heighti', places=2)
def __init__(self, original_nickname, *args, **kwargs):
FlaskForm.__init__(self, *args, **kwargs)
self.original_nickname = original_nickname
def validate(self):
if not FlaskForm.validate(self):
return False
if self.nickname.data == self.original_nickname:
return True
user = User.query.filter_by(nickname=self.nickname.data).first()
if user:
msg = 'This nickname is already in use. Please chose another one.'
self.nickname.errors.append(msg)
return False
return True
|
Modify to fit with PEP8 standard
|
Modify to fit with PEP8 standard
|
Python
|
mit
|
pahumadad/weight-control,pahumadad/weight-control,pahumadad/weight-control,pahumadad/weight-control
|
from flask_wtf import FlaskForm
from wtforms import StringField, IntegerField, DecimalField
from wtforms.validators import DataRequired
from app.models import User
class EditForm(FlaskForm):
nickname = StringField('nickname', validators=[DataRequired()])
name = StringField('name', validators=[DataRequired()])
age = IntegerField('age')
height = DecimalField('heighti', places=2)
def __init__(self, original_nickname, *args, **kwargs):
FlaskForm.__init__(self, *args, **kwargs)
self.original_nickname = original_nickname
def validate(self):
if not FlaskForm.validate(self):
return False
if self.nickname.data == self.original_nickname:
return True
user = User.query.filter_by(nickname=self.nickname.data).first()
if user != None:
self.nickname.errors.append('This nickname is already in use. Please chose another one.')
return False
return True
Modify to fit with PEP8 standard
|
from flask_wtf import FlaskForm
from wtforms import StringField, IntegerField, DecimalField
from wtforms.validators import DataRequired
from app.models import User
class EditForm(FlaskForm):
nickname = StringField('nickname', validators=[DataRequired()])
name = StringField('name', validators=[DataRequired()])
age = IntegerField('age')
height = DecimalField('heighti', places=2)
def __init__(self, original_nickname, *args, **kwargs):
FlaskForm.__init__(self, *args, **kwargs)
self.original_nickname = original_nickname
def validate(self):
if not FlaskForm.validate(self):
return False
if self.nickname.data == self.original_nickname:
return True
user = User.query.filter_by(nickname=self.nickname.data).first()
if user:
msg = 'This nickname is already in use. Please chose another one.'
self.nickname.errors.append(msg)
return False
return True
|
<commit_before>from flask_wtf import FlaskForm
from wtforms import StringField, IntegerField, DecimalField
from wtforms.validators import DataRequired
from app.models import User
class EditForm(FlaskForm):
nickname = StringField('nickname', validators=[DataRequired()])
name = StringField('name', validators=[DataRequired()])
age = IntegerField('age')
height = DecimalField('heighti', places=2)
def __init__(self, original_nickname, *args, **kwargs):
FlaskForm.__init__(self, *args, **kwargs)
self.original_nickname = original_nickname
def validate(self):
if not FlaskForm.validate(self):
return False
if self.nickname.data == self.original_nickname:
return True
user = User.query.filter_by(nickname=self.nickname.data).first()
if user != None:
self.nickname.errors.append('This nickname is already in use. Please chose another one.')
return False
return True
<commit_msg>Modify to fit with PEP8 standard<commit_after>
|
from flask_wtf import FlaskForm
from wtforms import StringField, IntegerField, DecimalField
from wtforms.validators import DataRequired
from app.models import User
class EditForm(FlaskForm):
nickname = StringField('nickname', validators=[DataRequired()])
name = StringField('name', validators=[DataRequired()])
age = IntegerField('age')
height = DecimalField('heighti', places=2)
def __init__(self, original_nickname, *args, **kwargs):
FlaskForm.__init__(self, *args, **kwargs)
self.original_nickname = original_nickname
def validate(self):
if not FlaskForm.validate(self):
return False
if self.nickname.data == self.original_nickname:
return True
user = User.query.filter_by(nickname=self.nickname.data).first()
if user:
msg = 'This nickname is already in use. Please chose another one.'
self.nickname.errors.append(msg)
return False
return True
|
from flask_wtf import FlaskForm
from wtforms import StringField, IntegerField, DecimalField
from wtforms.validators import DataRequired
from app.models import User
class EditForm(FlaskForm):
nickname = StringField('nickname', validators=[DataRequired()])
name = StringField('name', validators=[DataRequired()])
age = IntegerField('age')
height = DecimalField('heighti', places=2)
def __init__(self, original_nickname, *args, **kwargs):
FlaskForm.__init__(self, *args, **kwargs)
self.original_nickname = original_nickname
def validate(self):
if not FlaskForm.validate(self):
return False
if self.nickname.data == self.original_nickname:
return True
user = User.query.filter_by(nickname=self.nickname.data).first()
if user != None:
self.nickname.errors.append('This nickname is already in use. Please chose another one.')
return False
return True
Modify to fit with PEP8 standardfrom flask_wtf import FlaskForm
from wtforms import StringField, IntegerField, DecimalField
from wtforms.validators import DataRequired
from app.models import User
class EditForm(FlaskForm):
nickname = StringField('nickname', validators=[DataRequired()])
name = StringField('name', validators=[DataRequired()])
age = IntegerField('age')
height = DecimalField('heighti', places=2)
def __init__(self, original_nickname, *args, **kwargs):
FlaskForm.__init__(self, *args, **kwargs)
self.original_nickname = original_nickname
def validate(self):
if not FlaskForm.validate(self):
return False
if self.nickname.data == self.original_nickname:
return True
user = User.query.filter_by(nickname=self.nickname.data).first()
if user:
msg = 'This nickname is already in use. Please chose another one.'
self.nickname.errors.append(msg)
return False
return True
|
<commit_before>from flask_wtf import FlaskForm
from wtforms import StringField, IntegerField, DecimalField
from wtforms.validators import DataRequired
from app.models import User
class EditForm(FlaskForm):
nickname = StringField('nickname', validators=[DataRequired()])
name = StringField('name', validators=[DataRequired()])
age = IntegerField('age')
height = DecimalField('heighti', places=2)
def __init__(self, original_nickname, *args, **kwargs):
FlaskForm.__init__(self, *args, **kwargs)
self.original_nickname = original_nickname
def validate(self):
if not FlaskForm.validate(self):
return False
if self.nickname.data == self.original_nickname:
return True
user = User.query.filter_by(nickname=self.nickname.data).first()
if user != None:
self.nickname.errors.append('This nickname is already in use. Please chose another one.')
return False
return True
<commit_msg>Modify to fit with PEP8 standard<commit_after>from flask_wtf import FlaskForm
from wtforms import StringField, IntegerField, DecimalField
from wtforms.validators import DataRequired
from app.models import User
class EditForm(FlaskForm):
nickname = StringField('nickname', validators=[DataRequired()])
name = StringField('name', validators=[DataRequired()])
age = IntegerField('age')
height = DecimalField('heighti', places=2)
def __init__(self, original_nickname, *args, **kwargs):
FlaskForm.__init__(self, *args, **kwargs)
self.original_nickname = original_nickname
def validate(self):
if not FlaskForm.validate(self):
return False
if self.nickname.data == self.original_nickname:
return True
user = User.query.filter_by(nickname=self.nickname.data).first()
if user:
msg = 'This nickname is already in use. Please chose another one.'
self.nickname.errors.append(msg)
return False
return True
|
216a9176ecf395a7461c6f8ec926d48fa1634bad
|
manager/__init__.py
|
manager/__init__.py
|
import os
from flask import Flask
from flask.ext.assets import Bundle, Environment
app = Flask(__name__)
# Load the app config
app.config.from_object("config.Config")
assets = Environment(app)
assets.load_path = [
os.path.join(os.path.dirname(__file__), 'static'),
os.path.join(os.path.dirname(__file__), 'static', 'bower_components')
]
assets.register(
'js_all',
Bundle(
'jquery/dist/jquery.min.js',
'bootstrap/dist/js/bootstrap.min.js',
output='js_all.js'
)
)
assets.register(
'css_all',
Bundle(
'bootstrap/dist/css/bootstrap.css',
'bootstrap/dist/css/bootstrap-theme.css',
'css/ignition.css',
output='css_all.css'
)
)
from manager.views import core
|
import os
from flask import Flask
from flask.ext.assets import Bundle, Environment
app = Flask(__name__)
# Load the app config
app.config.from_object("config.Config")
assets = Environment(app)
assets.load_path = [
os.path.join(os.path.dirname(__file__), 'static'),
os.path.join(os.path.dirname(__file__), 'static', 'bower_components')
]
assets.register(
'js_all',
Bundle(
'jquery/dist/jquery.min.js',
'bootstrap/dist/js/bootstrap.min.js',
output='js_all.js'
)
)
assets.register(
'css_all',
Bundle(
'bootswatch/sandstone/bootstrap.css',
'css/ignition.css',
output='css_all.css'
)
)
from manager.views import core
|
Change theme to sandstone (bootswatch)
|
Change theme to sandstone (bootswatch)
|
Python
|
mit
|
hreeder/ignition,hreeder/ignition,hreeder/ignition
|
import os
from flask import Flask
from flask.ext.assets import Bundle, Environment
app = Flask(__name__)
# Load the app config
app.config.from_object("config.Config")
assets = Environment(app)
assets.load_path = [
os.path.join(os.path.dirname(__file__), 'static'),
os.path.join(os.path.dirname(__file__), 'static', 'bower_components')
]
assets.register(
'js_all',
Bundle(
'jquery/dist/jquery.min.js',
'bootstrap/dist/js/bootstrap.min.js',
output='js_all.js'
)
)
assets.register(
'css_all',
Bundle(
'bootstrap/dist/css/bootstrap.css',
'bootstrap/dist/css/bootstrap-theme.css',
'css/ignition.css',
output='css_all.css'
)
)
from manager.views import coreChange theme to sandstone (bootswatch)
|
import os
from flask import Flask
from flask.ext.assets import Bundle, Environment
app = Flask(__name__)
# Load the app config
app.config.from_object("config.Config")
assets = Environment(app)
assets.load_path = [
os.path.join(os.path.dirname(__file__), 'static'),
os.path.join(os.path.dirname(__file__), 'static', 'bower_components')
]
assets.register(
'js_all',
Bundle(
'jquery/dist/jquery.min.js',
'bootstrap/dist/js/bootstrap.min.js',
output='js_all.js'
)
)
assets.register(
'css_all',
Bundle(
'bootswatch/sandstone/bootstrap.css',
'css/ignition.css',
output='css_all.css'
)
)
from manager.views import core
|
<commit_before>import os
from flask import Flask
from flask.ext.assets import Bundle, Environment
app = Flask(__name__)
# Load the app config
app.config.from_object("config.Config")
assets = Environment(app)
assets.load_path = [
os.path.join(os.path.dirname(__file__), 'static'),
os.path.join(os.path.dirname(__file__), 'static', 'bower_components')
]
assets.register(
'js_all',
Bundle(
'jquery/dist/jquery.min.js',
'bootstrap/dist/js/bootstrap.min.js',
output='js_all.js'
)
)
assets.register(
'css_all',
Bundle(
'bootstrap/dist/css/bootstrap.css',
'bootstrap/dist/css/bootstrap-theme.css',
'css/ignition.css',
output='css_all.css'
)
)
from manager.views import core<commit_msg>Change theme to sandstone (bootswatch)<commit_after>
|
import os
from flask import Flask
from flask.ext.assets import Bundle, Environment
app = Flask(__name__)
# Load the app config
app.config.from_object("config.Config")
assets = Environment(app)
assets.load_path = [
os.path.join(os.path.dirname(__file__), 'static'),
os.path.join(os.path.dirname(__file__), 'static', 'bower_components')
]
assets.register(
'js_all',
Bundle(
'jquery/dist/jquery.min.js',
'bootstrap/dist/js/bootstrap.min.js',
output='js_all.js'
)
)
assets.register(
'css_all',
Bundle(
'bootswatch/sandstone/bootstrap.css',
'css/ignition.css',
output='css_all.css'
)
)
from manager.views import core
|
import os
from flask import Flask
from flask.ext.assets import Bundle, Environment
app = Flask(__name__)
# Load the app config
app.config.from_object("config.Config")
assets = Environment(app)
assets.load_path = [
os.path.join(os.path.dirname(__file__), 'static'),
os.path.join(os.path.dirname(__file__), 'static', 'bower_components')
]
assets.register(
'js_all',
Bundle(
'jquery/dist/jquery.min.js',
'bootstrap/dist/js/bootstrap.min.js',
output='js_all.js'
)
)
assets.register(
'css_all',
Bundle(
'bootstrap/dist/css/bootstrap.css',
'bootstrap/dist/css/bootstrap-theme.css',
'css/ignition.css',
output='css_all.css'
)
)
from manager.views import coreChange theme to sandstone (bootswatch)import os
from flask import Flask
from flask.ext.assets import Bundle, Environment
app = Flask(__name__)
# Load the app config
app.config.from_object("config.Config")
assets = Environment(app)
assets.load_path = [
os.path.join(os.path.dirname(__file__), 'static'),
os.path.join(os.path.dirname(__file__), 'static', 'bower_components')
]
assets.register(
'js_all',
Bundle(
'jquery/dist/jquery.min.js',
'bootstrap/dist/js/bootstrap.min.js',
output='js_all.js'
)
)
assets.register(
'css_all',
Bundle(
'bootswatch/sandstone/bootstrap.css',
'css/ignition.css',
output='css_all.css'
)
)
from manager.views import core
|
<commit_before>import os
from flask import Flask
from flask.ext.assets import Bundle, Environment
app = Flask(__name__)
# Load the app config
app.config.from_object("config.Config")
assets = Environment(app)
assets.load_path = [
os.path.join(os.path.dirname(__file__), 'static'),
os.path.join(os.path.dirname(__file__), 'static', 'bower_components')
]
assets.register(
'js_all',
Bundle(
'jquery/dist/jquery.min.js',
'bootstrap/dist/js/bootstrap.min.js',
output='js_all.js'
)
)
assets.register(
'css_all',
Bundle(
'bootstrap/dist/css/bootstrap.css',
'bootstrap/dist/css/bootstrap-theme.css',
'css/ignition.css',
output='css_all.css'
)
)
from manager.views import core<commit_msg>Change theme to sandstone (bootswatch)<commit_after>import os
from flask import Flask
from flask.ext.assets import Bundle, Environment
app = Flask(__name__)
# Load the app config
app.config.from_object("config.Config")
assets = Environment(app)
assets.load_path = [
os.path.join(os.path.dirname(__file__), 'static'),
os.path.join(os.path.dirname(__file__), 'static', 'bower_components')
]
assets.register(
'js_all',
Bundle(
'jquery/dist/jquery.min.js',
'bootstrap/dist/js/bootstrap.min.js',
output='js_all.js'
)
)
assets.register(
'css_all',
Bundle(
'bootswatch/sandstone/bootstrap.css',
'css/ignition.css',
output='css_all.css'
)
)
from manager.views import core
|
244fc4729f67595393f51bc2020968b6666c0b6d
|
quickdial/gateaddr.py
|
quickdial/gateaddr.py
|
from random import randint
from types import GeneratorType
from nekrobox.docdecs import params
from six.moves import range
@params(origin=(int, "Final origin symbol, if None then random"),
count=(int, "Number of addresses to generate"),
length=(int, "Length of a gate address in symbols excluding origin"),
symbols=(int, "Number of symbols to choose from"),
returns=(GeneratorType, "Pumps out gate addresses as specified."))
def generate(origin=None, count=1000, length=6, symbols=36):
"""Returns a generator that pumps out randomly generated gate addresses."""
if origin is None:
origin = randint(0, symbols)
return ([randint(0, symbols) for _ in range(length)] + [origin]
for _ in range(count))
@params(address=(list, "Gate address as generated"),
symbols=(str, "Pretty symbols to convert address to"),
returns=(str, "The gate address converted into a string"))
def pretty(address, symbols="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"):
"""
Converts the given gate address into a string by converting symbol
numbers to characters in the symbol string.
Symbols are grouped in threes.
"""
characters = []
count = 0
for x in address:
characters.append(symbols[x])
count += 1
if count >= 3:
characters.append(' ')
count = 0
return ''.join(characters)
|
from random import randint
from types import GeneratorType
from nekrobox.docdecs import params
from six.moves import range
@params(origin=(int, "Final origin symbol, if None then random"),
count=(int, "Number of addresses to generate"),
length=(int, "Length of a gate address in symbols excluding origin"),
symbols=(int, "Number of symbols to choose from"),
returns=(GeneratorType, "Pumps out gate addresses as specified."))
def generate(origin=None, count=1000, length=6, symbols=36):
"""Returns a generator that pumps out randomly generated gate addresses."""
if origin is None:
origin = randint(0, symbols-1)
return ([randint(0, symbols-1) for _ in range(length)] + [origin]
for _ in range(count))
@params(address=(list, "Gate address as generated"),
symbols=(str, "Pretty symbols to convert address to"),
returns=(str, "The gate address converted into a string"))
def pretty(address, symbols="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"):
"""
Converts the given gate address into a string by converting symbol
numbers to characters in the symbol string.
Symbols are grouped in threes.
"""
characters = []
count = 0
for x in address:
characters.append(symbols[x])
count += 1
if count >= 3:
characters.append(' ')
count = 0
return ''.join(characters)
|
Fix out of bounds symbol generation
|
Fix out of bounds symbol generation
|
Python
|
mit
|
Nekroze/quickdial,Nekroze/quickdial
|
from random import randint
from types import GeneratorType
from nekrobox.docdecs import params
from six.moves import range
@params(origin=(int, "Final origin symbol, if None then random"),
count=(int, "Number of addresses to generate"),
length=(int, "Length of a gate address in symbols excluding origin"),
symbols=(int, "Number of symbols to choose from"),
returns=(GeneratorType, "Pumps out gate addresses as specified."))
def generate(origin=None, count=1000, length=6, symbols=36):
"""Returns a generator that pumps out randomly generated gate addresses."""
if origin is None:
origin = randint(0, symbols)
return ([randint(0, symbols) for _ in range(length)] + [origin]
for _ in range(count))
@params(address=(list, "Gate address as generated"),
symbols=(str, "Pretty symbols to convert address to"),
returns=(str, "The gate address converted into a string"))
def pretty(address, symbols="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"):
"""
Converts the given gate address into a string by converting symbol
numbers to characters in the symbol string.
Symbols are grouped in threes.
"""
characters = []
count = 0
for x in address:
characters.append(symbols[x])
count += 1
if count >= 3:
characters.append(' ')
count = 0
return ''.join(characters)
Fix out of bounds symbol generation
|
from random import randint
from types import GeneratorType
from nekrobox.docdecs import params
from six.moves import range
@params(origin=(int, "Final origin symbol, if None then random"),
count=(int, "Number of addresses to generate"),
length=(int, "Length of a gate address in symbols excluding origin"),
symbols=(int, "Number of symbols to choose from"),
returns=(GeneratorType, "Pumps out gate addresses as specified."))
def generate(origin=None, count=1000, length=6, symbols=36):
"""Returns a generator that pumps out randomly generated gate addresses."""
if origin is None:
origin = randint(0, symbols-1)
return ([randint(0, symbols-1) for _ in range(length)] + [origin]
for _ in range(count))
@params(address=(list, "Gate address as generated"),
symbols=(str, "Pretty symbols to convert address to"),
returns=(str, "The gate address converted into a string"))
def pretty(address, symbols="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"):
"""
Converts the given gate address into a string by converting symbol
numbers to characters in the symbol string.
Symbols are grouped in threes.
"""
characters = []
count = 0
for x in address:
characters.append(symbols[x])
count += 1
if count >= 3:
characters.append(' ')
count = 0
return ''.join(characters)
|
<commit_before>from random import randint
from types import GeneratorType
from nekrobox.docdecs import params
from six.moves import range
@params(origin=(int, "Final origin symbol, if None then random"),
count=(int, "Number of addresses to generate"),
length=(int, "Length of a gate address in symbols excluding origin"),
symbols=(int, "Number of symbols to choose from"),
returns=(GeneratorType, "Pumps out gate addresses as specified."))
def generate(origin=None, count=1000, length=6, symbols=36):
"""Returns a generator that pumps out randomly generated gate addresses."""
if origin is None:
origin = randint(0, symbols)
return ([randint(0, symbols) for _ in range(length)] + [origin]
for _ in range(count))
@params(address=(list, "Gate address as generated"),
symbols=(str, "Pretty symbols to convert address to"),
returns=(str, "The gate address converted into a string"))
def pretty(address, symbols="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"):
"""
Converts the given gate address into a string by converting symbol
numbers to characters in the symbol string.
Symbols are grouped in threes.
"""
characters = []
count = 0
for x in address:
characters.append(symbols[x])
count += 1
if count >= 3:
characters.append(' ')
count = 0
return ''.join(characters)
<commit_msg>Fix out of bounds symbol generation<commit_after>
|
from random import randint
from types import GeneratorType
from nekrobox.docdecs import params
from six.moves import range
@params(origin=(int, "Final origin symbol, if None then random"),
count=(int, "Number of addresses to generate"),
length=(int, "Length of a gate address in symbols excluding origin"),
symbols=(int, "Number of symbols to choose from"),
returns=(GeneratorType, "Pumps out gate addresses as specified."))
def generate(origin=None, count=1000, length=6, symbols=36):
"""Returns a generator that pumps out randomly generated gate addresses."""
if origin is None:
origin = randint(0, symbols-1)
return ([randint(0, symbols-1) for _ in range(length)] + [origin]
for _ in range(count))
@params(address=(list, "Gate address as generated"),
symbols=(str, "Pretty symbols to convert address to"),
returns=(str, "The gate address converted into a string"))
def pretty(address, symbols="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"):
"""
Converts the given gate address into a string by converting symbol
numbers to characters in the symbol string.
Symbols are grouped in threes.
"""
characters = []
count = 0
for x in address:
characters.append(symbols[x])
count += 1
if count >= 3:
characters.append(' ')
count = 0
return ''.join(characters)
|
from random import randint
from types import GeneratorType
from nekrobox.docdecs import params
from six.moves import range
@params(origin=(int, "Final origin symbol, if None then random"),
count=(int, "Number of addresses to generate"),
length=(int, "Length of a gate address in symbols excluding origin"),
symbols=(int, "Number of symbols to choose from"),
returns=(GeneratorType, "Pumps out gate addresses as specified."))
def generate(origin=None, count=1000, length=6, symbols=36):
"""Returns a generator that pumps out randomly generated gate addresses."""
if origin is None:
origin = randint(0, symbols)
return ([randint(0, symbols) for _ in range(length)] + [origin]
for _ in range(count))
@params(address=(list, "Gate address as generated"),
symbols=(str, "Pretty symbols to convert address to"),
returns=(str, "The gate address converted into a string"))
def pretty(address, symbols="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"):
"""
Converts the given gate address into a string by converting symbol
numbers to characters in the symbol string.
Symbols are grouped in threes.
"""
characters = []
count = 0
for x in address:
characters.append(symbols[x])
count += 1
if count >= 3:
characters.append(' ')
count = 0
return ''.join(characters)
Fix out of bounds symbol generationfrom random import randint
from types import GeneratorType
from nekrobox.docdecs import params
from six.moves import range
@params(origin=(int, "Final origin symbol, if None then random"),
count=(int, "Number of addresses to generate"),
length=(int, "Length of a gate address in symbols excluding origin"),
symbols=(int, "Number of symbols to choose from"),
returns=(GeneratorType, "Pumps out gate addresses as specified."))
def generate(origin=None, count=1000, length=6, symbols=36):
"""Returns a generator that pumps out randomly generated gate addresses."""
if origin is None:
origin = randint(0, symbols-1)
return ([randint(0, symbols-1) for _ in range(length)] + [origin]
for _ in range(count))
@params(address=(list, "Gate address as generated"),
symbols=(str, "Pretty symbols to convert address to"),
returns=(str, "The gate address converted into a string"))
def pretty(address, symbols="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"):
"""
Converts the given gate address into a string by converting symbol
numbers to characters in the symbol string.
Symbols are grouped in threes.
"""
characters = []
count = 0
for x in address:
characters.append(symbols[x])
count += 1
if count >= 3:
characters.append(' ')
count = 0
return ''.join(characters)
|
<commit_before>from random import randint
from types import GeneratorType
from nekrobox.docdecs import params
from six.moves import range
@params(origin=(int, "Final origin symbol, if None then random"),
count=(int, "Number of addresses to generate"),
length=(int, "Length of a gate address in symbols excluding origin"),
symbols=(int, "Number of symbols to choose from"),
returns=(GeneratorType, "Pumps out gate addresses as specified."))
def generate(origin=None, count=1000, length=6, symbols=36):
"""Returns a generator that pumps out randomly generated gate addresses."""
if origin is None:
origin = randint(0, symbols)
return ([randint(0, symbols) for _ in range(length)] + [origin]
for _ in range(count))
@params(address=(list, "Gate address as generated"),
symbols=(str, "Pretty symbols to convert address to"),
returns=(str, "The gate address converted into a string"))
def pretty(address, symbols="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"):
"""
Converts the given gate address into a string by converting symbol
numbers to characters in the symbol string.
Symbols are grouped in threes.
"""
characters = []
count = 0
for x in address:
characters.append(symbols[x])
count += 1
if count >= 3:
characters.append(' ')
count = 0
return ''.join(characters)
<commit_msg>Fix out of bounds symbol generation<commit_after>from random import randint
from types import GeneratorType
from nekrobox.docdecs import params
from six.moves import range
@params(origin=(int, "Final origin symbol, if None then random"),
count=(int, "Number of addresses to generate"),
length=(int, "Length of a gate address in symbols excluding origin"),
symbols=(int, "Number of symbols to choose from"),
returns=(GeneratorType, "Pumps out gate addresses as specified."))
def generate(origin=None, count=1000, length=6, symbols=36):
"""Returns a generator that pumps out randomly generated gate addresses."""
if origin is None:
origin = randint(0, symbols-1)
return ([randint(0, symbols-1) for _ in range(length)] + [origin]
for _ in range(count))
@params(address=(list, "Gate address as generated"),
symbols=(str, "Pretty symbols to convert address to"),
returns=(str, "The gate address converted into a string"))
def pretty(address, symbols="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"):
"""
Converts the given gate address into a string by converting symbol
numbers to characters in the symbol string.
Symbols are grouped in threes.
"""
characters = []
count = 0
for x in address:
characters.append(symbols[x])
count += 1
if count >= 3:
characters.append(' ')
count = 0
return ''.join(characters)
|
8eaaab332616469bec567ad159b315cc0d1e35fc
|
vumi/persist/tests/test_fields.py
|
vumi/persist/tests/test_fields.py
|
# -*- coding: utf-8 -*-
"""Tests for vumi.persist.fields."""
from twisted.trial.unittest import TestCase
from vumi.persist.fields import Field, ValidationError, Integer, Unicode
class TestInteger(TestCase):
def test_unbounded(self):
i = Integer()
i.validate(5)
i.validate(-3)
self.assertRaises(ValidationError, i.validate, 5.0)
self.assertRaises(ValidationError, i.validate, "5")
def test_minimum(self):
i = Integer(min=3)
i.validate(3)
i.validate(4)
self.assertRaises(ValidationError, i.validate, 2)
def test_maximum(self):
i = Integer(max=5)
i.validate(5)
i.validate(4)
self.assertRaises(ValidationError, i.validate, 6)
class TestUnicode(TestCase):
def test_unicode(self):
u = Unicode()
u.validate(u"")
u.validate(u"a")
u.validate(u"æ")
u.validate(u"foé")
self.assertRaises(ValidationError, u.validate, "")
self.assertRaises(ValidationError, u.validate, "foo")
self.assertRaises(ValidationError, u.validate, 3)
|
# -*- coding: utf-8 -*-
"""Tests for vumi.persist.fields."""
from twisted.trial.unittest import TestCase
from vumi.persist.fields import (
ValidationError, Field, FieldDescriptor, Integer, Unicode, ForeignKey,
ForeignKeyDescriptor)
class TestBaseField(TestCase):
def test_validate(self):
f = Field()
f.validate("foo")
f.validate(object())
def test_get_descriptor(self):
f = Field()
descriptor = f.get_descriptor("foo")
self.assertEqual(descriptor.key, "foo")
self.assertEqual(descriptor.field, f)
class TestInteger(TestCase):
def test_unbounded(self):
i = Integer()
i.validate(5)
i.validate(-3)
self.assertRaises(ValidationError, i.validate, 5.0)
self.assertRaises(ValidationError, i.validate, "5")
def test_minimum(self):
i = Integer(min=3)
i.validate(3)
i.validate(4)
self.assertRaises(ValidationError, i.validate, 2)
def test_maximum(self):
i = Integer(max=5)
i.validate(5)
i.validate(4)
self.assertRaises(ValidationError, i.validate, 6)
class TestUnicode(TestCase):
def test_unicode(self):
u = Unicode()
u.validate(u"")
u.validate(u"a")
u.validate(u"æ")
u.validate(u"foé")
self.assertRaises(ValidationError, u.validate, "")
self.assertRaises(ValidationError, u.validate, "foo")
self.assertRaises(ValidationError, u.validate, 3)
|
Add tests for the Field class.
|
Add tests for the Field class.
|
Python
|
bsd-3-clause
|
TouK/vumi,TouK/vumi,vishwaprakashmishra/xmatrix,harrissoerja/vumi,vishwaprakashmishra/xmatrix,TouK/vumi,harrissoerja/vumi,harrissoerja/vumi,vishwaprakashmishra/xmatrix
|
# -*- coding: utf-8 -*-
"""Tests for vumi.persist.fields."""
from twisted.trial.unittest import TestCase
from vumi.persist.fields import Field, ValidationError, Integer, Unicode
class TestInteger(TestCase):
def test_unbounded(self):
i = Integer()
i.validate(5)
i.validate(-3)
self.assertRaises(ValidationError, i.validate, 5.0)
self.assertRaises(ValidationError, i.validate, "5")
def test_minimum(self):
i = Integer(min=3)
i.validate(3)
i.validate(4)
self.assertRaises(ValidationError, i.validate, 2)
def test_maximum(self):
i = Integer(max=5)
i.validate(5)
i.validate(4)
self.assertRaises(ValidationError, i.validate, 6)
class TestUnicode(TestCase):
def test_unicode(self):
u = Unicode()
u.validate(u"")
u.validate(u"a")
u.validate(u"æ")
u.validate(u"foé")
self.assertRaises(ValidationError, u.validate, "")
self.assertRaises(ValidationError, u.validate, "foo")
self.assertRaises(ValidationError, u.validate, 3)
Add tests for the Field class.
|
# -*- coding: utf-8 -*-
"""Tests for vumi.persist.fields."""
from twisted.trial.unittest import TestCase
from vumi.persist.fields import (
ValidationError, Field, FieldDescriptor, Integer, Unicode, ForeignKey,
ForeignKeyDescriptor)
class TestBaseField(TestCase):
def test_validate(self):
f = Field()
f.validate("foo")
f.validate(object())
def test_get_descriptor(self):
f = Field()
descriptor = f.get_descriptor("foo")
self.assertEqual(descriptor.key, "foo")
self.assertEqual(descriptor.field, f)
class TestInteger(TestCase):
def test_unbounded(self):
i = Integer()
i.validate(5)
i.validate(-3)
self.assertRaises(ValidationError, i.validate, 5.0)
self.assertRaises(ValidationError, i.validate, "5")
def test_minimum(self):
i = Integer(min=3)
i.validate(3)
i.validate(4)
self.assertRaises(ValidationError, i.validate, 2)
def test_maximum(self):
i = Integer(max=5)
i.validate(5)
i.validate(4)
self.assertRaises(ValidationError, i.validate, 6)
class TestUnicode(TestCase):
def test_unicode(self):
u = Unicode()
u.validate(u"")
u.validate(u"a")
u.validate(u"æ")
u.validate(u"foé")
self.assertRaises(ValidationError, u.validate, "")
self.assertRaises(ValidationError, u.validate, "foo")
self.assertRaises(ValidationError, u.validate, 3)
|
<commit_before># -*- coding: utf-8 -*-
"""Tests for vumi.persist.fields."""
from twisted.trial.unittest import TestCase
from vumi.persist.fields import Field, ValidationError, Integer, Unicode
class TestInteger(TestCase):
def test_unbounded(self):
i = Integer()
i.validate(5)
i.validate(-3)
self.assertRaises(ValidationError, i.validate, 5.0)
self.assertRaises(ValidationError, i.validate, "5")
def test_minimum(self):
i = Integer(min=3)
i.validate(3)
i.validate(4)
self.assertRaises(ValidationError, i.validate, 2)
def test_maximum(self):
i = Integer(max=5)
i.validate(5)
i.validate(4)
self.assertRaises(ValidationError, i.validate, 6)
class TestUnicode(TestCase):
def test_unicode(self):
u = Unicode()
u.validate(u"")
u.validate(u"a")
u.validate(u"æ")
u.validate(u"foé")
self.assertRaises(ValidationError, u.validate, "")
self.assertRaises(ValidationError, u.validate, "foo")
self.assertRaises(ValidationError, u.validate, 3)
<commit_msg>Add tests for the Field class.<commit_after>
|
# -*- coding: utf-8 -*-
"""Tests for vumi.persist.fields."""
from twisted.trial.unittest import TestCase
from vumi.persist.fields import (
ValidationError, Field, FieldDescriptor, Integer, Unicode, ForeignKey,
ForeignKeyDescriptor)
class TestBaseField(TestCase):
def test_validate(self):
f = Field()
f.validate("foo")
f.validate(object())
def test_get_descriptor(self):
f = Field()
descriptor = f.get_descriptor("foo")
self.assertEqual(descriptor.key, "foo")
self.assertEqual(descriptor.field, f)
class TestInteger(TestCase):
def test_unbounded(self):
i = Integer()
i.validate(5)
i.validate(-3)
self.assertRaises(ValidationError, i.validate, 5.0)
self.assertRaises(ValidationError, i.validate, "5")
def test_minimum(self):
i = Integer(min=3)
i.validate(3)
i.validate(4)
self.assertRaises(ValidationError, i.validate, 2)
def test_maximum(self):
i = Integer(max=5)
i.validate(5)
i.validate(4)
self.assertRaises(ValidationError, i.validate, 6)
class TestUnicode(TestCase):
def test_unicode(self):
u = Unicode()
u.validate(u"")
u.validate(u"a")
u.validate(u"æ")
u.validate(u"foé")
self.assertRaises(ValidationError, u.validate, "")
self.assertRaises(ValidationError, u.validate, "foo")
self.assertRaises(ValidationError, u.validate, 3)
|
# -*- coding: utf-8 -*-
"""Tests for vumi.persist.fields."""
from twisted.trial.unittest import TestCase
from vumi.persist.fields import Field, ValidationError, Integer, Unicode
class TestInteger(TestCase):
def test_unbounded(self):
i = Integer()
i.validate(5)
i.validate(-3)
self.assertRaises(ValidationError, i.validate, 5.0)
self.assertRaises(ValidationError, i.validate, "5")
def test_minimum(self):
i = Integer(min=3)
i.validate(3)
i.validate(4)
self.assertRaises(ValidationError, i.validate, 2)
def test_maximum(self):
i = Integer(max=5)
i.validate(5)
i.validate(4)
self.assertRaises(ValidationError, i.validate, 6)
class TestUnicode(TestCase):
def test_unicode(self):
u = Unicode()
u.validate(u"")
u.validate(u"a")
u.validate(u"æ")
u.validate(u"foé")
self.assertRaises(ValidationError, u.validate, "")
self.assertRaises(ValidationError, u.validate, "foo")
self.assertRaises(ValidationError, u.validate, 3)
Add tests for the Field class.# -*- coding: utf-8 -*-
"""Tests for vumi.persist.fields."""
from twisted.trial.unittest import TestCase
from vumi.persist.fields import (
ValidationError, Field, FieldDescriptor, Integer, Unicode, ForeignKey,
ForeignKeyDescriptor)
class TestBaseField(TestCase):
def test_validate(self):
f = Field()
f.validate("foo")
f.validate(object())
def test_get_descriptor(self):
f = Field()
descriptor = f.get_descriptor("foo")
self.assertEqual(descriptor.key, "foo")
self.assertEqual(descriptor.field, f)
class TestInteger(TestCase):
def test_unbounded(self):
i = Integer()
i.validate(5)
i.validate(-3)
self.assertRaises(ValidationError, i.validate, 5.0)
self.assertRaises(ValidationError, i.validate, "5")
def test_minimum(self):
i = Integer(min=3)
i.validate(3)
i.validate(4)
self.assertRaises(ValidationError, i.validate, 2)
def test_maximum(self):
i = Integer(max=5)
i.validate(5)
i.validate(4)
self.assertRaises(ValidationError, i.validate, 6)
class TestUnicode(TestCase):
def test_unicode(self):
u = Unicode()
u.validate(u"")
u.validate(u"a")
u.validate(u"æ")
u.validate(u"foé")
self.assertRaises(ValidationError, u.validate, "")
self.assertRaises(ValidationError, u.validate, "foo")
self.assertRaises(ValidationError, u.validate, 3)
|
<commit_before># -*- coding: utf-8 -*-
"""Tests for vumi.persist.fields."""
from twisted.trial.unittest import TestCase
from vumi.persist.fields import Field, ValidationError, Integer, Unicode
class TestInteger(TestCase):
def test_unbounded(self):
i = Integer()
i.validate(5)
i.validate(-3)
self.assertRaises(ValidationError, i.validate, 5.0)
self.assertRaises(ValidationError, i.validate, "5")
def test_minimum(self):
i = Integer(min=3)
i.validate(3)
i.validate(4)
self.assertRaises(ValidationError, i.validate, 2)
def test_maximum(self):
i = Integer(max=5)
i.validate(5)
i.validate(4)
self.assertRaises(ValidationError, i.validate, 6)
class TestUnicode(TestCase):
def test_unicode(self):
u = Unicode()
u.validate(u"")
u.validate(u"a")
u.validate(u"æ")
u.validate(u"foé")
self.assertRaises(ValidationError, u.validate, "")
self.assertRaises(ValidationError, u.validate, "foo")
self.assertRaises(ValidationError, u.validate, 3)
<commit_msg>Add tests for the Field class.<commit_after># -*- coding: utf-8 -*-
"""Tests for vumi.persist.fields."""
from twisted.trial.unittest import TestCase
from vumi.persist.fields import (
ValidationError, Field, FieldDescriptor, Integer, Unicode, ForeignKey,
ForeignKeyDescriptor)
class TestBaseField(TestCase):
def test_validate(self):
f = Field()
f.validate("foo")
f.validate(object())
def test_get_descriptor(self):
f = Field()
descriptor = f.get_descriptor("foo")
self.assertEqual(descriptor.key, "foo")
self.assertEqual(descriptor.field, f)
class TestInteger(TestCase):
def test_unbounded(self):
i = Integer()
i.validate(5)
i.validate(-3)
self.assertRaises(ValidationError, i.validate, 5.0)
self.assertRaises(ValidationError, i.validate, "5")
def test_minimum(self):
i = Integer(min=3)
i.validate(3)
i.validate(4)
self.assertRaises(ValidationError, i.validate, 2)
def test_maximum(self):
i = Integer(max=5)
i.validate(5)
i.validate(4)
self.assertRaises(ValidationError, i.validate, 6)
class TestUnicode(TestCase):
def test_unicode(self):
u = Unicode()
u.validate(u"")
u.validate(u"a")
u.validate(u"æ")
u.validate(u"foé")
self.assertRaises(ValidationError, u.validate, "")
self.assertRaises(ValidationError, u.validate, "foo")
self.assertRaises(ValidationError, u.validate, 3)
|
2d27e06d0f70921093b1a4629128ec456a47423d
|
euler/solutions/solution_19.py
|
euler/solutions/solution_19.py
|
"""Counting Sundays
You are given the following information, but you may prefer to do some research for yourself.
- 1 Jan 1900 was a Monday.
- Thirty days has September,
April, June and November.
All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, rain or shine.
And on leap years, twenty-nine.
- A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.
How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
"""
|
"""Counting Sundays
You are given the following information, but you may prefer to do some research for yourself.
- 1 Jan 1900 was a Monday.
- Thirty days has September,
April, June and November.
All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, rain or shine.
And on leap years, twenty-nine.
- A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.
How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
"""
import calendar
MONTHS = 12
SUNDAY = 6
def get_first_sundays(low_year, high_year):
"""
Find the number of Sundays falling on the first of the month between low_year
and high_year, inclusive.
"""
first_sundays = 0
for year in range(low_year, high_year + 1):
for month in range(1, MONTHS + 1):
first_day, _ = calendar.monthrange(year, month)
if first_day == SUNDAY:
first_sundays += 1
return first_sundays
|
Add solution for problem 19
|
Add solution for problem 19
Counting Sundays
|
Python
|
mit
|
rlucioni/project-euler
|
"""Counting Sundays
You are given the following information, but you may prefer to do some research for yourself.
- 1 Jan 1900 was a Monday.
- Thirty days has September,
April, June and November.
All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, rain or shine.
And on leap years, twenty-nine.
- A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.
How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
"""
Add solution for problem 19
Counting Sundays
|
"""Counting Sundays
You are given the following information, but you may prefer to do some research for yourself.
- 1 Jan 1900 was a Monday.
- Thirty days has September,
April, June and November.
All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, rain or shine.
And on leap years, twenty-nine.
- A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.
How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
"""
import calendar
MONTHS = 12
SUNDAY = 6
def get_first_sundays(low_year, high_year):
"""
Find the number of Sundays falling on the first of the month between low_year
and high_year, inclusive.
"""
first_sundays = 0
for year in range(low_year, high_year + 1):
for month in range(1, MONTHS + 1):
first_day, _ = calendar.monthrange(year, month)
if first_day == SUNDAY:
first_sundays += 1
return first_sundays
|
<commit_before>"""Counting Sundays
You are given the following information, but you may prefer to do some research for yourself.
- 1 Jan 1900 was a Monday.
- Thirty days has September,
April, June and November.
All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, rain or shine.
And on leap years, twenty-nine.
- A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.
How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
"""
<commit_msg>Add solution for problem 19
Counting Sundays<commit_after>
|
"""Counting Sundays
You are given the following information, but you may prefer to do some research for yourself.
- 1 Jan 1900 was a Monday.
- Thirty days has September,
April, June and November.
All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, rain or shine.
And on leap years, twenty-nine.
- A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.
How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
"""
import calendar
MONTHS = 12
SUNDAY = 6
def get_first_sundays(low_year, high_year):
"""
Find the number of Sundays falling on the first of the month between low_year
and high_year, inclusive.
"""
first_sundays = 0
for year in range(low_year, high_year + 1):
for month in range(1, MONTHS + 1):
first_day, _ = calendar.monthrange(year, month)
if first_day == SUNDAY:
first_sundays += 1
return first_sundays
|
"""Counting Sundays
You are given the following information, but you may prefer to do some research for yourself.
- 1 Jan 1900 was a Monday.
- Thirty days has September,
April, June and November.
All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, rain or shine.
And on leap years, twenty-nine.
- A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.
How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
"""
Add solution for problem 19
Counting Sundays"""Counting Sundays
You are given the following information, but you may prefer to do some research for yourself.
- 1 Jan 1900 was a Monday.
- Thirty days has September,
April, June and November.
All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, rain or shine.
And on leap years, twenty-nine.
- A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.
How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
"""
import calendar
MONTHS = 12
SUNDAY = 6
def get_first_sundays(low_year, high_year):
"""
Find the number of Sundays falling on the first of the month between low_year
and high_year, inclusive.
"""
first_sundays = 0
for year in range(low_year, high_year + 1):
for month in range(1, MONTHS + 1):
first_day, _ = calendar.monthrange(year, month)
if first_day == SUNDAY:
first_sundays += 1
return first_sundays
|
<commit_before>"""Counting Sundays
You are given the following information, but you may prefer to do some research for yourself.
- 1 Jan 1900 was a Monday.
- Thirty days has September,
April, June and November.
All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, rain or shine.
And on leap years, twenty-nine.
- A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.
How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
"""
<commit_msg>Add solution for problem 19
Counting Sundays<commit_after>"""Counting Sundays
You are given the following information, but you may prefer to do some research for yourself.
- 1 Jan 1900 was a Monday.
- Thirty days has September,
April, June and November.
All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, rain or shine.
And on leap years, twenty-nine.
- A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.
How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
"""
import calendar
MONTHS = 12
SUNDAY = 6
def get_first_sundays(low_year, high_year):
"""
Find the number of Sundays falling on the first of the month between low_year
and high_year, inclusive.
"""
first_sundays = 0
for year in range(low_year, high_year + 1):
for month in range(1, MONTHS + 1):
first_day, _ = calendar.monthrange(year, month)
if first_day == SUNDAY:
first_sundays += 1
return first_sundays
|
43a92adea08017fa13bf191a628e0bfc7661bd3b
|
third_party/__init__.py
|
third_party/__init__.py
|
import os.path
import sys
# This bit of evil should inject third_party into the path for relative imports.
sys.path.append(os.path.dirname(__file__))
|
import os.path
import sys
# This bit of evil should inject third_party into the path for relative imports.
sys.path.insert(1, os.path.dirname(__file__))
|
Insert third_party into the second slot of sys.path rather than the last slot
|
Insert third_party into the second slot of sys.path rather than the last slot
|
Python
|
apache-2.0
|
mirek2580/namebench
|
import os.path
import sys
# This bit of evil should inject third_party into the path for relative imports.
sys.path.append(os.path.dirname(__file__))
Insert third_party into the second slot of sys.path rather than the last slot
|
import os.path
import sys
# This bit of evil should inject third_party into the path for relative imports.
sys.path.insert(1, os.path.dirname(__file__))
|
<commit_before>import os.path
import sys
# This bit of evil should inject third_party into the path for relative imports.
sys.path.append(os.path.dirname(__file__))
<commit_msg>Insert third_party into the second slot of sys.path rather than the last slot<commit_after>
|
import os.path
import sys
# This bit of evil should inject third_party into the path for relative imports.
sys.path.insert(1, os.path.dirname(__file__))
|
import os.path
import sys
# This bit of evil should inject third_party into the path for relative imports.
sys.path.append(os.path.dirname(__file__))
Insert third_party into the second slot of sys.path rather than the last slotimport os.path
import sys
# This bit of evil should inject third_party into the path for relative imports.
sys.path.insert(1, os.path.dirname(__file__))
|
<commit_before>import os.path
import sys
# This bit of evil should inject third_party into the path for relative imports.
sys.path.append(os.path.dirname(__file__))
<commit_msg>Insert third_party into the second slot of sys.path rather than the last slot<commit_after>import os.path
import sys
# This bit of evil should inject third_party into the path for relative imports.
sys.path.insert(1, os.path.dirname(__file__))
|
8b30f787d3dabb9072ee0517cf0e5e92daa1038f
|
l10n_ch_dta_base_transaction_id/wizard/create_dta.py
|
l10n_ch_dta_base_transaction_id/wizard/create_dta.py
|
# -*- coding: utf-8 -*-
##############################################################################
#
# Author: Guewen Baconnier
# Copyright 2014 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.osv import orm
class DTAFileGenerator(orm.TransientModel):
_inherit = "create.dta.wizard"
def _set_bank_data(self, cr, uid, data, pline, elec_context,
seq, context=None):
super(DTAFileGenerator, self).\
_set_bank_data(cr, uid, data, pline,
elec_context, seq, context=context)
if pline.move_line_id.transaction_ref:
elec_context['reference'] = pline.move_line_id.transaction_ref
|
# -*- coding: utf-8 -*-
##############################################################################
#
# Author: Guewen Baconnier
# Copyright 2014 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.osv import orm
class DTAFileGenerator(orm.TransientModel):
_inherit = "create.dta.wizard"
def _set_bank_data(self, cr, uid, pline, elec_context,
seq, context=None):
super(DTAFileGenerator, self).\
_set_bank_data(cr, uid, pline,
elec_context, seq, context=context)
if pline.move_line_id.transaction_ref:
elec_context['reference'] = pline.move_line_id.transaction_ref
|
Fix TypeError: _set_bank_data() takes at least 7 arguments (7 given)
|
Fix TypeError: _set_bank_data() takes at least 7 arguments (7 given)
|
Python
|
agpl-3.0
|
open-net-sarl/l10n-switzerland,open-net-sarl/l10n-switzerland,BT-ojossen/l10n-switzerland,BT-ojossen/l10n-switzerland
|
# -*- coding: utf-8 -*-
##############################################################################
#
# Author: Guewen Baconnier
# Copyright 2014 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.osv import orm
class DTAFileGenerator(orm.TransientModel):
_inherit = "create.dta.wizard"
def _set_bank_data(self, cr, uid, data, pline, elec_context,
seq, context=None):
super(DTAFileGenerator, self).\
_set_bank_data(cr, uid, data, pline,
elec_context, seq, context=context)
if pline.move_line_id.transaction_ref:
elec_context['reference'] = pline.move_line_id.transaction_ref
Fix TypeError: _set_bank_data() takes at least 7 arguments (7 given)
|
# -*- coding: utf-8 -*-
##############################################################################
#
# Author: Guewen Baconnier
# Copyright 2014 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.osv import orm
class DTAFileGenerator(orm.TransientModel):
_inherit = "create.dta.wizard"
def _set_bank_data(self, cr, uid, pline, elec_context,
seq, context=None):
super(DTAFileGenerator, self).\
_set_bank_data(cr, uid, pline,
elec_context, seq, context=context)
if pline.move_line_id.transaction_ref:
elec_context['reference'] = pline.move_line_id.transaction_ref
|
<commit_before># -*- coding: utf-8 -*-
##############################################################################
#
# Author: Guewen Baconnier
# Copyright 2014 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.osv import orm
class DTAFileGenerator(orm.TransientModel):
_inherit = "create.dta.wizard"
def _set_bank_data(self, cr, uid, data, pline, elec_context,
seq, context=None):
super(DTAFileGenerator, self).\
_set_bank_data(cr, uid, data, pline,
elec_context, seq, context=context)
if pline.move_line_id.transaction_ref:
elec_context['reference'] = pline.move_line_id.transaction_ref
<commit_msg>Fix TypeError: _set_bank_data() takes at least 7 arguments (7 given)<commit_after>
|
# -*- coding: utf-8 -*-
##############################################################################
#
# Author: Guewen Baconnier
# Copyright 2014 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.osv import orm
class DTAFileGenerator(orm.TransientModel):
_inherit = "create.dta.wizard"
def _set_bank_data(self, cr, uid, pline, elec_context,
seq, context=None):
super(DTAFileGenerator, self).\
_set_bank_data(cr, uid, pline,
elec_context, seq, context=context)
if pline.move_line_id.transaction_ref:
elec_context['reference'] = pline.move_line_id.transaction_ref
|
# -*- coding: utf-8 -*-
##############################################################################
#
# Author: Guewen Baconnier
# Copyright 2014 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.osv import orm
class DTAFileGenerator(orm.TransientModel):
_inherit = "create.dta.wizard"
def _set_bank_data(self, cr, uid, data, pline, elec_context,
seq, context=None):
super(DTAFileGenerator, self).\
_set_bank_data(cr, uid, data, pline,
elec_context, seq, context=context)
if pline.move_line_id.transaction_ref:
elec_context['reference'] = pline.move_line_id.transaction_ref
Fix TypeError: _set_bank_data() takes at least 7 arguments (7 given)# -*- coding: utf-8 -*-
##############################################################################
#
# Author: Guewen Baconnier
# Copyright 2014 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.osv import orm
class DTAFileGenerator(orm.TransientModel):
_inherit = "create.dta.wizard"
def _set_bank_data(self, cr, uid, pline, elec_context,
seq, context=None):
super(DTAFileGenerator, self).\
_set_bank_data(cr, uid, pline,
elec_context, seq, context=context)
if pline.move_line_id.transaction_ref:
elec_context['reference'] = pline.move_line_id.transaction_ref
|
<commit_before># -*- coding: utf-8 -*-
##############################################################################
#
# Author: Guewen Baconnier
# Copyright 2014 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.osv import orm
class DTAFileGenerator(orm.TransientModel):
_inherit = "create.dta.wizard"
def _set_bank_data(self, cr, uid, data, pline, elec_context,
seq, context=None):
super(DTAFileGenerator, self).\
_set_bank_data(cr, uid, data, pline,
elec_context, seq, context=context)
if pline.move_line_id.transaction_ref:
elec_context['reference'] = pline.move_line_id.transaction_ref
<commit_msg>Fix TypeError: _set_bank_data() takes at least 7 arguments (7 given)<commit_after># -*- coding: utf-8 -*-
##############################################################################
#
# Author: Guewen Baconnier
# Copyright 2014 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.osv import orm
class DTAFileGenerator(orm.TransientModel):
_inherit = "create.dta.wizard"
def _set_bank_data(self, cr, uid, pline, elec_context,
seq, context=None):
super(DTAFileGenerator, self).\
_set_bank_data(cr, uid, pline,
elec_context, seq, context=context)
if pline.move_line_id.transaction_ref:
elec_context['reference'] = pline.move_line_id.transaction_ref
|
18261acd87a2e9c6735d9081eff50e2a09277605
|
src/pyshark/config.py
|
src/pyshark/config.py
|
from pathlib import Path
from configparser import ConfigParser
import pyshark
fp_config_path = Path.cwd() / 'config.ini' # get config from the current directory
pyshark_config_path = Path(pyshark.__file__).parent / 'config.ini'
def get_config():
if Path.exists(fp_config_path):
config_path = fp_config_path
elif Path.exists(pyshark_config_path):
config_path = pyshark_config_path
else:
return None
config = ConfigParser()
config.read(config_path)
return config
|
from pathlib import Path
from configparser import ConfigParser
import pyshark
fp_config_path = Path.cwd() / 'config.ini' # get config from the current directory
pyshark_config_path = Path(pyshark.__file__).parent / 'config.ini'
def get_config():
if fp_config_path.exists():
config_path = fp_config_path
elif pyshark_config_path.exists():
config_path = pyshark_config_path
else:
return None
config = ConfigParser()
config.read(config_path)
return config
|
Use `x_path.exists()` instead of `Path.exists(x)`.
|
Use `x_path.exists()` instead of `Path.exists(x)`.
|
Python
|
mit
|
KimiNewt/pyshark
|
from pathlib import Path
from configparser import ConfigParser
import pyshark
fp_config_path = Path.cwd() / 'config.ini' # get config from the current directory
pyshark_config_path = Path(pyshark.__file__).parent / 'config.ini'
def get_config():
if Path.exists(fp_config_path):
config_path = fp_config_path
elif Path.exists(pyshark_config_path):
config_path = pyshark_config_path
else:
return None
config = ConfigParser()
config.read(config_path)
return config
Use `x_path.exists()` instead of `Path.exists(x)`.
|
from pathlib import Path
from configparser import ConfigParser
import pyshark
fp_config_path = Path.cwd() / 'config.ini' # get config from the current directory
pyshark_config_path = Path(pyshark.__file__).parent / 'config.ini'
def get_config():
if fp_config_path.exists():
config_path = fp_config_path
elif pyshark_config_path.exists():
config_path = pyshark_config_path
else:
return None
config = ConfigParser()
config.read(config_path)
return config
|
<commit_before>from pathlib import Path
from configparser import ConfigParser
import pyshark
fp_config_path = Path.cwd() / 'config.ini' # get config from the current directory
pyshark_config_path = Path(pyshark.__file__).parent / 'config.ini'
def get_config():
if Path.exists(fp_config_path):
config_path = fp_config_path
elif Path.exists(pyshark_config_path):
config_path = pyshark_config_path
else:
return None
config = ConfigParser()
config.read(config_path)
return config
<commit_msg>Use `x_path.exists()` instead of `Path.exists(x)`.<commit_after>
|
from pathlib import Path
from configparser import ConfigParser
import pyshark
fp_config_path = Path.cwd() / 'config.ini' # get config from the current directory
pyshark_config_path = Path(pyshark.__file__).parent / 'config.ini'
def get_config():
if fp_config_path.exists():
config_path = fp_config_path
elif pyshark_config_path.exists():
config_path = pyshark_config_path
else:
return None
config = ConfigParser()
config.read(config_path)
return config
|
from pathlib import Path
from configparser import ConfigParser
import pyshark
fp_config_path = Path.cwd() / 'config.ini' # get config from the current directory
pyshark_config_path = Path(pyshark.__file__).parent / 'config.ini'
def get_config():
if Path.exists(fp_config_path):
config_path = fp_config_path
elif Path.exists(pyshark_config_path):
config_path = pyshark_config_path
else:
return None
config = ConfigParser()
config.read(config_path)
return config
Use `x_path.exists()` instead of `Path.exists(x)`.from pathlib import Path
from configparser import ConfigParser
import pyshark
fp_config_path = Path.cwd() / 'config.ini' # get config from the current directory
pyshark_config_path = Path(pyshark.__file__).parent / 'config.ini'
def get_config():
if fp_config_path.exists():
config_path = fp_config_path
elif pyshark_config_path.exists():
config_path = pyshark_config_path
else:
return None
config = ConfigParser()
config.read(config_path)
return config
|
<commit_before>from pathlib import Path
from configparser import ConfigParser
import pyshark
fp_config_path = Path.cwd() / 'config.ini' # get config from the current directory
pyshark_config_path = Path(pyshark.__file__).parent / 'config.ini'
def get_config():
if Path.exists(fp_config_path):
config_path = fp_config_path
elif Path.exists(pyshark_config_path):
config_path = pyshark_config_path
else:
return None
config = ConfigParser()
config.read(config_path)
return config
<commit_msg>Use `x_path.exists()` instead of `Path.exists(x)`.<commit_after>from pathlib import Path
from configparser import ConfigParser
import pyshark
fp_config_path = Path.cwd() / 'config.ini' # get config from the current directory
pyshark_config_path = Path(pyshark.__file__).parent / 'config.ini'
def get_config():
if fp_config_path.exists():
config_path = fp_config_path
elif pyshark_config_path.exists():
config_path = pyshark_config_path
else:
return None
config = ConfigParser()
config.read(config_path)
return config
|
003f646722233c49f4fa7c5d8bb313ae956a2c2a
|
content/test/gpu/gpu_tests/memory_expectations.py
|
content/test/gpu/gpu_tests/memory_expectations.py
|
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.page import test_expectations
# Valid expectation conditions are:
#
# Operating systems:
# win, xp, vista, win7, mac, leopard, snowleopard, lion, mountainlion,
# linux, chromeos, android
#
# GPU vendors:
# amd, arm, broadcom, hisilicon, intel, imagination, nvidia, qualcomm,
# vivante
#
# Specific GPUs can be listed as a tuple with vendor name and device ID.
# Examples: ('nvidia', 0x1234), ('arm', 'Mali-T604')
# Device IDs must be paired with a GPU vendor.
class MemoryExpectations(test_expectations.TestExpectations):
def SetExpectations(self):
# Sample Usage:
# self.Fail('Memory.CSS3D',
# ['mac', 'amd', ('nvidia', 0x1234)], bug=123)
self.Fail('Memory.CSS3D', ['mac', ('nvidia', 0x0fd5)], bug=368037)
|
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.page import test_expectations
# Valid expectation conditions are:
#
# Operating systems:
# win, xp, vista, win7, mac, leopard, snowleopard, lion, mountainlion,
# linux, chromeos, android
#
# GPU vendors:
# amd, arm, broadcom, hisilicon, intel, imagination, nvidia, qualcomm,
# vivante
#
# Specific GPUs can be listed as a tuple with vendor name and device ID.
# Examples: ('nvidia', 0x1234), ('arm', 'Mali-T604')
# Device IDs must be paired with a GPU vendor.
class MemoryExpectations(test_expectations.TestExpectations):
def SetExpectations(self):
# Sample Usage:
# self.Fail('Memory.CSS3D',
# ['mac', 'amd', ('nvidia', 0x1234)], bug=123)
self.Fail('Memory.CSS3D', ['mac', ('nvidia', 0x0fd5)], bug=368037)
# TODO(vmpstr): Memory drops and increases again, and this
# particular bot happens to catch it when its low. Remove
# once the bug is fixed.
self.Fail('Memory.CSS3D', ['win'], bug=373098)
|
Add a failure expectation to win memory.css3d test.
|
Add a failure expectation to win memory.css3d test.
In tile manager we seem to reach the memory limit early (with the
pending tree). However, when we activate our memory gets released
and we start filling it up again with the now active tree tiles.
The windows bot seems to catch the system at the moment when we're not
using a lot of memory, thus failing the test.
BUG=373098
R=kbr@chromium.org
Review URL: https://codereview.chromium.org/289003004
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@270962 0039d316-1c4b-4281-b951-d872f2087c98
|
Python
|
bsd-3-clause
|
dushu1203/chromium.src,jaruba/chromium.src,M4sse/chromium.src,bright-sparks/chromium-spacewalk,markYoungH/chromium.src,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk,fujunwei/chromium-crosswalk,M4sse/chromium.src,ondra-novak/chromium.src,crosswalk-project/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Chilledheart/chromium,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Jonekee/chromium.src,Jonekee/chromium.src,hgl888/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,TheTypoMaster/chromium-crosswalk,Jonekee/chromium.src,axinging/chromium-crosswalk,ltilve/chromium,dushu1203/chromium.src,dednal/chromium.src,Jonekee/chromium.src,krieger-od/nwjs_chromium.src,fujunwei/chromium-crosswalk,axinging/chromium-crosswalk,dushu1203/chromium.src,M4sse/chromium.src,hgl888/chromium-crosswalk,ondra-novak/chromium.src,Jonekee/chromium.src,Chilledheart/chromium,dednal/chromium.src,bright-sparks/chromium-spacewalk,jaruba/chromium.src,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk-efl,axinging/chromium-crosswalk,markYoungH/chromium.src,jaruba/chromium.src,bright-sparks/chromium-spacewalk,fujunwei/chromium-crosswalk,jaruba/chromium.src,chuan9/chromium-crosswalk,Pluto-tv/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk-efl,ltilve/chromium,Pluto-tv/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,littlstar/chromium.src,TheTypoMaster/chromium-crosswalk,littlstar/chromium.src,Fireblend/chromium-crosswalk,markYoungH/chromium.src,Jonekee/chromium.src,hgl888/chromium-crosswalk,markYoungH/chromium.src,Chilledheart/chromium,TheTypoMaster/chromium-crosswalk,Chilledheart/chromium,TheTypoMaster/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,ltilve/chromium,ondra-novak/chromium.src,bright-sparks/chromium-spacewalk,axinging/chromium-crosswalk,dednal/chromium.src,dednal/chromium.src,fujunwei/chromium-crosswalk,ondra-novak/chromium.src,Fireblend/chromium-crosswalk,Just-D/chromium-1,ltilve/chromium,Just-D/chromium-1,Pluto-tv/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,krieger-od/nwjs_chromium.src,jaruba/chromium.src,M4sse/chromium.src,dednal/chromium.src,Fireblend/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,jaruba/chromium.src,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk,Jonekee/chromium.src,axinging/chromium-crosswalk,hgl888/chromium-crosswalk,krieger-od/nwjs_chromium.src,markYoungH/chromium.src,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Jonekee/chromium.src,chuan9/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,M4sse/chromium.src,chuan9/chromium-crosswalk,dednal/chromium.src,PeterWangIntel/chromium-crosswalk,ondra-novak/chromium.src,bright-sparks/chromium-spacewalk,littlstar/chromium.src,mohamed--abdel-maksoud/chromium.src,markYoungH/chromium.src,Pluto-tv/chromium-crosswalk,ltilve/chromium,bright-sparks/chromium-spacewalk,axinging/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,ondra-novak/chromium.src,mohamed--abdel-maksoud/chromium.src,jaruba/chromium.src,krieger-od/nwjs_chromium.src,bright-sparks/chromium-spacewalk,M4sse/chromium.src,krieger-od/nwjs_chromium.src,markYoungH/chromium.src,markYoungH/chromium.src,markYoungH/chromium.src,Chilledheart/chromium,dushu1203/chromium.src,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,Pluto-tv/chromium-crosswalk,chuan9/chromium-crosswalk,littlstar/chromium.src,krieger-od/nwjs_chromium.src,Pluto-tv/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,dushu1203/chromium.src,dushu1203/chromium.src,chuan9/chromium-crosswalk,krieger-od/nwjs_chromium.src,crosswalk-project/chromium-crosswalk-efl,ltilve/chromium,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk-efl,Chilledheart/chromium,fujunwei/chromium-crosswalk,M4sse/chromium.src,mohamed--abdel-maksoud/chromium.src,Fireblend/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,ondra-novak/chromium.src,PeterWangIntel/chromium-crosswalk,krieger-od/nwjs_chromium.src,ltilve/chromium,Pluto-tv/chromium-crosswalk,dushu1203/chromium.src,ltilve/chromium,crosswalk-project/chromium-crosswalk-efl,markYoungH/chromium.src,Just-D/chromium-1,jaruba/chromium.src,krieger-od/nwjs_chromium.src,chuan9/chromium-crosswalk,M4sse/chromium.src,dednal/chromium.src,Just-D/chromium-1,dednal/chromium.src,dushu1203/chromium.src,Chilledheart/chromium,M4sse/chromium.src,ondra-novak/chromium.src,hgl888/chromium-crosswalk,Just-D/chromium-1,Pluto-tv/chromium-crosswalk,Fireblend/chromium-crosswalk,dednal/chromium.src,fujunwei/chromium-crosswalk,littlstar/chromium.src,hgl888/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,ondra-novak/chromium.src,ltilve/chromium,Pluto-tv/chromium-crosswalk,Jonekee/chromium.src,Chilledheart/chromium,hgl888/chromium-crosswalk-efl,M4sse/chromium.src,jaruba/chromium.src,littlstar/chromium.src,bright-sparks/chromium-spacewalk,Jonekee/chromium.src,Just-D/chromium-1,bright-sparks/chromium-spacewalk,PeterWangIntel/chromium-crosswalk,chuan9/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,littlstar/chromium.src,Just-D/chromium-1,Chilledheart/chromium,Fireblend/chromium-crosswalk,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,jaruba/chromium.src,axinging/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,dushu1203/chromium.src,axinging/chromium-crosswalk,Just-D/chromium-1,PeterWangIntel/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,krieger-od/nwjs_chromium.src,markYoungH/chromium.src,dednal/chromium.src,crosswalk-project/chromium-crosswalk-efl,dednal/chromium.src,dushu1203/chromium.src,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk-efl,littlstar/chromium.src,mohamed--abdel-maksoud/chromium.src,Jonekee/chromium.src,Just-D/chromium-1,M4sse/chromium.src,crosswalk-project/chromium-crosswalk-efl,dushu1203/chromium.src,PeterWangIntel/chromium-crosswalk
|
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.page import test_expectations
# Valid expectation conditions are:
#
# Operating systems:
# win, xp, vista, win7, mac, leopard, snowleopard, lion, mountainlion,
# linux, chromeos, android
#
# GPU vendors:
# amd, arm, broadcom, hisilicon, intel, imagination, nvidia, qualcomm,
# vivante
#
# Specific GPUs can be listed as a tuple with vendor name and device ID.
# Examples: ('nvidia', 0x1234), ('arm', 'Mali-T604')
# Device IDs must be paired with a GPU vendor.
class MemoryExpectations(test_expectations.TestExpectations):
def SetExpectations(self):
# Sample Usage:
# self.Fail('Memory.CSS3D',
# ['mac', 'amd', ('nvidia', 0x1234)], bug=123)
self.Fail('Memory.CSS3D', ['mac', ('nvidia', 0x0fd5)], bug=368037)
Add a failure expectation to win memory.css3d test.
In tile manager we seem to reach the memory limit early (with the
pending tree). However, when we activate our memory gets released
and we start filling it up again with the now active tree tiles.
The windows bot seems to catch the system at the moment when we're not
using a lot of memory, thus failing the test.
BUG=373098
R=kbr@chromium.org
Review URL: https://codereview.chromium.org/289003004
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@270962 0039d316-1c4b-4281-b951-d872f2087c98
|
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.page import test_expectations
# Valid expectation conditions are:
#
# Operating systems:
# win, xp, vista, win7, mac, leopard, snowleopard, lion, mountainlion,
# linux, chromeos, android
#
# GPU vendors:
# amd, arm, broadcom, hisilicon, intel, imagination, nvidia, qualcomm,
# vivante
#
# Specific GPUs can be listed as a tuple with vendor name and device ID.
# Examples: ('nvidia', 0x1234), ('arm', 'Mali-T604')
# Device IDs must be paired with a GPU vendor.
class MemoryExpectations(test_expectations.TestExpectations):
def SetExpectations(self):
# Sample Usage:
# self.Fail('Memory.CSS3D',
# ['mac', 'amd', ('nvidia', 0x1234)], bug=123)
self.Fail('Memory.CSS3D', ['mac', ('nvidia', 0x0fd5)], bug=368037)
# TODO(vmpstr): Memory drops and increases again, and this
# particular bot happens to catch it when its low. Remove
# once the bug is fixed.
self.Fail('Memory.CSS3D', ['win'], bug=373098)
|
<commit_before># Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.page import test_expectations
# Valid expectation conditions are:
#
# Operating systems:
# win, xp, vista, win7, mac, leopard, snowleopard, lion, mountainlion,
# linux, chromeos, android
#
# GPU vendors:
# amd, arm, broadcom, hisilicon, intel, imagination, nvidia, qualcomm,
# vivante
#
# Specific GPUs can be listed as a tuple with vendor name and device ID.
# Examples: ('nvidia', 0x1234), ('arm', 'Mali-T604')
# Device IDs must be paired with a GPU vendor.
class MemoryExpectations(test_expectations.TestExpectations):
def SetExpectations(self):
# Sample Usage:
# self.Fail('Memory.CSS3D',
# ['mac', 'amd', ('nvidia', 0x1234)], bug=123)
self.Fail('Memory.CSS3D', ['mac', ('nvidia', 0x0fd5)], bug=368037)
<commit_msg>Add a failure expectation to win memory.css3d test.
In tile manager we seem to reach the memory limit early (with the
pending tree). However, when we activate our memory gets released
and we start filling it up again with the now active tree tiles.
The windows bot seems to catch the system at the moment when we're not
using a lot of memory, thus failing the test.
BUG=373098
R=kbr@chromium.org
Review URL: https://codereview.chromium.org/289003004
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@270962 0039d316-1c4b-4281-b951-d872f2087c98<commit_after>
|
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.page import test_expectations
# Valid expectation conditions are:
#
# Operating systems:
# win, xp, vista, win7, mac, leopard, snowleopard, lion, mountainlion,
# linux, chromeos, android
#
# GPU vendors:
# amd, arm, broadcom, hisilicon, intel, imagination, nvidia, qualcomm,
# vivante
#
# Specific GPUs can be listed as a tuple with vendor name and device ID.
# Examples: ('nvidia', 0x1234), ('arm', 'Mali-T604')
# Device IDs must be paired with a GPU vendor.
class MemoryExpectations(test_expectations.TestExpectations):
def SetExpectations(self):
# Sample Usage:
# self.Fail('Memory.CSS3D',
# ['mac', 'amd', ('nvidia', 0x1234)], bug=123)
self.Fail('Memory.CSS3D', ['mac', ('nvidia', 0x0fd5)], bug=368037)
# TODO(vmpstr): Memory drops and increases again, and this
# particular bot happens to catch it when its low. Remove
# once the bug is fixed.
self.Fail('Memory.CSS3D', ['win'], bug=373098)
|
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.page import test_expectations
# Valid expectation conditions are:
#
# Operating systems:
# win, xp, vista, win7, mac, leopard, snowleopard, lion, mountainlion,
# linux, chromeos, android
#
# GPU vendors:
# amd, arm, broadcom, hisilicon, intel, imagination, nvidia, qualcomm,
# vivante
#
# Specific GPUs can be listed as a tuple with vendor name and device ID.
# Examples: ('nvidia', 0x1234), ('arm', 'Mali-T604')
# Device IDs must be paired with a GPU vendor.
class MemoryExpectations(test_expectations.TestExpectations):
def SetExpectations(self):
# Sample Usage:
# self.Fail('Memory.CSS3D',
# ['mac', 'amd', ('nvidia', 0x1234)], bug=123)
self.Fail('Memory.CSS3D', ['mac', ('nvidia', 0x0fd5)], bug=368037)
Add a failure expectation to win memory.css3d test.
In tile manager we seem to reach the memory limit early (with the
pending tree). However, when we activate our memory gets released
and we start filling it up again with the now active tree tiles.
The windows bot seems to catch the system at the moment when we're not
using a lot of memory, thus failing the test.
BUG=373098
R=kbr@chromium.org
Review URL: https://codereview.chromium.org/289003004
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@270962 0039d316-1c4b-4281-b951-d872f2087c98# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.page import test_expectations
# Valid expectation conditions are:
#
# Operating systems:
# win, xp, vista, win7, mac, leopard, snowleopard, lion, mountainlion,
# linux, chromeos, android
#
# GPU vendors:
# amd, arm, broadcom, hisilicon, intel, imagination, nvidia, qualcomm,
# vivante
#
# Specific GPUs can be listed as a tuple with vendor name and device ID.
# Examples: ('nvidia', 0x1234), ('arm', 'Mali-T604')
# Device IDs must be paired with a GPU vendor.
class MemoryExpectations(test_expectations.TestExpectations):
def SetExpectations(self):
# Sample Usage:
# self.Fail('Memory.CSS3D',
# ['mac', 'amd', ('nvidia', 0x1234)], bug=123)
self.Fail('Memory.CSS3D', ['mac', ('nvidia', 0x0fd5)], bug=368037)
# TODO(vmpstr): Memory drops and increases again, and this
# particular bot happens to catch it when its low. Remove
# once the bug is fixed.
self.Fail('Memory.CSS3D', ['win'], bug=373098)
|
<commit_before># Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.page import test_expectations
# Valid expectation conditions are:
#
# Operating systems:
# win, xp, vista, win7, mac, leopard, snowleopard, lion, mountainlion,
# linux, chromeos, android
#
# GPU vendors:
# amd, arm, broadcom, hisilicon, intel, imagination, nvidia, qualcomm,
# vivante
#
# Specific GPUs can be listed as a tuple with vendor name and device ID.
# Examples: ('nvidia', 0x1234), ('arm', 'Mali-T604')
# Device IDs must be paired with a GPU vendor.
class MemoryExpectations(test_expectations.TestExpectations):
def SetExpectations(self):
# Sample Usage:
# self.Fail('Memory.CSS3D',
# ['mac', 'amd', ('nvidia', 0x1234)], bug=123)
self.Fail('Memory.CSS3D', ['mac', ('nvidia', 0x0fd5)], bug=368037)
<commit_msg>Add a failure expectation to win memory.css3d test.
In tile manager we seem to reach the memory limit early (with the
pending tree). However, when we activate our memory gets released
and we start filling it up again with the now active tree tiles.
The windows bot seems to catch the system at the moment when we're not
using a lot of memory, thus failing the test.
BUG=373098
R=kbr@chromium.org
Review URL: https://codereview.chromium.org/289003004
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@270962 0039d316-1c4b-4281-b951-d872f2087c98<commit_after># Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.page import test_expectations
# Valid expectation conditions are:
#
# Operating systems:
# win, xp, vista, win7, mac, leopard, snowleopard, lion, mountainlion,
# linux, chromeos, android
#
# GPU vendors:
# amd, arm, broadcom, hisilicon, intel, imagination, nvidia, qualcomm,
# vivante
#
# Specific GPUs can be listed as a tuple with vendor name and device ID.
# Examples: ('nvidia', 0x1234), ('arm', 'Mali-T604')
# Device IDs must be paired with a GPU vendor.
class MemoryExpectations(test_expectations.TestExpectations):
def SetExpectations(self):
# Sample Usage:
# self.Fail('Memory.CSS3D',
# ['mac', 'amd', ('nvidia', 0x1234)], bug=123)
self.Fail('Memory.CSS3D', ['mac', ('nvidia', 0x0fd5)], bug=368037)
# TODO(vmpstr): Memory drops and increases again, and this
# particular bot happens to catch it when its low. Remove
# once the bug is fixed.
self.Fail('Memory.CSS3D', ['win'], bug=373098)
|
cf8f3dc4d2cde04a1f822627db522c1b021c3359
|
dataset/__init__.py
|
dataset/__init__.py
|
# shut up useless SA warning:
import warnings
warnings.filterwarnings(
'ignore', 'Unicode type received non-unicode bind param value.')
from dataset.persistence.database import Database
from dataset.persistence.table import Table
from dataset.freeze.app import freeze
__all__ = ['Database', 'Table', 'freeze', 'connect']
def connect(url, reflectMetadata=True):
"""
Opens a new connection to a database. *url* can be any valid `SQLAlchemy engine URL`_. Returns
an instance of :py:class:`Database <dataset.Database>`. Set *reflectMetadata* to False if you
don't want the entire database schema to be pre-loaded. This significantly speeds up
connecting to large databases with lots of tables.
::
db = dataset.connect('sqlite:///factbook.db')
.. _SQLAlchemy Engine URL: http://docs.sqlalchemy.org/en/latest/core/engines.html#sqlalchemy.create_engine
"""
return Database(url, reflectMetadata)
|
import os
# shut up useless SA warning:
import warnings
warnings.filterwarnings(
'ignore', 'Unicode type received non-unicode bind param value.')
from dataset.persistence.database import Database
from dataset.persistence.table import Table
from dataset.freeze.app import freeze
__all__ = ['Database', 'Table', 'freeze', 'connect']
def connect(url=None, reflectMetadata=True):
"""
Opens a new connection to a database. *url* can be any valid `SQLAlchemy engine URL`_.
If *url* is not defined it will try to use *DATABASE_URL* from environment variable.
Returns an instance of :py:class:`Database <dataset.Database>`. Set *reflectMetadata* to False if you
don't want the entire database schema to be pre-loaded. This significantly speeds up
connecting to large databases with lots of tables.
::
db = dataset.connect('sqlite:///factbook.db')
.. _SQLAlchemy Engine URL: http://docs.sqlalchemy.org/en/latest/core/engines.html#sqlalchemy.create_engine
"""
url = os.environ.get('DATABASE_URL', url)
return Database(url, reflectMetadata)
|
Allow to use `url` defined as env variable.
|
Allow to use `url` defined as env variable.
|
Python
|
mit
|
pudo/dataset,askebos/dataset,twds/dataset,vguzmanp/dataset,stefanw/dataset,saimn/dataset,reubano/dataset
|
# shut up useless SA warning:
import warnings
warnings.filterwarnings(
'ignore', 'Unicode type received non-unicode bind param value.')
from dataset.persistence.database import Database
from dataset.persistence.table import Table
from dataset.freeze.app import freeze
__all__ = ['Database', 'Table', 'freeze', 'connect']
def connect(url, reflectMetadata=True):
"""
Opens a new connection to a database. *url* can be any valid `SQLAlchemy engine URL`_. Returns
an instance of :py:class:`Database <dataset.Database>`. Set *reflectMetadata* to False if you
don't want the entire database schema to be pre-loaded. This significantly speeds up
connecting to large databases with lots of tables.
::
db = dataset.connect('sqlite:///factbook.db')
.. _SQLAlchemy Engine URL: http://docs.sqlalchemy.org/en/latest/core/engines.html#sqlalchemy.create_engine
"""
return Database(url, reflectMetadata)
Allow to use `url` defined as env variable.
|
import os
# shut up useless SA warning:
import warnings
warnings.filterwarnings(
'ignore', 'Unicode type received non-unicode bind param value.')
from dataset.persistence.database import Database
from dataset.persistence.table import Table
from dataset.freeze.app import freeze
__all__ = ['Database', 'Table', 'freeze', 'connect']
def connect(url=None, reflectMetadata=True):
"""
Opens a new connection to a database. *url* can be any valid `SQLAlchemy engine URL`_.
If *url* is not defined it will try to use *DATABASE_URL* from environment variable.
Returns an instance of :py:class:`Database <dataset.Database>`. Set *reflectMetadata* to False if you
don't want the entire database schema to be pre-loaded. This significantly speeds up
connecting to large databases with lots of tables.
::
db = dataset.connect('sqlite:///factbook.db')
.. _SQLAlchemy Engine URL: http://docs.sqlalchemy.org/en/latest/core/engines.html#sqlalchemy.create_engine
"""
url = os.environ.get('DATABASE_URL', url)
return Database(url, reflectMetadata)
|
<commit_before># shut up useless SA warning:
import warnings
warnings.filterwarnings(
'ignore', 'Unicode type received non-unicode bind param value.')
from dataset.persistence.database import Database
from dataset.persistence.table import Table
from dataset.freeze.app import freeze
__all__ = ['Database', 'Table', 'freeze', 'connect']
def connect(url, reflectMetadata=True):
"""
Opens a new connection to a database. *url* can be any valid `SQLAlchemy engine URL`_. Returns
an instance of :py:class:`Database <dataset.Database>`. Set *reflectMetadata* to False if you
don't want the entire database schema to be pre-loaded. This significantly speeds up
connecting to large databases with lots of tables.
::
db = dataset.connect('sqlite:///factbook.db')
.. _SQLAlchemy Engine URL: http://docs.sqlalchemy.org/en/latest/core/engines.html#sqlalchemy.create_engine
"""
return Database(url, reflectMetadata)
<commit_msg>Allow to use `url` defined as env variable.<commit_after>
|
import os
# shut up useless SA warning:
import warnings
warnings.filterwarnings(
'ignore', 'Unicode type received non-unicode bind param value.')
from dataset.persistence.database import Database
from dataset.persistence.table import Table
from dataset.freeze.app import freeze
__all__ = ['Database', 'Table', 'freeze', 'connect']
def connect(url=None, reflectMetadata=True):
"""
Opens a new connection to a database. *url* can be any valid `SQLAlchemy engine URL`_.
If *url* is not defined it will try to use *DATABASE_URL* from environment variable.
Returns an instance of :py:class:`Database <dataset.Database>`. Set *reflectMetadata* to False if you
don't want the entire database schema to be pre-loaded. This significantly speeds up
connecting to large databases with lots of tables.
::
db = dataset.connect('sqlite:///factbook.db')
.. _SQLAlchemy Engine URL: http://docs.sqlalchemy.org/en/latest/core/engines.html#sqlalchemy.create_engine
"""
url = os.environ.get('DATABASE_URL', url)
return Database(url, reflectMetadata)
|
# shut up useless SA warning:
import warnings
warnings.filterwarnings(
'ignore', 'Unicode type received non-unicode bind param value.')
from dataset.persistence.database import Database
from dataset.persistence.table import Table
from dataset.freeze.app import freeze
__all__ = ['Database', 'Table', 'freeze', 'connect']
def connect(url, reflectMetadata=True):
"""
Opens a new connection to a database. *url* can be any valid `SQLAlchemy engine URL`_. Returns
an instance of :py:class:`Database <dataset.Database>`. Set *reflectMetadata* to False if you
don't want the entire database schema to be pre-loaded. This significantly speeds up
connecting to large databases with lots of tables.
::
db = dataset.connect('sqlite:///factbook.db')
.. _SQLAlchemy Engine URL: http://docs.sqlalchemy.org/en/latest/core/engines.html#sqlalchemy.create_engine
"""
return Database(url, reflectMetadata)
Allow to use `url` defined as env variable.import os
# shut up useless SA warning:
import warnings
warnings.filterwarnings(
'ignore', 'Unicode type received non-unicode bind param value.')
from dataset.persistence.database import Database
from dataset.persistence.table import Table
from dataset.freeze.app import freeze
__all__ = ['Database', 'Table', 'freeze', 'connect']
def connect(url=None, reflectMetadata=True):
"""
Opens a new connection to a database. *url* can be any valid `SQLAlchemy engine URL`_.
If *url* is not defined it will try to use *DATABASE_URL* from environment variable.
Returns an instance of :py:class:`Database <dataset.Database>`. Set *reflectMetadata* to False if you
don't want the entire database schema to be pre-loaded. This significantly speeds up
connecting to large databases with lots of tables.
::
db = dataset.connect('sqlite:///factbook.db')
.. _SQLAlchemy Engine URL: http://docs.sqlalchemy.org/en/latest/core/engines.html#sqlalchemy.create_engine
"""
url = os.environ.get('DATABASE_URL', url)
return Database(url, reflectMetadata)
|
<commit_before># shut up useless SA warning:
import warnings
warnings.filterwarnings(
'ignore', 'Unicode type received non-unicode bind param value.')
from dataset.persistence.database import Database
from dataset.persistence.table import Table
from dataset.freeze.app import freeze
__all__ = ['Database', 'Table', 'freeze', 'connect']
def connect(url, reflectMetadata=True):
"""
Opens a new connection to a database. *url* can be any valid `SQLAlchemy engine URL`_. Returns
an instance of :py:class:`Database <dataset.Database>`. Set *reflectMetadata* to False if you
don't want the entire database schema to be pre-loaded. This significantly speeds up
connecting to large databases with lots of tables.
::
db = dataset.connect('sqlite:///factbook.db')
.. _SQLAlchemy Engine URL: http://docs.sqlalchemy.org/en/latest/core/engines.html#sqlalchemy.create_engine
"""
return Database(url, reflectMetadata)
<commit_msg>Allow to use `url` defined as env variable.<commit_after>import os
# shut up useless SA warning:
import warnings
warnings.filterwarnings(
'ignore', 'Unicode type received non-unicode bind param value.')
from dataset.persistence.database import Database
from dataset.persistence.table import Table
from dataset.freeze.app import freeze
__all__ = ['Database', 'Table', 'freeze', 'connect']
def connect(url=None, reflectMetadata=True):
"""
Opens a new connection to a database. *url* can be any valid `SQLAlchemy engine URL`_.
If *url* is not defined it will try to use *DATABASE_URL* from environment variable.
Returns an instance of :py:class:`Database <dataset.Database>`. Set *reflectMetadata* to False if you
don't want the entire database schema to be pre-loaded. This significantly speeds up
connecting to large databases with lots of tables.
::
db = dataset.connect('sqlite:///factbook.db')
.. _SQLAlchemy Engine URL: http://docs.sqlalchemy.org/en/latest/core/engines.html#sqlalchemy.create_engine
"""
url = os.environ.get('DATABASE_URL', url)
return Database(url, reflectMetadata)
|
d5765d0d961aa32f783f6c2a61c86a6adf282b62
|
dipy/core/histeq.py
|
dipy/core/histeq.py
|
import numpy as np
def histeq(im, num_bins=256):
"""
Performs an histogram equalization on ``img``.
This was taken from:
http://www.janeriksolem.net/2009/06/histogram-equalization-with-python-and.html
Parameters
----------
im : ndarray
Image on which to perform histogram equalization.
num_bins : int
Number of bins used to construct the histogram.
Returns
-------
result : ndarray
Histogram equalized image.
"""
#get image histogram
histo, bins = np.histogram(im.flatten(), num_bins, normed=True)
cdf = histo.cumsum()
cdf = 255 * cdf / cdf[-1]
#use linear interpolation of cdf to find new pixel values
result = np.interp(im.flatten(), bins[:-1], cdf)
return result.reshape(im.shape)
|
import numpy as np
def histeq(arr, num_bins=256):
""" Performs an histogram equalization on ``arr``.
This was taken from:
http://www.janeriksolem.net/2009/06/histogram-equalization-with-python-and.html
Parameters
----------
arr : ndarray
Image on which to perform histogram equalization.
num_bins : int
Number of bins used to construct the histogram.
Returns
-------
result : ndarray
Histogram equalized image.
"""
#get image histogram
histo, bins = np.histogram(arr.flatten(), num_bins, normed=True)
cdf = histo.cumsum()
cdf = 255 * cdf / cdf[-1]
#use linear interpolation of cdf to find new pixel values
result = np.interp(arr.flatten(), bins[:-1], cdf)
return result.reshape(arr.shape)
|
Fix comment format and input var name.
|
Fix comment format and input var name.
|
Python
|
bsd-3-clause
|
JohnGriffiths/dipy,demianw/dipy,oesteban/dipy,jyeatman/dipy,nilgoyyou/dipy,sinkpoint/dipy,matthieudumont/dipy,FrancoisRheaultUS/dipy,rfdougherty/dipy,mdesco/dipy,beni55/dipy,StongeEtienne/dipy,rfdougherty/dipy,samuelstjean/dipy,nilgoyyou/dipy,beni55/dipy,StongeEtienne/dipy,villalonreina/dipy,demianw/dipy,matthieudumont/dipy,villalonreina/dipy,samuelstjean/dipy,Messaoud-Boudjada/dipy,jyeatman/dipy,FrancoisRheaultUS/dipy,oesteban/dipy,mdesco/dipy,sinkpoint/dipy,samuelstjean/dipy,Messaoud-Boudjada/dipy,JohnGriffiths/dipy
|
import numpy as np
def histeq(im, num_bins=256):
"""
Performs an histogram equalization on ``img``.
This was taken from:
http://www.janeriksolem.net/2009/06/histogram-equalization-with-python-and.html
Parameters
----------
im : ndarray
Image on which to perform histogram equalization.
num_bins : int
Number of bins used to construct the histogram.
Returns
-------
result : ndarray
Histogram equalized image.
"""
#get image histogram
histo, bins = np.histogram(im.flatten(), num_bins, normed=True)
cdf = histo.cumsum()
cdf = 255 * cdf / cdf[-1]
#use linear interpolation of cdf to find new pixel values
result = np.interp(im.flatten(), bins[:-1], cdf)
return result.reshape(im.shape)
Fix comment format and input var name.
|
import numpy as np
def histeq(arr, num_bins=256):
""" Performs an histogram equalization on ``arr``.
This was taken from:
http://www.janeriksolem.net/2009/06/histogram-equalization-with-python-and.html
Parameters
----------
arr : ndarray
Image on which to perform histogram equalization.
num_bins : int
Number of bins used to construct the histogram.
Returns
-------
result : ndarray
Histogram equalized image.
"""
#get image histogram
histo, bins = np.histogram(arr.flatten(), num_bins, normed=True)
cdf = histo.cumsum()
cdf = 255 * cdf / cdf[-1]
#use linear interpolation of cdf to find new pixel values
result = np.interp(arr.flatten(), bins[:-1], cdf)
return result.reshape(arr.shape)
|
<commit_before>import numpy as np
def histeq(im, num_bins=256):
"""
Performs an histogram equalization on ``img``.
This was taken from:
http://www.janeriksolem.net/2009/06/histogram-equalization-with-python-and.html
Parameters
----------
im : ndarray
Image on which to perform histogram equalization.
num_bins : int
Number of bins used to construct the histogram.
Returns
-------
result : ndarray
Histogram equalized image.
"""
#get image histogram
histo, bins = np.histogram(im.flatten(), num_bins, normed=True)
cdf = histo.cumsum()
cdf = 255 * cdf / cdf[-1]
#use linear interpolation of cdf to find new pixel values
result = np.interp(im.flatten(), bins[:-1], cdf)
return result.reshape(im.shape)
<commit_msg>Fix comment format and input var name.<commit_after>
|
import numpy as np
def histeq(arr, num_bins=256):
""" Performs an histogram equalization on ``arr``.
This was taken from:
http://www.janeriksolem.net/2009/06/histogram-equalization-with-python-and.html
Parameters
----------
arr : ndarray
Image on which to perform histogram equalization.
num_bins : int
Number of bins used to construct the histogram.
Returns
-------
result : ndarray
Histogram equalized image.
"""
#get image histogram
histo, bins = np.histogram(arr.flatten(), num_bins, normed=True)
cdf = histo.cumsum()
cdf = 255 * cdf / cdf[-1]
#use linear interpolation of cdf to find new pixel values
result = np.interp(arr.flatten(), bins[:-1], cdf)
return result.reshape(arr.shape)
|
import numpy as np
def histeq(im, num_bins=256):
"""
Performs an histogram equalization on ``img``.
This was taken from:
http://www.janeriksolem.net/2009/06/histogram-equalization-with-python-and.html
Parameters
----------
im : ndarray
Image on which to perform histogram equalization.
num_bins : int
Number of bins used to construct the histogram.
Returns
-------
result : ndarray
Histogram equalized image.
"""
#get image histogram
histo, bins = np.histogram(im.flatten(), num_bins, normed=True)
cdf = histo.cumsum()
cdf = 255 * cdf / cdf[-1]
#use linear interpolation of cdf to find new pixel values
result = np.interp(im.flatten(), bins[:-1], cdf)
return result.reshape(im.shape)
Fix comment format and input var name.import numpy as np
def histeq(arr, num_bins=256):
""" Performs an histogram equalization on ``arr``.
This was taken from:
http://www.janeriksolem.net/2009/06/histogram-equalization-with-python-and.html
Parameters
----------
arr : ndarray
Image on which to perform histogram equalization.
num_bins : int
Number of bins used to construct the histogram.
Returns
-------
result : ndarray
Histogram equalized image.
"""
#get image histogram
histo, bins = np.histogram(arr.flatten(), num_bins, normed=True)
cdf = histo.cumsum()
cdf = 255 * cdf / cdf[-1]
#use linear interpolation of cdf to find new pixel values
result = np.interp(arr.flatten(), bins[:-1], cdf)
return result.reshape(arr.shape)
|
<commit_before>import numpy as np
def histeq(im, num_bins=256):
"""
Performs an histogram equalization on ``img``.
This was taken from:
http://www.janeriksolem.net/2009/06/histogram-equalization-with-python-and.html
Parameters
----------
im : ndarray
Image on which to perform histogram equalization.
num_bins : int
Number of bins used to construct the histogram.
Returns
-------
result : ndarray
Histogram equalized image.
"""
#get image histogram
histo, bins = np.histogram(im.flatten(), num_bins, normed=True)
cdf = histo.cumsum()
cdf = 255 * cdf / cdf[-1]
#use linear interpolation of cdf to find new pixel values
result = np.interp(im.flatten(), bins[:-1], cdf)
return result.reshape(im.shape)
<commit_msg>Fix comment format and input var name.<commit_after>import numpy as np
def histeq(arr, num_bins=256):
""" Performs an histogram equalization on ``arr``.
This was taken from:
http://www.janeriksolem.net/2009/06/histogram-equalization-with-python-and.html
Parameters
----------
arr : ndarray
Image on which to perform histogram equalization.
num_bins : int
Number of bins used to construct the histogram.
Returns
-------
result : ndarray
Histogram equalized image.
"""
#get image histogram
histo, bins = np.histogram(arr.flatten(), num_bins, normed=True)
cdf = histo.cumsum()
cdf = 255 * cdf / cdf[-1]
#use linear interpolation of cdf to find new pixel values
result = np.interp(arr.flatten(), bins[:-1], cdf)
return result.reshape(arr.shape)
|
8a4165f2d7a252e6f3de3fd82b215e46d532a237
|
lms/djangoapps/grades/migrations/0005_multiple_course_flags.py
|
lms/djangoapps/grades/migrations/0005_multiple_course_flags.py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from openedx.core.djangoapps.xmodule_django.models import CourseKeyField
class Migration(migrations.Migration):
dependencies = [
('grades', '0004_visibleblocks_course_id'),
]
operations = [
migrations.AlterField(
model_name='coursepersistentgradesflag',
name='course_id',
field=CourseKeyField(max_length=255, db_index=True),
),
]
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from openedx.core.djangoapps.xmodule_django.models import CourseKeyField
class Migration(migrations.Migration):
dependencies = [
('grades', '0004_visibleblocks_course_id'),
]
operations = [
migrations.AlterField(
model_name='coursepersistentgradesflag',
name='course_id',
field=CourseKeyField(max_length=255, db_index=True),
),
]
def unapply(self, project_state, schema_editor, collect_sql=False):
"""
This is a bit of a hack. This migration is removing a unique index that was erroneously included in the initial
migrations for this app, so it's very likely that IntegrityErrors would result if we did roll this particular
migration back. To avoid this, we override the default unapply method and skip the addition of a unique index
that was never intended to exist.
The assumption here is that you are never going to be specifically targeting a migration < 0005 for grades,
and will only ever be migrating backwards if you intend to go all the way back to zero and drop the tables.
If this is not the case and you are reading this comment, please file a PR to help us with your intended usage.
"""
pass
|
Allow grades app to be zero-migrated
|
Allow grades app to be zero-migrated
|
Python
|
agpl-3.0
|
ahmedaljazzar/edx-platform,gymnasium/edx-platform,gsehub/edx-platform,jzoldak/edx-platform,pabloborrego93/edx-platform,fintech-circle/edx-platform,ESOedX/edx-platform,stvstnfrd/edx-platform,philanthropy-u/edx-platform,kmoocdev2/edx-platform,appsembler/edx-platform,amir-qayyum-khan/edx-platform,pepeportela/edx-platform,BehavioralInsightsTeam/edx-platform,Stanford-Online/edx-platform,edx/edx-platform,synergeticsedx/deployment-wipro,EDUlib/edx-platform,philanthropy-u/edx-platform,cpennington/edx-platform,edx-solutions/edx-platform,edx/edx-platform,gsehub/edx-platform,caesar2164/edx-platform,naresh21/synergetics-edx-platform,raccoongang/edx-platform,appsembler/edx-platform,naresh21/synergetics-edx-platform,kmoocdev2/edx-platform,eduNEXT/edunext-platform,angelapper/edx-platform,msegado/edx-platform,gymnasium/edx-platform,Stanford-Online/edx-platform,caesar2164/edx-platform,romain-li/edx-platform,gymnasium/edx-platform,kmoocdev2/edx-platform,miptliot/edx-platform,Edraak/edraak-platform,proversity-org/edx-platform,pepeportela/edx-platform,gsehub/edx-platform,CredoReference/edx-platform,prarthitm/edxplatform,EDUlib/edx-platform,raccoongang/edx-platform,stvstnfrd/edx-platform,teltek/edx-platform,pepeportela/edx-platform,miptliot/edx-platform,eduNEXT/edx-platform,teltek/edx-platform,edx/edx-platform,stvstnfrd/edx-platform,cpennington/edx-platform,CredoReference/edx-platform,msegado/edx-platform,jzoldak/edx-platform,ESOedX/edx-platform,amir-qayyum-khan/edx-platform,caesar2164/edx-platform,caesar2164/edx-platform,fintech-circle/edx-platform,angelapper/edx-platform,eduNEXT/edunext-platform,edx-solutions/edx-platform,a-parhom/edx-platform,synergeticsedx/deployment-wipro,prarthitm/edxplatform,BehavioralInsightsTeam/edx-platform,arbrandes/edx-platform,edx/edx-platform,mitocw/edx-platform,Edraak/edraak-platform,appsembler/edx-platform,romain-li/edx-platform,teltek/edx-platform,jzoldak/edx-platform,lduarte1991/edx-platform,hastexo/edx-platform,a-parhom/edx-platform,TeachAtTUM/edx-platform,teltek/edx-platform,ESOedX/edx-platform,Edraak/edraak-platform,proversity-org/edx-platform,prarthitm/edxplatform,ahmedaljazzar/edx-platform,procangroup/edx-platform,msegado/edx-platform,BehavioralInsightsTeam/edx-platform,TeachAtTUM/edx-platform,pabloborrego93/edx-platform,ahmedaljazzar/edx-platform,jolyonb/edx-platform,eduNEXT/edunext-platform,arbrandes/edx-platform,TeachAtTUM/edx-platform,proversity-org/edx-platform,naresh21/synergetics-edx-platform,TeachAtTUM/edx-platform,procangroup/edx-platform,synergeticsedx/deployment-wipro,miptliot/edx-platform,edx-solutions/edx-platform,hastexo/edx-platform,a-parhom/edx-platform,eduNEXT/edx-platform,proversity-org/edx-platform,edx-solutions/edx-platform,kmoocdev2/edx-platform,lduarte1991/edx-platform,EDUlib/edx-platform,fintech-circle/edx-platform,eduNEXT/edunext-platform,eduNEXT/edx-platform,philanthropy-u/edx-platform,ahmedaljazzar/edx-platform,fintech-circle/edx-platform,romain-li/edx-platform,arbrandes/edx-platform,jolyonb/edx-platform,BehavioralInsightsTeam/edx-platform,jolyonb/edx-platform,Stanford-Online/edx-platform,lduarte1991/edx-platform,msegado/edx-platform,romain-li/edx-platform,mitocw/edx-platform,CredoReference/edx-platform,Lektorium-LLC/edx-platform,pabloborrego93/edx-platform,pepeportela/edx-platform,angelapper/edx-platform,cpennington/edx-platform,msegado/edx-platform,lduarte1991/edx-platform,mitocw/edx-platform,Lektorium-LLC/edx-platform,jzoldak/edx-platform,cpennington/edx-platform,philanthropy-u/edx-platform,EDUlib/edx-platform,naresh21/synergetics-edx-platform,CredoReference/edx-platform,Edraak/edraak-platform,Lektorium-LLC/edx-platform,procangroup/edx-platform,gymnasium/edx-platform,kmoocdev2/edx-platform,angelapper/edx-platform,pabloborrego93/edx-platform,romain-li/edx-platform,eduNEXT/edx-platform,ESOedX/edx-platform,synergeticsedx/deployment-wipro,prarthitm/edxplatform,miptliot/edx-platform,appsembler/edx-platform,Lektorium-LLC/edx-platform,amir-qayyum-khan/edx-platform,raccoongang/edx-platform,gsehub/edx-platform,raccoongang/edx-platform,hastexo/edx-platform,hastexo/edx-platform,procangroup/edx-platform,a-parhom/edx-platform,mitocw/edx-platform,jolyonb/edx-platform,Stanford-Online/edx-platform,stvstnfrd/edx-platform,amir-qayyum-khan/edx-platform,arbrandes/edx-platform
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from openedx.core.djangoapps.xmodule_django.models import CourseKeyField
class Migration(migrations.Migration):
dependencies = [
('grades', '0004_visibleblocks_course_id'),
]
operations = [
migrations.AlterField(
model_name='coursepersistentgradesflag',
name='course_id',
field=CourseKeyField(max_length=255, db_index=True),
),
]
Allow grades app to be zero-migrated
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from openedx.core.djangoapps.xmodule_django.models import CourseKeyField
class Migration(migrations.Migration):
dependencies = [
('grades', '0004_visibleblocks_course_id'),
]
operations = [
migrations.AlterField(
model_name='coursepersistentgradesflag',
name='course_id',
field=CourseKeyField(max_length=255, db_index=True),
),
]
def unapply(self, project_state, schema_editor, collect_sql=False):
"""
This is a bit of a hack. This migration is removing a unique index that was erroneously included in the initial
migrations for this app, so it's very likely that IntegrityErrors would result if we did roll this particular
migration back. To avoid this, we override the default unapply method and skip the addition of a unique index
that was never intended to exist.
The assumption here is that you are never going to be specifically targeting a migration < 0005 for grades,
and will only ever be migrating backwards if you intend to go all the way back to zero and drop the tables.
If this is not the case and you are reading this comment, please file a PR to help us with your intended usage.
"""
pass
|
<commit_before># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from openedx.core.djangoapps.xmodule_django.models import CourseKeyField
class Migration(migrations.Migration):
dependencies = [
('grades', '0004_visibleblocks_course_id'),
]
operations = [
migrations.AlterField(
model_name='coursepersistentgradesflag',
name='course_id',
field=CourseKeyField(max_length=255, db_index=True),
),
]
<commit_msg>Allow grades app to be zero-migrated<commit_after>
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from openedx.core.djangoapps.xmodule_django.models import CourseKeyField
class Migration(migrations.Migration):
dependencies = [
('grades', '0004_visibleblocks_course_id'),
]
operations = [
migrations.AlterField(
model_name='coursepersistentgradesflag',
name='course_id',
field=CourseKeyField(max_length=255, db_index=True),
),
]
def unapply(self, project_state, schema_editor, collect_sql=False):
"""
This is a bit of a hack. This migration is removing a unique index that was erroneously included in the initial
migrations for this app, so it's very likely that IntegrityErrors would result if we did roll this particular
migration back. To avoid this, we override the default unapply method and skip the addition of a unique index
that was never intended to exist.
The assumption here is that you are never going to be specifically targeting a migration < 0005 for grades,
and will only ever be migrating backwards if you intend to go all the way back to zero and drop the tables.
If this is not the case and you are reading this comment, please file a PR to help us with your intended usage.
"""
pass
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from openedx.core.djangoapps.xmodule_django.models import CourseKeyField
class Migration(migrations.Migration):
dependencies = [
('grades', '0004_visibleblocks_course_id'),
]
operations = [
migrations.AlterField(
model_name='coursepersistentgradesflag',
name='course_id',
field=CourseKeyField(max_length=255, db_index=True),
),
]
Allow grades app to be zero-migrated# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from openedx.core.djangoapps.xmodule_django.models import CourseKeyField
class Migration(migrations.Migration):
dependencies = [
('grades', '0004_visibleblocks_course_id'),
]
operations = [
migrations.AlterField(
model_name='coursepersistentgradesflag',
name='course_id',
field=CourseKeyField(max_length=255, db_index=True),
),
]
def unapply(self, project_state, schema_editor, collect_sql=False):
"""
This is a bit of a hack. This migration is removing a unique index that was erroneously included in the initial
migrations for this app, so it's very likely that IntegrityErrors would result if we did roll this particular
migration back. To avoid this, we override the default unapply method and skip the addition of a unique index
that was never intended to exist.
The assumption here is that you are never going to be specifically targeting a migration < 0005 for grades,
and will only ever be migrating backwards if you intend to go all the way back to zero and drop the tables.
If this is not the case and you are reading this comment, please file a PR to help us with your intended usage.
"""
pass
|
<commit_before># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from openedx.core.djangoapps.xmodule_django.models import CourseKeyField
class Migration(migrations.Migration):
dependencies = [
('grades', '0004_visibleblocks_course_id'),
]
operations = [
migrations.AlterField(
model_name='coursepersistentgradesflag',
name='course_id',
field=CourseKeyField(max_length=255, db_index=True),
),
]
<commit_msg>Allow grades app to be zero-migrated<commit_after># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from openedx.core.djangoapps.xmodule_django.models import CourseKeyField
class Migration(migrations.Migration):
dependencies = [
('grades', '0004_visibleblocks_course_id'),
]
operations = [
migrations.AlterField(
model_name='coursepersistentgradesflag',
name='course_id',
field=CourseKeyField(max_length=255, db_index=True),
),
]
def unapply(self, project_state, schema_editor, collect_sql=False):
"""
This is a bit of a hack. This migration is removing a unique index that was erroneously included in the initial
migrations for this app, so it's very likely that IntegrityErrors would result if we did roll this particular
migration back. To avoid this, we override the default unapply method and skip the addition of a unique index
that was never intended to exist.
The assumption here is that you are never going to be specifically targeting a migration < 0005 for grades,
and will only ever be migrating backwards if you intend to go all the way back to zero and drop the tables.
If this is not the case and you are reading this comment, please file a PR to help us with your intended usage.
"""
pass
|
d7b7f157fd5758c1de22810d871642768f4eac68
|
trunk/metpy/__init__.py
|
trunk/metpy/__init__.py
|
import bl
import readers
import vis
import tools
import constants
from calc import *
import version
__version__ = version.get_version()
|
import bl
import readers
import vis
import tools
import constants
#What do we want to pull into the top-level namespace
from calc import *
from readers.mesonet import *
import version
__version__ = version.get_version()
|
Add mesonet readers to top level namespace.
|
Add mesonet readers to top level namespace.
git-svn-id: acf0ef94bfce630b1a882387fc03ab8593ec6522@150 150532fb-1d5b-0410-a8ab-efec50f980d4
|
Python
|
bsd-3-clause
|
dopplershift/MetPy,deeplycloudy/MetPy,dopplershift/MetPy,Unidata/MetPy,Unidata/MetPy,ahaberlie/MetPy,ahaberlie/MetPy,jrleeman/MetPy,jrleeman/MetPy,ShawnMurd/MetPy,ahill818/MetPy
|
import bl
import readers
import vis
import tools
import constants
from calc import *
import version
__version__ = version.get_version()
Add mesonet readers to top level namespace.
git-svn-id: acf0ef94bfce630b1a882387fc03ab8593ec6522@150 150532fb-1d5b-0410-a8ab-efec50f980d4
|
import bl
import readers
import vis
import tools
import constants
#What do we want to pull into the top-level namespace
from calc import *
from readers.mesonet import *
import version
__version__ = version.get_version()
|
<commit_before>import bl
import readers
import vis
import tools
import constants
from calc import *
import version
__version__ = version.get_version()
<commit_msg>Add mesonet readers to top level namespace.
git-svn-id: acf0ef94bfce630b1a882387fc03ab8593ec6522@150 150532fb-1d5b-0410-a8ab-efec50f980d4<commit_after>
|
import bl
import readers
import vis
import tools
import constants
#What do we want to pull into the top-level namespace
from calc import *
from readers.mesonet import *
import version
__version__ = version.get_version()
|
import bl
import readers
import vis
import tools
import constants
from calc import *
import version
__version__ = version.get_version()
Add mesonet readers to top level namespace.
git-svn-id: acf0ef94bfce630b1a882387fc03ab8593ec6522@150 150532fb-1d5b-0410-a8ab-efec50f980d4import bl
import readers
import vis
import tools
import constants
#What do we want to pull into the top-level namespace
from calc import *
from readers.mesonet import *
import version
__version__ = version.get_version()
|
<commit_before>import bl
import readers
import vis
import tools
import constants
from calc import *
import version
__version__ = version.get_version()
<commit_msg>Add mesonet readers to top level namespace.
git-svn-id: acf0ef94bfce630b1a882387fc03ab8593ec6522@150 150532fb-1d5b-0410-a8ab-efec50f980d4<commit_after>import bl
import readers
import vis
import tools
import constants
#What do we want to pull into the top-level namespace
from calc import *
from readers.mesonet import *
import version
__version__ = version.get_version()
|
20c121d218de2663186f2e5898aa643194902829
|
thumbor/detectors/queued_detector/__init__.py
|
thumbor/detectors/queued_detector/__init__.py
|
from remotecv import pyres_tasks
from remotecv.unique_queue import UniqueQueue
from thumbor.detectors import BaseDetector
class QueuedDetector(BaseDetector):
queue = UniqueQueue()
def detect(self, callback):
engine = self.context.modules.engine
self.queue.enqueue_unique(pyres_tasks.DetectTask,
args=[self.detection_type, self.context.request.image_url],
key=self.context.request.image_url)
self.context.prevent_result_storage = True
callback([])
|
from remotecv.unique_queue import UniqueQueue
from thumbor.detectors import BaseDetector
class QueuedDetector(BaseDetector):
queue = UniqueQueue()
def detect(self, callback):
engine = self.context.modules.engine
self.queue.enqueue_unique_from_string('remotecv.pyres_tasks.DetectTask', 'Detect',
args=[self.detection_type, self.context.request.image_url],
key=self.context.request.image_url)
self.context.prevent_result_storage = True
callback([])
|
Remove dependency from remotecv worker on queued detector
|
Remove dependency from remotecv worker on queued detector
|
Python
|
mit
|
Jimdo/thumbor,abaldwin1/thumbor,okor/thumbor,voxmedia/thumbor,wking/thumbor,gi11es/thumbor,figarocms/thumbor,jdunaravich/thumbor,thumbor/thumbor,grevutiu-gabriel/thumbor,suwaji/thumbor,marcelometal/thumbor,2947721120/thumbor,food52/thumbor,thumbor/thumbor,kkopachev/thumbor,dhardy92/thumbor,davduran/thumbor,scorphus/thumbor,adeboisanger/thumbor,wking/thumbor,dhardy92/thumbor,kkopachev/thumbor,davduran/thumbor,MaTriXy/thumbor,grevutiu-gabriel/thumbor,figarocms/thumbor,jdunaravich/thumbor,jiangzhonghui/thumbor,2947721120/thumbor,aaxx/thumbor,jiangzhonghui/thumbor,gi11es/thumbor,felipemorais/thumbor,MaTriXy/thumbor,gselva/thumbor,Bladrak/thumbor,lfalcao/thumbor,scorphus/thumbor,Bladrak/thumbor,BetterCollective/thumbor,MaTriXy/thumbor,fanhero/thumbor,camargoanderso/thumbor,suwaji/thumbor,kkopachev/thumbor,abaldwin1/thumbor,adeboisanger/thumbor,Jimdo/thumbor,thumbor/thumbor,aaxx/thumbor,marcelometal/thumbor,felipemorais/thumbor,figarocms/thumbor,food52/thumbor,jiangzhonghui/thumbor,okor/thumbor,lfalcao/thumbor,wking/thumbor,dhardy92/thumbor,BetterCollective/thumbor,camargoanderso/thumbor,raphaelfruneaux/thumbor,suwaji/thumbor,2947721120/thumbor,raphaelfruneaux/thumbor,lfalcao/thumbor,food52/thumbor,raphaelfruneaux/thumbor,camargoanderso/thumbor,gselva/thumbor,gi11es/thumbor,raphaelfruneaux/thumbor,adeboisanger/thumbor,grevutiu-gabriel/thumbor,voxmedia/thumbor,lfalcao/thumbor,marcelometal/thumbor,fanhero/thumbor,gselva/thumbor,felipemorais/thumbor,thumbor/thumbor,BetterCollective/thumbor,scorphus/thumbor,Jimdo/thumbor,fanhero/thumbor,2947721120/thumbor,gselva/thumbor,jdunaravich/thumbor,abaldwin1/thumbor,food52/thumbor,aaxx/thumbor,voxmedia/thumbor,jiangzhonghui/thumbor,suwaji/thumbor,scorphus/thumbor,fanhero/thumbor,wking/thumbor,felipemorais/thumbor,Jimdo/thumbor,camargoanderso/thumbor,kkopachev/thumbor,okor/thumbor,davduran/thumbor,davduran/thumbor,grevutiu-gabriel/thumbor,abaldwin1/thumbor,adeboisanger/thumbor,aaxx/thumbor,jdunaravich/thumbor,MaTriXy/thumbor,figarocms/thumbor
|
from remotecv import pyres_tasks
from remotecv.unique_queue import UniqueQueue
from thumbor.detectors import BaseDetector
class QueuedDetector(BaseDetector):
queue = UniqueQueue()
def detect(self, callback):
engine = self.context.modules.engine
self.queue.enqueue_unique(pyres_tasks.DetectTask,
args=[self.detection_type, self.context.request.image_url],
key=self.context.request.image_url)
self.context.prevent_result_storage = True
callback([])
Remove dependency from remotecv worker on queued detector
|
from remotecv.unique_queue import UniqueQueue
from thumbor.detectors import BaseDetector
class QueuedDetector(BaseDetector):
queue = UniqueQueue()
def detect(self, callback):
engine = self.context.modules.engine
self.queue.enqueue_unique_from_string('remotecv.pyres_tasks.DetectTask', 'Detect',
args=[self.detection_type, self.context.request.image_url],
key=self.context.request.image_url)
self.context.prevent_result_storage = True
callback([])
|
<commit_before>from remotecv import pyres_tasks
from remotecv.unique_queue import UniqueQueue
from thumbor.detectors import BaseDetector
class QueuedDetector(BaseDetector):
queue = UniqueQueue()
def detect(self, callback):
engine = self.context.modules.engine
self.queue.enqueue_unique(pyres_tasks.DetectTask,
args=[self.detection_type, self.context.request.image_url],
key=self.context.request.image_url)
self.context.prevent_result_storage = True
callback([])
<commit_msg>Remove dependency from remotecv worker on queued detector<commit_after>
|
from remotecv.unique_queue import UniqueQueue
from thumbor.detectors import BaseDetector
class QueuedDetector(BaseDetector):
queue = UniqueQueue()
def detect(self, callback):
engine = self.context.modules.engine
self.queue.enqueue_unique_from_string('remotecv.pyres_tasks.DetectTask', 'Detect',
args=[self.detection_type, self.context.request.image_url],
key=self.context.request.image_url)
self.context.prevent_result_storage = True
callback([])
|
from remotecv import pyres_tasks
from remotecv.unique_queue import UniqueQueue
from thumbor.detectors import BaseDetector
class QueuedDetector(BaseDetector):
queue = UniqueQueue()
def detect(self, callback):
engine = self.context.modules.engine
self.queue.enqueue_unique(pyres_tasks.DetectTask,
args=[self.detection_type, self.context.request.image_url],
key=self.context.request.image_url)
self.context.prevent_result_storage = True
callback([])
Remove dependency from remotecv worker on queued detectorfrom remotecv.unique_queue import UniqueQueue
from thumbor.detectors import BaseDetector
class QueuedDetector(BaseDetector):
queue = UniqueQueue()
def detect(self, callback):
engine = self.context.modules.engine
self.queue.enqueue_unique_from_string('remotecv.pyres_tasks.DetectTask', 'Detect',
args=[self.detection_type, self.context.request.image_url],
key=self.context.request.image_url)
self.context.prevent_result_storage = True
callback([])
|
<commit_before>from remotecv import pyres_tasks
from remotecv.unique_queue import UniqueQueue
from thumbor.detectors import BaseDetector
class QueuedDetector(BaseDetector):
queue = UniqueQueue()
def detect(self, callback):
engine = self.context.modules.engine
self.queue.enqueue_unique(pyres_tasks.DetectTask,
args=[self.detection_type, self.context.request.image_url],
key=self.context.request.image_url)
self.context.prevent_result_storage = True
callback([])
<commit_msg>Remove dependency from remotecv worker on queued detector<commit_after>from remotecv.unique_queue import UniqueQueue
from thumbor.detectors import BaseDetector
class QueuedDetector(BaseDetector):
queue = UniqueQueue()
def detect(self, callback):
engine = self.context.modules.engine
self.queue.enqueue_unique_from_string('remotecv.pyres_tasks.DetectTask', 'Detect',
args=[self.detection_type, self.context.request.image_url],
key=self.context.request.image_url)
self.context.prevent_result_storage = True
callback([])
|
f02ce3a2e94bc40cde87a39ba5b133599d729f9c
|
mpltools/widgets/__init__.py
|
mpltools/widgets/__init__.py
|
import matplotlib.widgets as mwidgets
if not hasattr(mwidgets, 'AxesWidget'):
branch = "<https://github.com/tonysyu/matplotlib/tree/base-widget>"
msg = "mpltools.widgets requires a branch of Matplotlib: %s" % branch
raise ImportError(msg)
from .rectangle_selector import RectangleSelector
from .slider import Slider
__all__ = ['RectangleSelector', 'Slider']
|
import matplotlib.widgets as mwidgets
if not hasattr(mwidgets, 'AxesWidget'):
version = "(github master; after March 16, 2012)"
msg = "mpltools.widgets requires recent version of Matplotlib %s" % version
raise ImportError(msg)
from .rectangle_selector import RectangleSelector
from .slider import Slider
__all__ = ['RectangleSelector', 'Slider']
|
Update MPL version requirement for `widgets`.
|
Update MPL version requirement for `widgets`.
|
Python
|
bsd-3-clause
|
tonysyu/mpltools,matteoicardi/mpltools
|
import matplotlib.widgets as mwidgets
if not hasattr(mwidgets, 'AxesWidget'):
branch = "<https://github.com/tonysyu/matplotlib/tree/base-widget>"
msg = "mpltools.widgets requires a branch of Matplotlib: %s" % branch
raise ImportError(msg)
from .rectangle_selector import RectangleSelector
from .slider import Slider
__all__ = ['RectangleSelector', 'Slider']
Update MPL version requirement for `widgets`.
|
import matplotlib.widgets as mwidgets
if not hasattr(mwidgets, 'AxesWidget'):
version = "(github master; after March 16, 2012)"
msg = "mpltools.widgets requires recent version of Matplotlib %s" % version
raise ImportError(msg)
from .rectangle_selector import RectangleSelector
from .slider import Slider
__all__ = ['RectangleSelector', 'Slider']
|
<commit_before>import matplotlib.widgets as mwidgets
if not hasattr(mwidgets, 'AxesWidget'):
branch = "<https://github.com/tonysyu/matplotlib/tree/base-widget>"
msg = "mpltools.widgets requires a branch of Matplotlib: %s" % branch
raise ImportError(msg)
from .rectangle_selector import RectangleSelector
from .slider import Slider
__all__ = ['RectangleSelector', 'Slider']
<commit_msg>Update MPL version requirement for `widgets`.<commit_after>
|
import matplotlib.widgets as mwidgets
if not hasattr(mwidgets, 'AxesWidget'):
version = "(github master; after March 16, 2012)"
msg = "mpltools.widgets requires recent version of Matplotlib %s" % version
raise ImportError(msg)
from .rectangle_selector import RectangleSelector
from .slider import Slider
__all__ = ['RectangleSelector', 'Slider']
|
import matplotlib.widgets as mwidgets
if not hasattr(mwidgets, 'AxesWidget'):
branch = "<https://github.com/tonysyu/matplotlib/tree/base-widget>"
msg = "mpltools.widgets requires a branch of Matplotlib: %s" % branch
raise ImportError(msg)
from .rectangle_selector import RectangleSelector
from .slider import Slider
__all__ = ['RectangleSelector', 'Slider']
Update MPL version requirement for `widgets`.import matplotlib.widgets as mwidgets
if not hasattr(mwidgets, 'AxesWidget'):
version = "(github master; after March 16, 2012)"
msg = "mpltools.widgets requires recent version of Matplotlib %s" % version
raise ImportError(msg)
from .rectangle_selector import RectangleSelector
from .slider import Slider
__all__ = ['RectangleSelector', 'Slider']
|
<commit_before>import matplotlib.widgets as mwidgets
if not hasattr(mwidgets, 'AxesWidget'):
branch = "<https://github.com/tonysyu/matplotlib/tree/base-widget>"
msg = "mpltools.widgets requires a branch of Matplotlib: %s" % branch
raise ImportError(msg)
from .rectangle_selector import RectangleSelector
from .slider import Slider
__all__ = ['RectangleSelector', 'Slider']
<commit_msg>Update MPL version requirement for `widgets`.<commit_after>import matplotlib.widgets as mwidgets
if not hasattr(mwidgets, 'AxesWidget'):
version = "(github master; after March 16, 2012)"
msg = "mpltools.widgets requires recent version of Matplotlib %s" % version
raise ImportError(msg)
from .rectangle_selector import RectangleSelector
from .slider import Slider
__all__ = ['RectangleSelector', 'Slider']
|
7ddb5b9ab579c58fc1fc8be7760f7f0963d02c3a
|
CodeFights/chessBoardCellColor.py
|
CodeFights/chessBoardCellColor.py
|
#!/usr/local/bin/python
# Code Fights Chess Board Cell Color Problem
def chessBoardCellColor(cell1, cell2):
pass
def main():
tests = [
["A1", "C3", True],
["A1", "H3", False],
["A1", "A2", False],
["A1", "B2", True],
["B3", "H8", False],
["C3", "B5", False],
["G5", "E7", True],
["C8", "H8", False],
["D2", "D2", True],
["A2", "A5", False]
]
for t in tests:
res = chessBoardCellColor(t[0], t[1])
if t[2] == res:
print("PASSED: chessBoardCellColor({}, {}) returned {}"
.format(t[0], t[1], res))
else:
print("FAILED: chessBoardCellColor({}, {}) returned {}, answer: {}"
.format(t[0], t[1], res, t[2]))
if __name__ == '__main__':
main()
|
#!/usr/local/bin/python
# Code Fights Chess Board Cell Color Problem
def chessBoardCellColor(cell1, cell2):
'''
Determine if the two given cells on chess board are same color
A, C, E, G odd cells are same color as B, D, F, H even cells
'''
def get_color(cell):
return ("DARK" if (cell[0] in "ACEG" and int(cell[1]) % 2 == 1) or
(cell[0] in "BDFH" and int(cell[1]) % 2 == 0) else "LIGHT")
return get_color(cell1) == get_color(cell2)
def main():
tests = [
["A1", "C3", True],
["A1", "H3", False],
["A1", "A2", False],
["A1", "B2", True],
["B3", "H8", False],
["C3", "B5", False],
["G5", "E7", True],
["C8", "H8", False],
["D2", "D2", True],
["A2", "A5", False]
]
for t in tests:
res = chessBoardCellColor(t[0], t[1])
if t[2] == res:
print("PASSED: chessBoardCellColor({}, {}) returned {}"
.format(t[0], t[1], res))
else:
print("FAILED: chessBoardCellColor({}, {}) returned {}, answer: {}"
.format(t[0], t[1], res, t[2]))
if __name__ == '__main__':
main()
|
Solve chess board cell color problem
|
Solve chess board cell color problem
|
Python
|
mit
|
HKuz/Test_Code
|
#!/usr/local/bin/python
# Code Fights Chess Board Cell Color Problem
def chessBoardCellColor(cell1, cell2):
pass
def main():
tests = [
["A1", "C3", True],
["A1", "H3", False],
["A1", "A2", False],
["A1", "B2", True],
["B3", "H8", False],
["C3", "B5", False],
["G5", "E7", True],
["C8", "H8", False],
["D2", "D2", True],
["A2", "A5", False]
]
for t in tests:
res = chessBoardCellColor(t[0], t[1])
if t[2] == res:
print("PASSED: chessBoardCellColor({}, {}) returned {}"
.format(t[0], t[1], res))
else:
print("FAILED: chessBoardCellColor({}, {}) returned {}, answer: {}"
.format(t[0], t[1], res, t[2]))
if __name__ == '__main__':
main()
Solve chess board cell color problem
|
#!/usr/local/bin/python
# Code Fights Chess Board Cell Color Problem
def chessBoardCellColor(cell1, cell2):
'''
Determine if the two given cells on chess board are same color
A, C, E, G odd cells are same color as B, D, F, H even cells
'''
def get_color(cell):
return ("DARK" if (cell[0] in "ACEG" and int(cell[1]) % 2 == 1) or
(cell[0] in "BDFH" and int(cell[1]) % 2 == 0) else "LIGHT")
return get_color(cell1) == get_color(cell2)
def main():
tests = [
["A1", "C3", True],
["A1", "H3", False],
["A1", "A2", False],
["A1", "B2", True],
["B3", "H8", False],
["C3", "B5", False],
["G5", "E7", True],
["C8", "H8", False],
["D2", "D2", True],
["A2", "A5", False]
]
for t in tests:
res = chessBoardCellColor(t[0], t[1])
if t[2] == res:
print("PASSED: chessBoardCellColor({}, {}) returned {}"
.format(t[0], t[1], res))
else:
print("FAILED: chessBoardCellColor({}, {}) returned {}, answer: {}"
.format(t[0], t[1], res, t[2]))
if __name__ == '__main__':
main()
|
<commit_before>#!/usr/local/bin/python
# Code Fights Chess Board Cell Color Problem
def chessBoardCellColor(cell1, cell2):
pass
def main():
tests = [
["A1", "C3", True],
["A1", "H3", False],
["A1", "A2", False],
["A1", "B2", True],
["B3", "H8", False],
["C3", "B5", False],
["G5", "E7", True],
["C8", "H8", False],
["D2", "D2", True],
["A2", "A5", False]
]
for t in tests:
res = chessBoardCellColor(t[0], t[1])
if t[2] == res:
print("PASSED: chessBoardCellColor({}, {}) returned {}"
.format(t[0], t[1], res))
else:
print("FAILED: chessBoardCellColor({}, {}) returned {}, answer: {}"
.format(t[0], t[1], res, t[2]))
if __name__ == '__main__':
main()
<commit_msg>Solve chess board cell color problem<commit_after>
|
#!/usr/local/bin/python
# Code Fights Chess Board Cell Color Problem
def chessBoardCellColor(cell1, cell2):
'''
Determine if the two given cells on chess board are same color
A, C, E, G odd cells are same color as B, D, F, H even cells
'''
def get_color(cell):
return ("DARK" if (cell[0] in "ACEG" and int(cell[1]) % 2 == 1) or
(cell[0] in "BDFH" and int(cell[1]) % 2 == 0) else "LIGHT")
return get_color(cell1) == get_color(cell2)
def main():
tests = [
["A1", "C3", True],
["A1", "H3", False],
["A1", "A2", False],
["A1", "B2", True],
["B3", "H8", False],
["C3", "B5", False],
["G5", "E7", True],
["C8", "H8", False],
["D2", "D2", True],
["A2", "A5", False]
]
for t in tests:
res = chessBoardCellColor(t[0], t[1])
if t[2] == res:
print("PASSED: chessBoardCellColor({}, {}) returned {}"
.format(t[0], t[1], res))
else:
print("FAILED: chessBoardCellColor({}, {}) returned {}, answer: {}"
.format(t[0], t[1], res, t[2]))
if __name__ == '__main__':
main()
|
#!/usr/local/bin/python
# Code Fights Chess Board Cell Color Problem
def chessBoardCellColor(cell1, cell2):
pass
def main():
tests = [
["A1", "C3", True],
["A1", "H3", False],
["A1", "A2", False],
["A1", "B2", True],
["B3", "H8", False],
["C3", "B5", False],
["G5", "E7", True],
["C8", "H8", False],
["D2", "D2", True],
["A2", "A5", False]
]
for t in tests:
res = chessBoardCellColor(t[0], t[1])
if t[2] == res:
print("PASSED: chessBoardCellColor({}, {}) returned {}"
.format(t[0], t[1], res))
else:
print("FAILED: chessBoardCellColor({}, {}) returned {}, answer: {}"
.format(t[0], t[1], res, t[2]))
if __name__ == '__main__':
main()
Solve chess board cell color problem#!/usr/local/bin/python
# Code Fights Chess Board Cell Color Problem
def chessBoardCellColor(cell1, cell2):
'''
Determine if the two given cells on chess board are same color
A, C, E, G odd cells are same color as B, D, F, H even cells
'''
def get_color(cell):
return ("DARK" if (cell[0] in "ACEG" and int(cell[1]) % 2 == 1) or
(cell[0] in "BDFH" and int(cell[1]) % 2 == 0) else "LIGHT")
return get_color(cell1) == get_color(cell2)
def main():
tests = [
["A1", "C3", True],
["A1", "H3", False],
["A1", "A2", False],
["A1", "B2", True],
["B3", "H8", False],
["C3", "B5", False],
["G5", "E7", True],
["C8", "H8", False],
["D2", "D2", True],
["A2", "A5", False]
]
for t in tests:
res = chessBoardCellColor(t[0], t[1])
if t[2] == res:
print("PASSED: chessBoardCellColor({}, {}) returned {}"
.format(t[0], t[1], res))
else:
print("FAILED: chessBoardCellColor({}, {}) returned {}, answer: {}"
.format(t[0], t[1], res, t[2]))
if __name__ == '__main__':
main()
|
<commit_before>#!/usr/local/bin/python
# Code Fights Chess Board Cell Color Problem
def chessBoardCellColor(cell1, cell2):
pass
def main():
tests = [
["A1", "C3", True],
["A1", "H3", False],
["A1", "A2", False],
["A1", "B2", True],
["B3", "H8", False],
["C3", "B5", False],
["G5", "E7", True],
["C8", "H8", False],
["D2", "D2", True],
["A2", "A5", False]
]
for t in tests:
res = chessBoardCellColor(t[0], t[1])
if t[2] == res:
print("PASSED: chessBoardCellColor({}, {}) returned {}"
.format(t[0], t[1], res))
else:
print("FAILED: chessBoardCellColor({}, {}) returned {}, answer: {}"
.format(t[0], t[1], res, t[2]))
if __name__ == '__main__':
main()
<commit_msg>Solve chess board cell color problem<commit_after>#!/usr/local/bin/python
# Code Fights Chess Board Cell Color Problem
def chessBoardCellColor(cell1, cell2):
'''
Determine if the two given cells on chess board are same color
A, C, E, G odd cells are same color as B, D, F, H even cells
'''
def get_color(cell):
return ("DARK" if (cell[0] in "ACEG" and int(cell[1]) % 2 == 1) or
(cell[0] in "BDFH" and int(cell[1]) % 2 == 0) else "LIGHT")
return get_color(cell1) == get_color(cell2)
def main():
tests = [
["A1", "C3", True],
["A1", "H3", False],
["A1", "A2", False],
["A1", "B2", True],
["B3", "H8", False],
["C3", "B5", False],
["G5", "E7", True],
["C8", "H8", False],
["D2", "D2", True],
["A2", "A5", False]
]
for t in tests:
res = chessBoardCellColor(t[0], t[1])
if t[2] == res:
print("PASSED: chessBoardCellColor({}, {}) returned {}"
.format(t[0], t[1], res))
else:
print("FAILED: chessBoardCellColor({}, {}) returned {}, answer: {}"
.format(t[0], t[1], res, t[2]))
if __name__ == '__main__':
main()
|
f4c5bb0a77108f340533736c52f01c861146a6b6
|
byceps/util/money.py
|
byceps/util/money.py
|
"""
byceps.util.money
~~~~~~~~~~~~~~~~~
Handle monetary amounts.
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from decimal import Decimal
import locale
TWO_PLACES = Decimal('.00')
def format_euro_amount(x: Decimal) -> str:
"""Return a textual representation with two decimal places,
locale-specific decimal point and thousands separators, and the Euro
symbol.
"""
quantized = to_two_places(x)
formatted_number = locale.format_string('%.2f', quantized, grouping=True,
monetary=True)
return f'{formatted_number} €'
def to_two_places(x: Decimal) -> Decimal:
"""Quantize to two decimal places."""
return x.quantize(TWO_PLACES)
|
"""
byceps.util.money
~~~~~~~~~~~~~~~~~
Handle monetary amounts.
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from decimal import Decimal
import locale
TWO_PLACES = Decimal('.00')
def format_euro_amount(x: Decimal) -> str:
"""Return a textual representation with two decimal places,
locale-specific decimal point and thousands separators, and the Euro
symbol.
"""
quantized = to_two_places(x)
formatted_number = locale.format_string('%.2f', quantized, grouping=True)
return f'{formatted_number} €'
def to_two_places(x: Decimal) -> Decimal:
"""Quantize to two decimal places."""
return x.quantize(TWO_PLACES)
|
Remove usage of `monetary` keyword argument again as it is not available on Python 3.6
|
Remove usage of `monetary` keyword argument again as it is not available on Python 3.6
|
Python
|
bsd-3-clause
|
m-ober/byceps,homeworkprod/byceps,m-ober/byceps,homeworkprod/byceps,homeworkprod/byceps,m-ober/byceps
|
"""
byceps.util.money
~~~~~~~~~~~~~~~~~
Handle monetary amounts.
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from decimal import Decimal
import locale
TWO_PLACES = Decimal('.00')
def format_euro_amount(x: Decimal) -> str:
"""Return a textual representation with two decimal places,
locale-specific decimal point and thousands separators, and the Euro
symbol.
"""
quantized = to_two_places(x)
formatted_number = locale.format_string('%.2f', quantized, grouping=True,
monetary=True)
return f'{formatted_number} €'
def to_two_places(x: Decimal) -> Decimal:
"""Quantize to two decimal places."""
return x.quantize(TWO_PLACES)
Remove usage of `monetary` keyword argument again as it is not available on Python 3.6
|
"""
byceps.util.money
~~~~~~~~~~~~~~~~~
Handle monetary amounts.
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from decimal import Decimal
import locale
TWO_PLACES = Decimal('.00')
def format_euro_amount(x: Decimal) -> str:
"""Return a textual representation with two decimal places,
locale-specific decimal point and thousands separators, and the Euro
symbol.
"""
quantized = to_two_places(x)
formatted_number = locale.format_string('%.2f', quantized, grouping=True)
return f'{formatted_number} €'
def to_two_places(x: Decimal) -> Decimal:
"""Quantize to two decimal places."""
return x.quantize(TWO_PLACES)
|
<commit_before>"""
byceps.util.money
~~~~~~~~~~~~~~~~~
Handle monetary amounts.
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from decimal import Decimal
import locale
TWO_PLACES = Decimal('.00')
def format_euro_amount(x: Decimal) -> str:
"""Return a textual representation with two decimal places,
locale-specific decimal point and thousands separators, and the Euro
symbol.
"""
quantized = to_two_places(x)
formatted_number = locale.format_string('%.2f', quantized, grouping=True,
monetary=True)
return f'{formatted_number} €'
def to_two_places(x: Decimal) -> Decimal:
"""Quantize to two decimal places."""
return x.quantize(TWO_PLACES)
<commit_msg>Remove usage of `monetary` keyword argument again as it is not available on Python 3.6<commit_after>
|
"""
byceps.util.money
~~~~~~~~~~~~~~~~~
Handle monetary amounts.
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from decimal import Decimal
import locale
TWO_PLACES = Decimal('.00')
def format_euro_amount(x: Decimal) -> str:
"""Return a textual representation with two decimal places,
locale-specific decimal point and thousands separators, and the Euro
symbol.
"""
quantized = to_two_places(x)
formatted_number = locale.format_string('%.2f', quantized, grouping=True)
return f'{formatted_number} €'
def to_two_places(x: Decimal) -> Decimal:
"""Quantize to two decimal places."""
return x.quantize(TWO_PLACES)
|
"""
byceps.util.money
~~~~~~~~~~~~~~~~~
Handle monetary amounts.
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from decimal import Decimal
import locale
TWO_PLACES = Decimal('.00')
def format_euro_amount(x: Decimal) -> str:
"""Return a textual representation with two decimal places,
locale-specific decimal point and thousands separators, and the Euro
symbol.
"""
quantized = to_two_places(x)
formatted_number = locale.format_string('%.2f', quantized, grouping=True,
monetary=True)
return f'{formatted_number} €'
def to_two_places(x: Decimal) -> Decimal:
"""Quantize to two decimal places."""
return x.quantize(TWO_PLACES)
Remove usage of `monetary` keyword argument again as it is not available on Python 3.6"""
byceps.util.money
~~~~~~~~~~~~~~~~~
Handle monetary amounts.
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from decimal import Decimal
import locale
TWO_PLACES = Decimal('.00')
def format_euro_amount(x: Decimal) -> str:
"""Return a textual representation with two decimal places,
locale-specific decimal point and thousands separators, and the Euro
symbol.
"""
quantized = to_two_places(x)
formatted_number = locale.format_string('%.2f', quantized, grouping=True)
return f'{formatted_number} €'
def to_two_places(x: Decimal) -> Decimal:
"""Quantize to two decimal places."""
return x.quantize(TWO_PLACES)
|
<commit_before>"""
byceps.util.money
~~~~~~~~~~~~~~~~~
Handle monetary amounts.
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from decimal import Decimal
import locale
TWO_PLACES = Decimal('.00')
def format_euro_amount(x: Decimal) -> str:
"""Return a textual representation with two decimal places,
locale-specific decimal point and thousands separators, and the Euro
symbol.
"""
quantized = to_two_places(x)
formatted_number = locale.format_string('%.2f', quantized, grouping=True,
monetary=True)
return f'{formatted_number} €'
def to_two_places(x: Decimal) -> Decimal:
"""Quantize to two decimal places."""
return x.quantize(TWO_PLACES)
<commit_msg>Remove usage of `monetary` keyword argument again as it is not available on Python 3.6<commit_after>"""
byceps.util.money
~~~~~~~~~~~~~~~~~
Handle monetary amounts.
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from decimal import Decimal
import locale
TWO_PLACES = Decimal('.00')
def format_euro_amount(x: Decimal) -> str:
"""Return a textual representation with two decimal places,
locale-specific decimal point and thousands separators, and the Euro
symbol.
"""
quantized = to_two_places(x)
formatted_number = locale.format_string('%.2f', quantized, grouping=True)
return f'{formatted_number} €'
def to_two_places(x: Decimal) -> Decimal:
"""Quantize to two decimal places."""
return x.quantize(TWO_PLACES)
|
58236d8bc6a23477d83c244fc117f493aa2651a6
|
thinglang/parser/tokens/arithmetic.py
|
thinglang/parser/tokens/arithmetic.py
|
from thinglang.common import ObtainableValue
from thinglang.parser.tokens import BaseToken
class ArithmeticOperation(BaseToken, ObtainableValue):
OPERATIONS = {
"+": lambda rhs, lhs: rhs + lhs,
"*": lambda rhs, lhs: rhs * lhs,
"-": lambda rhs, lhs: rhs - lhs,
"/": lambda rhs, lhs: rhs / lhs
}
def __init__(self, slice):
super(ArithmeticOperation, self).__init__(slice)
self.lhs, self.operator, self.rhs = slice
def evaluate(self, stack):
return self.OPERATIONS[self.operator.operator](self.lhs.evaluate(stack), self.rhs.evaluate(stack))
def describe(self):
return '{} {} {}'.format(self.lhs, self.operator, self.rhs)
|
from thinglang.common import ObtainableValue
from thinglang.parser.tokens import BaseToken
class ArithmeticOperation(BaseToken, ObtainableValue):
OPERATIONS = {
"+": lambda rhs, lhs: rhs + lhs,
"*": lambda rhs, lhs: rhs * lhs,
"-": lambda rhs, lhs: rhs - lhs,
"/": lambda rhs, lhs: rhs / lhs
}
def __init__(self, slice):
super(ArithmeticOperation, self).__init__(slice)
self.lhs, self.operator, self.rhs = slice
def evaluate(self, stack):
return self.OPERATIONS[self.operator.operator](self.lhs.evaluate(stack), self.rhs.evaluate(stack))
def describe(self):
return '|{} {} {}|'.format(self[0], self.operator, self[1])
def replace_argument(self, original, replacement):
self.arguments = [replacement if x is original else x for x in self.arguments]
def __getitem__(self, item):
return self.arguments[item]
|
Add replace method to Arithmetic operation
|
Add replace method to Arithmetic operation
|
Python
|
mit
|
ytanay/thinglang,ytanay/thinglang,ytanay/thinglang,ytanay/thinglang
|
from thinglang.common import ObtainableValue
from thinglang.parser.tokens import BaseToken
class ArithmeticOperation(BaseToken, ObtainableValue):
OPERATIONS = {
"+": lambda rhs, lhs: rhs + lhs,
"*": lambda rhs, lhs: rhs * lhs,
"-": lambda rhs, lhs: rhs - lhs,
"/": lambda rhs, lhs: rhs / lhs
}
def __init__(self, slice):
super(ArithmeticOperation, self).__init__(slice)
self.lhs, self.operator, self.rhs = slice
def evaluate(self, stack):
return self.OPERATIONS[self.operator.operator](self.lhs.evaluate(stack), self.rhs.evaluate(stack))
def describe(self):
return '{} {} {}'.format(self.lhs, self.operator, self.rhs)Add replace method to Arithmetic operation
|
from thinglang.common import ObtainableValue
from thinglang.parser.tokens import BaseToken
class ArithmeticOperation(BaseToken, ObtainableValue):
OPERATIONS = {
"+": lambda rhs, lhs: rhs + lhs,
"*": lambda rhs, lhs: rhs * lhs,
"-": lambda rhs, lhs: rhs - lhs,
"/": lambda rhs, lhs: rhs / lhs
}
def __init__(self, slice):
super(ArithmeticOperation, self).__init__(slice)
self.lhs, self.operator, self.rhs = slice
def evaluate(self, stack):
return self.OPERATIONS[self.operator.operator](self.lhs.evaluate(stack), self.rhs.evaluate(stack))
def describe(self):
return '|{} {} {}|'.format(self[0], self.operator, self[1])
def replace_argument(self, original, replacement):
self.arguments = [replacement if x is original else x for x in self.arguments]
def __getitem__(self, item):
return self.arguments[item]
|
<commit_before>from thinglang.common import ObtainableValue
from thinglang.parser.tokens import BaseToken
class ArithmeticOperation(BaseToken, ObtainableValue):
OPERATIONS = {
"+": lambda rhs, lhs: rhs + lhs,
"*": lambda rhs, lhs: rhs * lhs,
"-": lambda rhs, lhs: rhs - lhs,
"/": lambda rhs, lhs: rhs / lhs
}
def __init__(self, slice):
super(ArithmeticOperation, self).__init__(slice)
self.lhs, self.operator, self.rhs = slice
def evaluate(self, stack):
return self.OPERATIONS[self.operator.operator](self.lhs.evaluate(stack), self.rhs.evaluate(stack))
def describe(self):
return '{} {} {}'.format(self.lhs, self.operator, self.rhs)<commit_msg>Add replace method to Arithmetic operation<commit_after>
|
from thinglang.common import ObtainableValue
from thinglang.parser.tokens import BaseToken
class ArithmeticOperation(BaseToken, ObtainableValue):
OPERATIONS = {
"+": lambda rhs, lhs: rhs + lhs,
"*": lambda rhs, lhs: rhs * lhs,
"-": lambda rhs, lhs: rhs - lhs,
"/": lambda rhs, lhs: rhs / lhs
}
def __init__(self, slice):
super(ArithmeticOperation, self).__init__(slice)
self.lhs, self.operator, self.rhs = slice
def evaluate(self, stack):
return self.OPERATIONS[self.operator.operator](self.lhs.evaluate(stack), self.rhs.evaluate(stack))
def describe(self):
return '|{} {} {}|'.format(self[0], self.operator, self[1])
def replace_argument(self, original, replacement):
self.arguments = [replacement if x is original else x for x in self.arguments]
def __getitem__(self, item):
return self.arguments[item]
|
from thinglang.common import ObtainableValue
from thinglang.parser.tokens import BaseToken
class ArithmeticOperation(BaseToken, ObtainableValue):
OPERATIONS = {
"+": lambda rhs, lhs: rhs + lhs,
"*": lambda rhs, lhs: rhs * lhs,
"-": lambda rhs, lhs: rhs - lhs,
"/": lambda rhs, lhs: rhs / lhs
}
def __init__(self, slice):
super(ArithmeticOperation, self).__init__(slice)
self.lhs, self.operator, self.rhs = slice
def evaluate(self, stack):
return self.OPERATIONS[self.operator.operator](self.lhs.evaluate(stack), self.rhs.evaluate(stack))
def describe(self):
return '{} {} {}'.format(self.lhs, self.operator, self.rhs)Add replace method to Arithmetic operationfrom thinglang.common import ObtainableValue
from thinglang.parser.tokens import BaseToken
class ArithmeticOperation(BaseToken, ObtainableValue):
OPERATIONS = {
"+": lambda rhs, lhs: rhs + lhs,
"*": lambda rhs, lhs: rhs * lhs,
"-": lambda rhs, lhs: rhs - lhs,
"/": lambda rhs, lhs: rhs / lhs
}
def __init__(self, slice):
super(ArithmeticOperation, self).__init__(slice)
self.lhs, self.operator, self.rhs = slice
def evaluate(self, stack):
return self.OPERATIONS[self.operator.operator](self.lhs.evaluate(stack), self.rhs.evaluate(stack))
def describe(self):
return '|{} {} {}|'.format(self[0], self.operator, self[1])
def replace_argument(self, original, replacement):
self.arguments = [replacement if x is original else x for x in self.arguments]
def __getitem__(self, item):
return self.arguments[item]
|
<commit_before>from thinglang.common import ObtainableValue
from thinglang.parser.tokens import BaseToken
class ArithmeticOperation(BaseToken, ObtainableValue):
OPERATIONS = {
"+": lambda rhs, lhs: rhs + lhs,
"*": lambda rhs, lhs: rhs * lhs,
"-": lambda rhs, lhs: rhs - lhs,
"/": lambda rhs, lhs: rhs / lhs
}
def __init__(self, slice):
super(ArithmeticOperation, self).__init__(slice)
self.lhs, self.operator, self.rhs = slice
def evaluate(self, stack):
return self.OPERATIONS[self.operator.operator](self.lhs.evaluate(stack), self.rhs.evaluate(stack))
def describe(self):
return '{} {} {}'.format(self.lhs, self.operator, self.rhs)<commit_msg>Add replace method to Arithmetic operation<commit_after>from thinglang.common import ObtainableValue
from thinglang.parser.tokens import BaseToken
class ArithmeticOperation(BaseToken, ObtainableValue):
OPERATIONS = {
"+": lambda rhs, lhs: rhs + lhs,
"*": lambda rhs, lhs: rhs * lhs,
"-": lambda rhs, lhs: rhs - lhs,
"/": lambda rhs, lhs: rhs / lhs
}
def __init__(self, slice):
super(ArithmeticOperation, self).__init__(slice)
self.lhs, self.operator, self.rhs = slice
def evaluate(self, stack):
return self.OPERATIONS[self.operator.operator](self.lhs.evaluate(stack), self.rhs.evaluate(stack))
def describe(self):
return '|{} {} {}|'.format(self[0], self.operator, self[1])
def replace_argument(self, original, replacement):
self.arguments = [replacement if x is original else x for x in self.arguments]
def __getitem__(self, item):
return self.arguments[item]
|
bfafb5c3fd2de6f2a87439553b3a55465f07d24c
|
django_medusa/renderers/__init__.py
|
django_medusa/renderers/__init__.py
|
from django.conf import settings
import importlib
from .base import BaseStaticSiteRenderer
from .disk import DiskStaticSiteRenderer
from .appengine import GAEStaticSiteRenderer
from .s3 import S3StaticSiteRenderer
__all__ = ('BaseStaticSiteRenderer', 'DiskStaticSiteRenderer',
'S3StaticSiteRenderer', 'GAEStaticSiteRenderer',
'StaticSiteRenderer')
def get_cls(renderer_name):
mod_path, cls_name = renderer_name.rsplit('.', 1)
mod = importlib.import_module(mod_path)
return getattr(mod, cls_name)
DEFAULT_RENDERER = 'medusa.renderers.BaseStaticSiteRenderer'
# Define the default "django_medusa.renderers.StaticSiteRenderer" class as
# whatever class we have chosen in settings (defaulting to Base which will
# throw NotImplementedErrors when attempting to render).
StaticSiteRenderer = get_cls(getattr(settings,
'MEDUSA_RENDERER_CLASS', DEFAULT_RENDERER
))
|
from django.conf import settings
from django.utils import importlib
from .base import BaseStaticSiteRenderer
from .disk import DiskStaticSiteRenderer
from .appengine import GAEStaticSiteRenderer
from .s3 import S3StaticSiteRenderer
__all__ = ('BaseStaticSiteRenderer', 'DiskStaticSiteRenderer',
'S3StaticSiteRenderer', 'GAEStaticSiteRenderer',
'StaticSiteRenderer')
def get_cls(renderer_name):
mod_path, cls_name = renderer_name.rsplit('.', 1)
mod = importlib.import_module(mod_path)
return getattr(mod, cls_name)
DEFAULT_RENDERER = 'medusa.renderers.BaseStaticSiteRenderer'
# Define the default "django_medusa.renderers.StaticSiteRenderer" class as
# whatever class we have chosen in settings (defaulting to Base which will
# throw NotImplementedErrors when attempting to render).
StaticSiteRenderer = get_cls(getattr(settings,
'MEDUSA_RENDERER_CLASS', DEFAULT_RENDERER
))
|
Remove importlib dependency, add django's own importlib
|
Remove importlib dependency, add django's own importlib
|
Python
|
mit
|
alsoicode/django-medusa,mtigas/django-medusa,hyperair/django-medusa,botify-labs/django-medusa
|
from django.conf import settings
import importlib
from .base import BaseStaticSiteRenderer
from .disk import DiskStaticSiteRenderer
from .appengine import GAEStaticSiteRenderer
from .s3 import S3StaticSiteRenderer
__all__ = ('BaseStaticSiteRenderer', 'DiskStaticSiteRenderer',
'S3StaticSiteRenderer', 'GAEStaticSiteRenderer',
'StaticSiteRenderer')
def get_cls(renderer_name):
mod_path, cls_name = renderer_name.rsplit('.', 1)
mod = importlib.import_module(mod_path)
return getattr(mod, cls_name)
DEFAULT_RENDERER = 'medusa.renderers.BaseStaticSiteRenderer'
# Define the default "django_medusa.renderers.StaticSiteRenderer" class as
# whatever class we have chosen in settings (defaulting to Base which will
# throw NotImplementedErrors when attempting to render).
StaticSiteRenderer = get_cls(getattr(settings,
'MEDUSA_RENDERER_CLASS', DEFAULT_RENDERER
))
Remove importlib dependency, add django's own importlib
|
from django.conf import settings
from django.utils import importlib
from .base import BaseStaticSiteRenderer
from .disk import DiskStaticSiteRenderer
from .appengine import GAEStaticSiteRenderer
from .s3 import S3StaticSiteRenderer
__all__ = ('BaseStaticSiteRenderer', 'DiskStaticSiteRenderer',
'S3StaticSiteRenderer', 'GAEStaticSiteRenderer',
'StaticSiteRenderer')
def get_cls(renderer_name):
mod_path, cls_name = renderer_name.rsplit('.', 1)
mod = importlib.import_module(mod_path)
return getattr(mod, cls_name)
DEFAULT_RENDERER = 'medusa.renderers.BaseStaticSiteRenderer'
# Define the default "django_medusa.renderers.StaticSiteRenderer" class as
# whatever class we have chosen in settings (defaulting to Base which will
# throw NotImplementedErrors when attempting to render).
StaticSiteRenderer = get_cls(getattr(settings,
'MEDUSA_RENDERER_CLASS', DEFAULT_RENDERER
))
|
<commit_before>from django.conf import settings
import importlib
from .base import BaseStaticSiteRenderer
from .disk import DiskStaticSiteRenderer
from .appengine import GAEStaticSiteRenderer
from .s3 import S3StaticSiteRenderer
__all__ = ('BaseStaticSiteRenderer', 'DiskStaticSiteRenderer',
'S3StaticSiteRenderer', 'GAEStaticSiteRenderer',
'StaticSiteRenderer')
def get_cls(renderer_name):
mod_path, cls_name = renderer_name.rsplit('.', 1)
mod = importlib.import_module(mod_path)
return getattr(mod, cls_name)
DEFAULT_RENDERER = 'medusa.renderers.BaseStaticSiteRenderer'
# Define the default "django_medusa.renderers.StaticSiteRenderer" class as
# whatever class we have chosen in settings (defaulting to Base which will
# throw NotImplementedErrors when attempting to render).
StaticSiteRenderer = get_cls(getattr(settings,
'MEDUSA_RENDERER_CLASS', DEFAULT_RENDERER
))
<commit_msg>Remove importlib dependency, add django's own importlib<commit_after>
|
from django.conf import settings
from django.utils import importlib
from .base import BaseStaticSiteRenderer
from .disk import DiskStaticSiteRenderer
from .appengine import GAEStaticSiteRenderer
from .s3 import S3StaticSiteRenderer
__all__ = ('BaseStaticSiteRenderer', 'DiskStaticSiteRenderer',
'S3StaticSiteRenderer', 'GAEStaticSiteRenderer',
'StaticSiteRenderer')
def get_cls(renderer_name):
mod_path, cls_name = renderer_name.rsplit('.', 1)
mod = importlib.import_module(mod_path)
return getattr(mod, cls_name)
DEFAULT_RENDERER = 'medusa.renderers.BaseStaticSiteRenderer'
# Define the default "django_medusa.renderers.StaticSiteRenderer" class as
# whatever class we have chosen in settings (defaulting to Base which will
# throw NotImplementedErrors when attempting to render).
StaticSiteRenderer = get_cls(getattr(settings,
'MEDUSA_RENDERER_CLASS', DEFAULT_RENDERER
))
|
from django.conf import settings
import importlib
from .base import BaseStaticSiteRenderer
from .disk import DiskStaticSiteRenderer
from .appengine import GAEStaticSiteRenderer
from .s3 import S3StaticSiteRenderer
__all__ = ('BaseStaticSiteRenderer', 'DiskStaticSiteRenderer',
'S3StaticSiteRenderer', 'GAEStaticSiteRenderer',
'StaticSiteRenderer')
def get_cls(renderer_name):
mod_path, cls_name = renderer_name.rsplit('.', 1)
mod = importlib.import_module(mod_path)
return getattr(mod, cls_name)
DEFAULT_RENDERER = 'medusa.renderers.BaseStaticSiteRenderer'
# Define the default "django_medusa.renderers.StaticSiteRenderer" class as
# whatever class we have chosen in settings (defaulting to Base which will
# throw NotImplementedErrors when attempting to render).
StaticSiteRenderer = get_cls(getattr(settings,
'MEDUSA_RENDERER_CLASS', DEFAULT_RENDERER
))
Remove importlib dependency, add django's own importlibfrom django.conf import settings
from django.utils import importlib
from .base import BaseStaticSiteRenderer
from .disk import DiskStaticSiteRenderer
from .appengine import GAEStaticSiteRenderer
from .s3 import S3StaticSiteRenderer
__all__ = ('BaseStaticSiteRenderer', 'DiskStaticSiteRenderer',
'S3StaticSiteRenderer', 'GAEStaticSiteRenderer',
'StaticSiteRenderer')
def get_cls(renderer_name):
mod_path, cls_name = renderer_name.rsplit('.', 1)
mod = importlib.import_module(mod_path)
return getattr(mod, cls_name)
DEFAULT_RENDERER = 'medusa.renderers.BaseStaticSiteRenderer'
# Define the default "django_medusa.renderers.StaticSiteRenderer" class as
# whatever class we have chosen in settings (defaulting to Base which will
# throw NotImplementedErrors when attempting to render).
StaticSiteRenderer = get_cls(getattr(settings,
'MEDUSA_RENDERER_CLASS', DEFAULT_RENDERER
))
|
<commit_before>from django.conf import settings
import importlib
from .base import BaseStaticSiteRenderer
from .disk import DiskStaticSiteRenderer
from .appengine import GAEStaticSiteRenderer
from .s3 import S3StaticSiteRenderer
__all__ = ('BaseStaticSiteRenderer', 'DiskStaticSiteRenderer',
'S3StaticSiteRenderer', 'GAEStaticSiteRenderer',
'StaticSiteRenderer')
def get_cls(renderer_name):
mod_path, cls_name = renderer_name.rsplit('.', 1)
mod = importlib.import_module(mod_path)
return getattr(mod, cls_name)
DEFAULT_RENDERER = 'medusa.renderers.BaseStaticSiteRenderer'
# Define the default "django_medusa.renderers.StaticSiteRenderer" class as
# whatever class we have chosen in settings (defaulting to Base which will
# throw NotImplementedErrors when attempting to render).
StaticSiteRenderer = get_cls(getattr(settings,
'MEDUSA_RENDERER_CLASS', DEFAULT_RENDERER
))
<commit_msg>Remove importlib dependency, add django's own importlib<commit_after>from django.conf import settings
from django.utils import importlib
from .base import BaseStaticSiteRenderer
from .disk import DiskStaticSiteRenderer
from .appengine import GAEStaticSiteRenderer
from .s3 import S3StaticSiteRenderer
__all__ = ('BaseStaticSiteRenderer', 'DiskStaticSiteRenderer',
'S3StaticSiteRenderer', 'GAEStaticSiteRenderer',
'StaticSiteRenderer')
def get_cls(renderer_name):
mod_path, cls_name = renderer_name.rsplit('.', 1)
mod = importlib.import_module(mod_path)
return getattr(mod, cls_name)
DEFAULT_RENDERER = 'medusa.renderers.BaseStaticSiteRenderer'
# Define the default "django_medusa.renderers.StaticSiteRenderer" class as
# whatever class we have chosen in settings (defaulting to Base which will
# throw NotImplementedErrors when attempting to render).
StaticSiteRenderer = get_cls(getattr(settings,
'MEDUSA_RENDERER_CLASS', DEFAULT_RENDERER
))
|
c734fbbcb8680f704cfcc5b8ee605c4d0557526d
|
Brownian/view/utils/plugins.py
|
Brownian/view/utils/plugins.py
|
import subprocess
import string
class Plugin:
def __init__(self, command, allowedChars):
# We replace the characters we do allow with empty strings, to get a string of all the characters we don't allow.
self.notAllowedCharMap = string.maketrans(allowedChars, " "*len(allowedChars))
self.command = command
def run(self, values):
sanitizedValues = []
for value in values:
sanitizedValues.append(str(value).translate(None, self.notAllowedCharMap))
result = subprocess.Popen([self.command] + sanitizedValues, stdout=subprocess.PIPE)
stdout, stderr = result.communicate()
return stdout.replace("\n", "<br>")
whois = {"displayName": "Whois Lookup",
"plugin": Plugin("whois", string.letters + string.digits + ".:-_")}
dns_lookup = {"displayName": "DNS Lookup",
"plugin": Plugin("host", string.letters + string.digits + ".:-_")}
mapping = {"addr": [whois, dns_lookup],
"string": [dns_lookup]}
|
import subprocess
import string
import shlex
class Plugin:
def __init__(self, command, allowedChars, insertInitialNewline=False):
# We replace the characters we do allow with empty strings, to get a string of all the characters we don't allow.
self.notAllowedCharMap = str(string.maketrans(allowedChars, " "*len(allowedChars)))
self.command = shlex.split(command)
self.insertInitialNewline = insertInitialNewline
def run(self, values):
sanitizedValues = []
for value in values:
sanitizedValues.append(str(value).translate(None, self.notAllowedCharMap))
result = subprocess.Popen(self.command + sanitizedValues, stdout=subprocess.PIPE)
stdout, stderr = result.communicate()
if self.insertInitialNewline:
stdout = "\n" + stdout
return stdout.replace("\n", "<br>")
whois = {"displayName": "Whois Lookup",
"plugin": Plugin("whois -h whois.cymru.com \" -p -u\"", string.letters + string.digits + ".:-_", insertInitialNewline=True)}
dns_lookup = {"displayName": "DNS Lookup",
"plugin": Plugin("host", string.letters + string.digits + ".:-_")}
mapping = {"addr": [whois, dns_lookup],
"string": [dns_lookup]}
|
Use the Team Cymru whois server by default, make it easier to use complex commands, and optionally insert a new line before the output.
|
Use the Team Cymru whois server by default, make it easier to use complex commands, and optionally insert a new line before the output.
|
Python
|
bsd-2-clause
|
jpressnell/Brownian,grigorescu/Brownian,ruslux/Brownian,grigorescu/Brownian,grigorescu/Brownian,jpressnell/Brownian,jpressnell/Brownian,ruslux/Brownian,ruslux/Brownian
|
import subprocess
import string
class Plugin:
def __init__(self, command, allowedChars):
# We replace the characters we do allow with empty strings, to get a string of all the characters we don't allow.
self.notAllowedCharMap = string.maketrans(allowedChars, " "*len(allowedChars))
self.command = command
def run(self, values):
sanitizedValues = []
for value in values:
sanitizedValues.append(str(value).translate(None, self.notAllowedCharMap))
result = subprocess.Popen([self.command] + sanitizedValues, stdout=subprocess.PIPE)
stdout, stderr = result.communicate()
return stdout.replace("\n", "<br>")
whois = {"displayName": "Whois Lookup",
"plugin": Plugin("whois", string.letters + string.digits + ".:-_")}
dns_lookup = {"displayName": "DNS Lookup",
"plugin": Plugin("host", string.letters + string.digits + ".:-_")}
mapping = {"addr": [whois, dns_lookup],
"string": [dns_lookup]}Use the Team Cymru whois server by default, make it easier to use complex commands, and optionally insert a new line before the output.
|
import subprocess
import string
import shlex
class Plugin:
def __init__(self, command, allowedChars, insertInitialNewline=False):
# We replace the characters we do allow with empty strings, to get a string of all the characters we don't allow.
self.notAllowedCharMap = str(string.maketrans(allowedChars, " "*len(allowedChars)))
self.command = shlex.split(command)
self.insertInitialNewline = insertInitialNewline
def run(self, values):
sanitizedValues = []
for value in values:
sanitizedValues.append(str(value).translate(None, self.notAllowedCharMap))
result = subprocess.Popen(self.command + sanitizedValues, stdout=subprocess.PIPE)
stdout, stderr = result.communicate()
if self.insertInitialNewline:
stdout = "\n" + stdout
return stdout.replace("\n", "<br>")
whois = {"displayName": "Whois Lookup",
"plugin": Plugin("whois -h whois.cymru.com \" -p -u\"", string.letters + string.digits + ".:-_", insertInitialNewline=True)}
dns_lookup = {"displayName": "DNS Lookup",
"plugin": Plugin("host", string.letters + string.digits + ".:-_")}
mapping = {"addr": [whois, dns_lookup],
"string": [dns_lookup]}
|
<commit_before>import subprocess
import string
class Plugin:
def __init__(self, command, allowedChars):
# We replace the characters we do allow with empty strings, to get a string of all the characters we don't allow.
self.notAllowedCharMap = string.maketrans(allowedChars, " "*len(allowedChars))
self.command = command
def run(self, values):
sanitizedValues = []
for value in values:
sanitizedValues.append(str(value).translate(None, self.notAllowedCharMap))
result = subprocess.Popen([self.command] + sanitizedValues, stdout=subprocess.PIPE)
stdout, stderr = result.communicate()
return stdout.replace("\n", "<br>")
whois = {"displayName": "Whois Lookup",
"plugin": Plugin("whois", string.letters + string.digits + ".:-_")}
dns_lookup = {"displayName": "DNS Lookup",
"plugin": Plugin("host", string.letters + string.digits + ".:-_")}
mapping = {"addr": [whois, dns_lookup],
"string": [dns_lookup]}<commit_msg>Use the Team Cymru whois server by default, make it easier to use complex commands, and optionally insert a new line before the output.<commit_after>
|
import subprocess
import string
import shlex
class Plugin:
def __init__(self, command, allowedChars, insertInitialNewline=False):
# We replace the characters we do allow with empty strings, to get a string of all the characters we don't allow.
self.notAllowedCharMap = str(string.maketrans(allowedChars, " "*len(allowedChars)))
self.command = shlex.split(command)
self.insertInitialNewline = insertInitialNewline
def run(self, values):
sanitizedValues = []
for value in values:
sanitizedValues.append(str(value).translate(None, self.notAllowedCharMap))
result = subprocess.Popen(self.command + sanitizedValues, stdout=subprocess.PIPE)
stdout, stderr = result.communicate()
if self.insertInitialNewline:
stdout = "\n" + stdout
return stdout.replace("\n", "<br>")
whois = {"displayName": "Whois Lookup",
"plugin": Plugin("whois -h whois.cymru.com \" -p -u\"", string.letters + string.digits + ".:-_", insertInitialNewline=True)}
dns_lookup = {"displayName": "DNS Lookup",
"plugin": Plugin("host", string.letters + string.digits + ".:-_")}
mapping = {"addr": [whois, dns_lookup],
"string": [dns_lookup]}
|
import subprocess
import string
class Plugin:
def __init__(self, command, allowedChars):
# We replace the characters we do allow with empty strings, to get a string of all the characters we don't allow.
self.notAllowedCharMap = string.maketrans(allowedChars, " "*len(allowedChars))
self.command = command
def run(self, values):
sanitizedValues = []
for value in values:
sanitizedValues.append(str(value).translate(None, self.notAllowedCharMap))
result = subprocess.Popen([self.command] + sanitizedValues, stdout=subprocess.PIPE)
stdout, stderr = result.communicate()
return stdout.replace("\n", "<br>")
whois = {"displayName": "Whois Lookup",
"plugin": Plugin("whois", string.letters + string.digits + ".:-_")}
dns_lookup = {"displayName": "DNS Lookup",
"plugin": Plugin("host", string.letters + string.digits + ".:-_")}
mapping = {"addr": [whois, dns_lookup],
"string": [dns_lookup]}Use the Team Cymru whois server by default, make it easier to use complex commands, and optionally insert a new line before the output.import subprocess
import string
import shlex
class Plugin:
def __init__(self, command, allowedChars, insertInitialNewline=False):
# We replace the characters we do allow with empty strings, to get a string of all the characters we don't allow.
self.notAllowedCharMap = str(string.maketrans(allowedChars, " "*len(allowedChars)))
self.command = shlex.split(command)
self.insertInitialNewline = insertInitialNewline
def run(self, values):
sanitizedValues = []
for value in values:
sanitizedValues.append(str(value).translate(None, self.notAllowedCharMap))
result = subprocess.Popen(self.command + sanitizedValues, stdout=subprocess.PIPE)
stdout, stderr = result.communicate()
if self.insertInitialNewline:
stdout = "\n" + stdout
return stdout.replace("\n", "<br>")
whois = {"displayName": "Whois Lookup",
"plugin": Plugin("whois -h whois.cymru.com \" -p -u\"", string.letters + string.digits + ".:-_", insertInitialNewline=True)}
dns_lookup = {"displayName": "DNS Lookup",
"plugin": Plugin("host", string.letters + string.digits + ".:-_")}
mapping = {"addr": [whois, dns_lookup],
"string": [dns_lookup]}
|
<commit_before>import subprocess
import string
class Plugin:
def __init__(self, command, allowedChars):
# We replace the characters we do allow with empty strings, to get a string of all the characters we don't allow.
self.notAllowedCharMap = string.maketrans(allowedChars, " "*len(allowedChars))
self.command = command
def run(self, values):
sanitizedValues = []
for value in values:
sanitizedValues.append(str(value).translate(None, self.notAllowedCharMap))
result = subprocess.Popen([self.command] + sanitizedValues, stdout=subprocess.PIPE)
stdout, stderr = result.communicate()
return stdout.replace("\n", "<br>")
whois = {"displayName": "Whois Lookup",
"plugin": Plugin("whois", string.letters + string.digits + ".:-_")}
dns_lookup = {"displayName": "DNS Lookup",
"plugin": Plugin("host", string.letters + string.digits + ".:-_")}
mapping = {"addr": [whois, dns_lookup],
"string": [dns_lookup]}<commit_msg>Use the Team Cymru whois server by default, make it easier to use complex commands, and optionally insert a new line before the output.<commit_after>import subprocess
import string
import shlex
class Plugin:
def __init__(self, command, allowedChars, insertInitialNewline=False):
# We replace the characters we do allow with empty strings, to get a string of all the characters we don't allow.
self.notAllowedCharMap = str(string.maketrans(allowedChars, " "*len(allowedChars)))
self.command = shlex.split(command)
self.insertInitialNewline = insertInitialNewline
def run(self, values):
sanitizedValues = []
for value in values:
sanitizedValues.append(str(value).translate(None, self.notAllowedCharMap))
result = subprocess.Popen(self.command + sanitizedValues, stdout=subprocess.PIPE)
stdout, stderr = result.communicate()
if self.insertInitialNewline:
stdout = "\n" + stdout
return stdout.replace("\n", "<br>")
whois = {"displayName": "Whois Lookup",
"plugin": Plugin("whois -h whois.cymru.com \" -p -u\"", string.letters + string.digits + ".:-_", insertInitialNewline=True)}
dns_lookup = {"displayName": "DNS Lookup",
"plugin": Plugin("host", string.letters + string.digits + ".:-_")}
mapping = {"addr": [whois, dns_lookup],
"string": [dns_lookup]}
|
57444bdd253e428174c7a5475ef205063ac95ef3
|
lms/djangoapps/heartbeat/views.py
|
lms/djangoapps/heartbeat/views.py
|
import json
from datetime import datetime
from django.http import HttpResponse
def heartbeat(request):
"""
Simple view that a loadbalancer can check to verify that the app is up
"""
output = {
'date': datetime.now().isoformat()
}
return HttpResponse(json.dumps(output, indent=4))
|
import json
from datetime import datetime
from django.http import HttpResponse
from xmodule.modulestore.django import modulestore
def heartbeat(request):
"""
Simple view that a loadbalancer can check to verify that the app is up
"""
output = {
'date': datetime.now().isoformat(),
'courses': [course.location for course in modulestore().get_courses()],
}
return HttpResponse(json.dumps(output, indent=4))
|
Make heartbeat url wait for courses to be loaded
|
Make heartbeat url wait for courses to be loaded
|
Python
|
agpl-3.0
|
benpatterson/edx-platform,bigdatauniversity/edx-platform,Softmotions/edx-platform,shashank971/edx-platform,shabab12/edx-platform,ampax/edx-platform,mcgachey/edx-platform,yokose-ks/edx-platform,Livit/Livit.Learn.EdX,DefyVentures/edx-platform,pdehaye/theming-edx-platform,jruiperezv/ANALYSE,carsongee/edx-platform,jjmiranda/edx-platform,sudheerchintala/LearnEraPlatForm,olexiim/edx-platform,shubhdev/edx-platform,beacloudgenius/edx-platform,eestay/edx-platform,beacloudgenius/edx-platform,Edraak/edx-platform,torchingloom/edx-platform,EDUlib/edx-platform,IONISx/edx-platform,alu042/edx-platform,alexthered/kienhoc-platform,zhenzhai/edx-platform,jruiperezv/ANALYSE,dkarakats/edx-platform,inares/edx-platform,hmcmooc/muddx-platform,xingyepei/edx-platform,cyanna/edx-platform,hkawasaki/kawasaki-aio8-0,Stanford-Online/edx-platform,Kalyzee/edx-platform,playm2mboy/edx-platform,atsolakid/edx-platform,cognitiveclass/edx-platform,Livit/Livit.Learn.EdX,prarthitm/edxplatform,procangroup/edx-platform,angelapper/edx-platform,arbrandes/edx-platform,angelapper/edx-platform,Softmotions/edx-platform,itsjeyd/edx-platform,adoosii/edx-platform,mtlchun/edx,dsajkl/123,chauhanhardik/populo_2,benpatterson/edx-platform,mjirayu/sit_academy,kalebhartje/schoolboost,alu042/edx-platform,chrisndodge/edx-platform,DNFcode/edx-platform,analyseuc3m/ANALYSE-v1,CourseTalk/edx-platform,appliedx/edx-platform,dsajkl/123,mahendra-r/edx-platform,waheedahmed/edx-platform,antoviaque/edx-platform,Stanford-Online/edx-platform,dsajkl/reqiop,vasyarv/edx-platform,xingyepei/edx-platform,torchingloom/edx-platform,bigdatauniversity/edx-platform,cecep-edu/edx-platform,shabab12/edx-platform,MakeHer/edx-platform,rhndg/openedx,mtlchun/edx,zofuthan/edx-platform,shubhdev/edxOnBaadal,Semi-global/edx-platform,zhenzhai/edx-platform,Endika/edx-platform,eestay/edx-platform,nttks/edx-platform,shurihell/testasia,jbzdak/edx-platform,chand3040/cloud_that,ESOedX/edx-platform,LICEF/edx-platform,cpennington/edx-platform,hkawasaki/kawasaki-aio8-2,xinjiguaike/edx-platform,edx-solutions/edx-platform,sameetb-cuelogic/edx-platform-test,MSOpenTech/edx-platform,ak2703/edx-platform,nanolearningllc/edx-platform-cypress,devs1991/test_edx_docmode,ZLLab-Mooc/edx-platform,eduNEXT/edx-platform,waheedahmed/edx-platform,romain-li/edx-platform,vasyarv/edx-platform,PepperPD/edx-pepper-platform,Ayub-Khan/edx-platform,halvertoluke/edx-platform,mitocw/edx-platform,peterm-itr/edx-platform,nttks/jenkins-test,inares/edx-platform,hkawasaki/kawasaki-aio8-2,defance/edx-platform,chauhanhardik/populo_2,shubhdev/edxOnBaadal,kamalx/edx-platform,arbrandes/edx-platform,fintech-circle/edx-platform,polimediaupv/edx-platform,shubhdev/edx-platform,inares/edx-platform,shashank971/edx-platform,TeachAtTUM/edx-platform,kamalx/edx-platform,carsongee/edx-platform,IONISx/edx-platform,iivic/BoiseStateX,OmarIthawi/edx-platform,knehez/edx-platform,IITBinterns13/edx-platform-dev,beacloudgenius/edx-platform,dcosentino/edx-platform,eestay/edx-platform,procangroup/edx-platform,iivic/BoiseStateX,martynovp/edx-platform,jelugbo/tundex,appsembler/edx-platform,ahmedaljazzar/edx-platform,msegado/edx-platform,olexiim/edx-platform,torchingloom/edx-platform,dsajkl/reqiop,alexthered/kienhoc-platform,AkA84/edx-platform,edx/edx-platform,naresh21/synergetics-edx-platform,kmoocdev/edx-platform,adoosii/edx-platform,y12uc231/edx-platform,jbassen/edx-platform,jamesblunt/edx-platform,appliedx/edx-platform,pabloborrego93/edx-platform,dkarakats/edx-platform,chand3040/cloud_that,pabloborrego93/edx-platform,B-MOOC/edx-platform,apigee/edx-platform,jswope00/griffinx,waheedahmed/edx-platform,eemirtekin/edx-platform,gsehub/edx-platform,SivilTaram/edx-platform,UOMx/edx-platform,J861449197/edx-platform,mitocw/edx-platform,hkawasaki/kawasaki-aio8-2,MSOpenTech/edx-platform,y12uc231/edx-platform,arbrandes/edx-platform,Edraak/edraak-platform,chudaol/edx-platform,eemirtekin/edx-platform,motion2015/edx-platform,IndonesiaX/edx-platform,jswope00/griffinx,rationalAgent/edx-platform-custom,shubhdev/edxOnBaadal,xinjiguaike/edx-platform,jonathan-beard/edx-platform,TeachAtTUM/edx-platform,gymnasium/edx-platform,kxliugang/edx-platform,etzhou/edx-platform,tanmaykm/edx-platform,auferack08/edx-platform,andyzsf/edx,vismartltd/edx-platform,chand3040/cloud_that,nagyistoce/edx-platform,valtech-mooc/edx-platform,kursitet/edx-platform,Unow/edx-platform,morenopc/edx-platform,iivic/BoiseStateX,hamzehd/edx-platform,teltek/edx-platform,etzhou/edx-platform,longmen21/edx-platform,openfun/edx-platform,jjmiranda/edx-platform,marcore/edx-platform,philanthropy-u/edx-platform,SivilTaram/edx-platform,nagyistoce/edx-platform,benpatterson/edx-platform,martynovp/edx-platform,PepperPD/edx-pepper-platform,jbzdak/edx-platform,EDUlib/edx-platform,pomegranited/edx-platform,AkA84/edx-platform,caesar2164/edx-platform,ubc/edx-platform,pepeportela/edx-platform,auferack08/edx-platform,pku9104038/edx-platform,stvstnfrd/edx-platform,10clouds/edx-platform,EduPepperPDTesting/pepper2013-testing,ESOedX/edx-platform,jswope00/GAI,zofuthan/edx-platform,antonve/s4-project-mooc,ZLLab-Mooc/edx-platform,xuxiao19910803/edx,10clouds/edx-platform,chauhanhardik/populo,nagyistoce/edx-platform,bdero/edx-platform,EduPepperPD/pepper2013,mtlchun/edx,fintech-circle/edx-platform,kxliugang/edx-platform,unicri/edx-platform,alexthered/kienhoc-platform,arifsetiawan/edx-platform,kalebhartje/schoolboost,ovnicraft/edx-platform,Semi-global/edx-platform,beni55/edx-platform,deepsrijit1105/edx-platform,WatanabeYasumasa/edx-platform,franosincic/edx-platform,torchingloom/edx-platform,bdero/edx-platform,fintech-circle/edx-platform,jbassen/edx-platform,jzoldak/edx-platform,pomegranited/edx-platform,mahendra-r/edx-platform,angelapper/edx-platform,kursitet/edx-platform,ZLLab-Mooc/edx-platform,sameetb-cuelogic/edx-platform-test,morpheby/levelup-by,jamesblunt/edx-platform,y12uc231/edx-platform,shubhdev/edx-platform,yokose-ks/edx-platform,pdehaye/theming-edx-platform,morenopc/edx-platform,nanolearning/edx-platform,philanthropy-u/edx-platform,Kalyzee/edx-platform,dsajkl/reqiop,mtlchun/edx,JCBarahona/edX,motion2015/a3,rationalAgent/edx-platform-custom,Endika/edx-platform,zubair-arbi/edx-platform,caesar2164/edx-platform,eduNEXT/edx-platform,SravanthiSinha/edx-platform,kmoocdev2/edx-platform,franosincic/edx-platform,LearnEra/LearnEraPlaftform,antonve/s4-project-mooc,nanolearning/edx-platform,jbzdak/edx-platform,10clouds/edx-platform,wwj718/edx-platform,Kalyzee/edx-platform,jbassen/edx-platform,10clouds/edx-platform,sudheerchintala/LearnEraPlatForm,ahmadio/edx-platform,nanolearningllc/edx-platform-cypress,ampax/edx-platform-backup,CredoReference/edx-platform,4eek/edx-platform,chand3040/cloud_that,hkawasaki/kawasaki-aio8-1,iivic/BoiseStateX,don-github/edx-platform,cpennington/edx-platform,valtech-mooc/edx-platform,wwj718/edx-platform,polimediaupv/edx-platform,kamalx/edx-platform,xinjiguaike/edx-platform,rue89-tech/edx-platform,zerobatu/edx-platform,bitifirefly/edx-platform,shubhdev/openedx,lduarte1991/edx-platform,nanolearningllc/edx-platform-cypress-2,ahmedaljazzar/edx-platform,jazkarta/edx-platform-for-isc,vasyarv/edx-platform,syjeon/new_edx,nikolas/edx-platform,marcore/edx-platform,longmen21/edx-platform,a-parhom/edx-platform,ovnicraft/edx-platform,sameetb-cuelogic/edx-platform-test,cselis86/edx-platform,ovnicraft/edx-platform,nanolearning/edx-platform,shurihell/testasia,arifsetiawan/edx-platform,DefyVentures/edx-platform,nttks/edx-platform,EduPepperPD/pepper2013,louyihua/edx-platform,atsolakid/edx-platform,xingyepei/edx-platform,CourseTalk/edx-platform,ubc/edx-platform,jazztpt/edx-platform,shashank971/edx-platform,OmarIthawi/edx-platform,franosincic/edx-platform,raccoongang/edx-platform,jazkarta/edx-platform,kxliugang/edx-platform,MSOpenTech/edx-platform,nanolearningllc/edx-platform-cypress,msegado/edx-platform,Livit/Livit.Learn.EdX,hastexo/edx-platform,peterm-itr/edx-platform,ahmadio/edx-platform,nanolearningllc/edx-platform-cypress-2,amir-qayyum-khan/edx-platform,SivilTaram/edx-platform,mushtaqak/edx-platform,zadgroup/edx-platform,edx/edx-platform,pepeportela/edx-platform,ahmadiga/min_edx,fly19890211/edx-platform,jruiperezv/ANALYSE,kmoocdev/edx-platform,RPI-OPENEDX/edx-platform,WatanabeYasumasa/edx-platform,zadgroup/edx-platform,etzhou/edx-platform,jruiperezv/ANALYSE,shubhdev/edx-platform,openfun/edx-platform,cselis86/edx-platform,Edraak/circleci-edx-platform,abdoosh00/edx-rtl-final,eduNEXT/edx-platform,dkarakats/edx-platform,zubair-arbi/edx-platform,romain-li/edx-platform,iivic/BoiseStateX,gsehub/edx-platform,morpheby/levelup-by,nttks/jenkins-test,leansoft/edx-platform,antoviaque/edx-platform,Edraak/edraak-platform,unicri/edx-platform,jelugbo/tundex,edry/edx-platform,abdoosh00/edraak,Stanford-Online/edx-platform,itsjeyd/edx-platform,shubhdev/openedx,rismalrv/edx-platform,motion2015/edx-platform,yokose-ks/edx-platform,utecuy/edx-platform,ferabra/edx-platform,nikolas/edx-platform,romain-li/edx-platform,Edraak/edraak-platform,a-parhom/edx-platform,mahendra-r/edx-platform,amir-qayyum-khan/edx-platform,abdoosh00/edraak,jswope00/GAI,DNFcode/edx-platform,beni55/edx-platform,dcosentino/edx-platform,atsolakid/edx-platform,naresh21/synergetics-edx-platform,4eek/edx-platform,UOMx/edx-platform,xuxiao19910803/edx-platform,chauhanhardik/populo,longmen21/edx-platform,shubhdev/openedx,edx/edx-platform,pelikanchik/edx-platform,yokose-ks/edx-platform,SravanthiSinha/edx-platform,apigee/edx-platform,alu042/edx-platform,Lektorium-LLC/edx-platform,fly19890211/edx-platform,xuxiao19910803/edx,pelikanchik/edx-platform,carsongee/edx-platform,fintech-circle/edx-platform,jolyonb/edx-platform,Semi-global/edx-platform,apigee/edx-platform,mcgachey/edx-platform,jamesblunt/edx-platform,antonve/s4-project-mooc,doismellburning/edx-platform,Ayub-Khan/edx-platform,Edraak/circleci-edx-platform,xuxiao19910803/edx-platform,zofuthan/edx-platform,jzoldak/edx-platform,beacloudgenius/edx-platform,motion2015/edx-platform,appliedx/edx-platform,olexiim/edx-platform,a-parhom/edx-platform,cognitiveclass/edx-platform,olexiim/edx-platform,valtech-mooc/edx-platform,Livit/Livit.Learn.EdX,IndonesiaX/edx-platform,dkarakats/edx-platform,morpheby/levelup-by,dsajkl/123,martynovp/edx-platform,ampax/edx-platform-backup,tanmaykm/edx-platform,angelapper/edx-platform,jazkarta/edx-platform,SivilTaram/edx-platform,pelikanchik/edx-platform,IONISx/edx-platform,edx-solutions/edx-platform,J861449197/edx-platform,chrisndodge/edx-platform,Softmotions/edx-platform,openfun/edx-platform,zerobatu/edx-platform,atsolakid/edx-platform,atsolakid/edx-platform,mjirayu/sit_academy,rue89-tech/edx-platform,appliedx/edx-platform,ak2703/edx-platform,gsehub/edx-platform,ahmadiga/min_edx,don-github/edx-platform,shubhdev/edx-platform,Edraak/edx-platform,pku9104038/edx-platform,prarthitm/edxplatform,solashirai/edx-platform,mbareta/edx-platform-ft,xinjiguaike/edx-platform,BehavioralInsightsTeam/edx-platform,Softmotions/edx-platform,devs1991/test_edx_docmode,shabab12/edx-platform,TeachAtTUM/edx-platform,mjg2203/edx-platform-seas,peterm-itr/edx-platform,synergeticsedx/deployment-wipro,inares/edx-platform,lduarte1991/edx-platform,motion2015/a3,xuxiao19910803/edx-platform,Stanford-Online/edx-platform,doganov/edx-platform,appsembler/edx-platform,philanthropy-u/edx-platform,nanolearningllc/edx-platform-cypress-2,morenopc/edx-platform,carsongee/edx-platform,ferabra/edx-platform,andyzsf/edx,appsembler/edx-platform,Shrhawk/edx-platform,teltek/edx-platform,halvertoluke/edx-platform,eemirtekin/edx-platform,etzhou/edx-platform,tanmaykm/edx-platform,B-MOOC/edx-platform,xingyepei/edx-platform,beacloudgenius/edx-platform,jolyonb/edx-platform,jelugbo/tundex,mushtaqak/edx-platform,jazkarta/edx-platform,pku9104038/edx-platform,Edraak/edx-platform,ahmedaljazzar/edx-platform,appsembler/edx-platform,jswope00/griffinx,playm2mboy/edx-platform,ubc/edx-platform,kxliugang/edx-platform,y12uc231/edx-platform,JCBarahona/edX,RPI-OPENEDX/edx-platform,devs1991/test_edx_docmode,IITBinterns13/edx-platform-dev,adoosii/edx-platform,polimediaupv/edx-platform,UXE/local-edx,mahendra-r/edx-platform,SravanthiSinha/edx-platform,analyseuc3m/ANALYSE-v1,hmcmooc/muddx-platform,auferack08/edx-platform,jbzdak/edx-platform,kursitet/edx-platform,Endika/edx-platform,rismalrv/edx-platform,EduPepperPDTesting/pepper2013-testing,devs1991/test_edx_docmode,hamzehd/edx-platform,sudheerchintala/LearnEraPlatForm,dcosentino/edx-platform,ahmadiga/min_edx,kalebhartje/schoolboost,wwj718/ANALYSE,deepsrijit1105/edx-platform,syjeon/new_edx,procangroup/edx-platform,Unow/edx-platform,nikolas/edx-platform,J861449197/edx-platform,ahmedaljazzar/edx-platform,cognitiveclass/edx-platform,prarthitm/edxplatform,syjeon/new_edx,louyihua/edx-platform,defance/edx-platform,EduPepperPDTesting/pepper2013-testing,mjg2203/edx-platform-seas,MSOpenTech/edx-platform,Ayub-Khan/edx-platform,Edraak/edx-platform,devs1991/test_edx_docmode,edx-solutions/edx-platform,peterm-itr/edx-platform,vismartltd/edx-platform,vasyarv/edx-platform,ferabra/edx-platform,Shrhawk/edx-platform,openfun/edx-platform,pomegranited/edx-platform,ahmadio/edx-platform,eduNEXT/edunext-platform,UXE/local-edx,Lektorium-LLC/edx-platform,Edraak/circleci-edx-platform,don-github/edx-platform,simbs/edx-platform,chauhanhardik/populo,hmcmooc/muddx-platform,zubair-arbi/edx-platform,bitifirefly/edx-platform,DNFcode/edx-platform,Kalyzee/edx-platform,fly19890211/edx-platform,pdehaye/theming-edx-platform,shubhdev/edxOnBaadal,doganov/edx-platform,doismellburning/edx-platform,EDUlib/edx-platform,antonve/s4-project-mooc,rhndg/openedx,pku9104038/edx-platform,inares/edx-platform,philanthropy-u/edx-platform,deepsrijit1105/edx-platform,bdero/edx-platform,edry/edx-platform,prarthitm/edxplatform,jswope00/GAI,nanolearning/edx-platform,mjg2203/edx-platform-seas,nttks/jenkins-test,teltek/edx-platform,jamiefolsom/edx-platform,Unow/edx-platform,caesar2164/edx-platform,cecep-edu/edx-platform,solashirai/edx-platform,procangroup/edx-platform,gymnasium/edx-platform,devs1991/test_edx_docmode,polimediaupv/edx-platform,don-github/edx-platform,tiagochiavericosta/edx-platform,gymnasium/edx-platform,shubhdev/edxOnBaadal,nikolas/edx-platform,bigdatauniversity/edx-platform,vikas1885/test1,mjirayu/sit_academy,wwj718/edx-platform,utecuy/edx-platform,doismellburning/edx-platform,UXE/local-edx,vismartltd/edx-platform,Shrhawk/edx-platform,xuxiao19910803/edx,zhenzhai/edx-platform,rhndg/openedx,IndonesiaX/edx-platform,praveen-pal/edx-platform,MSOpenTech/edx-platform,kxliugang/edx-platform,WatanabeYasumasa/edx-platform,utecuy/edx-platform,jonathan-beard/edx-platform,vasyarv/edx-platform,simbs/edx-platform,alexthered/kienhoc-platform,EduPepperPD/pepper2013,chauhanhardik/populo,morenopc/edx-platform,J861449197/edx-platform,SravanthiSinha/edx-platform,hkawasaki/kawasaki-aio8-1,OmarIthawi/edx-platform,vikas1885/test1,devs1991/test_edx_docmode,eduNEXT/edunext-platform,jamiefolsom/edx-platform,amir-qayyum-khan/edx-platform,rue89-tech/edx-platform,waheedahmed/edx-platform,Endika/edx-platform,utecuy/edx-platform,raccoongang/edx-platform,beni55/edx-platform,jamiefolsom/edx-platform,gymnasium/edx-platform,AkA84/edx-platform,synergeticsedx/deployment-wipro,shashank971/edx-platform,ampax/edx-platform-backup,jazztpt/edx-platform,cognitiveclass/edx-platform,itsjeyd/edx-platform,bigdatauniversity/edx-platform,playm2mboy/edx-platform,shubhdev/openedx,jazkarta/edx-platform,eemirtekin/edx-platform,rue89-tech/edx-platform,4eek/edx-platform,pabloborrego93/edx-platform,olexiim/edx-platform,hamzehd/edx-platform,chauhanhardik/populo_2,louyihua/edx-platform,jjmiranda/edx-platform,mtlchun/edx,abdoosh00/edraak,IONISx/edx-platform,playm2mboy/edx-platform,jonathan-beard/edx-platform,kmoocdev2/edx-platform,pepeportela/edx-platform,benpatterson/edx-platform,vismartltd/edx-platform,rationalAgent/edx-platform-custom,yokose-ks/edx-platform,adoosii/edx-platform,jamesblunt/edx-platform,mcgachey/edx-platform,JioEducation/edx-platform,Edraak/edraak-platform,utecuy/edx-platform,martynovp/edx-platform,mushtaqak/edx-platform,jazkarta/edx-platform-for-isc,kursitet/edx-platform,cselis86/edx-platform,franosincic/edx-platform,franosincic/edx-platform,J861449197/edx-platform,PepperPD/edx-pepper-platform,jazztpt/edx-platform,bdero/edx-platform,hamzehd/edx-platform,pelikanchik/edx-platform,jazkarta/edx-platform,kmoocdev/edx-platform,chand3040/cloud_that,morenopc/edx-platform,edry/edx-platform,cecep-edu/edx-platform,LearnEra/LearnEraPlaftform,Unow/edx-platform,openfun/edx-platform,edry/edx-platform,LICEF/edx-platform,unicri/edx-platform,ESOedX/edx-platform,jelugbo/tundex,ubc/edx-platform,wwj718/ANALYSE,appliedx/edx-platform,cselis86/edx-platform,ak2703/edx-platform,MakeHer/edx-platform,alexthered/kienhoc-platform,rismalrv/edx-platform,cognitiveclass/edx-platform,halvertoluke/edx-platform,wwj718/edx-platform,teltek/edx-platform,zerobatu/edx-platform,DNFcode/edx-platform,shurihell/testasia,hkawasaki/kawasaki-aio8-0,andyzsf/edx,nanolearningllc/edx-platform-cypress,ovnicraft/edx-platform,ahmadiga/min_edx,nagyistoce/edx-platform,kmoocdev2/edx-platform,motion2015/a3,sudheerchintala/LearnEraPlatForm,EDUlib/edx-platform,Semi-global/edx-platform,eestay/edx-platform,hkawasaki/kawasaki-aio8-2,arifsetiawan/edx-platform,longmen21/edx-platform,defance/edx-platform,RPI-OPENEDX/edx-platform,morpheby/levelup-by,ferabra/edx-platform,valtech-mooc/edx-platform,leansoft/edx-platform,arifsetiawan/edx-platform,knehez/edx-platform,rue89-tech/edx-platform,DefyVentures/edx-platform,B-MOOC/edx-platform,cecep-edu/edx-platform,synergeticsedx/deployment-wipro,mushtaqak/edx-platform,IndonesiaX/edx-platform,xuxiao19910803/edx,analyseuc3m/ANALYSE-v1,rhndg/openedx,nanolearningllc/edx-platform-cypress,eestay/edx-platform,chauhanhardik/populo_2,playm2mboy/edx-platform,miptliot/edx-platform,adoosii/edx-platform,nttks/edx-platform,cpennington/edx-platform,tiagochiavericosta/edx-platform,abdoosh00/edx-rtl-final,rismalrv/edx-platform,4eek/edx-platform,wwj718/ANALYSE,JioEducation/edx-platform,kamalx/edx-platform,jazztpt/edx-platform,proversity-org/edx-platform,BehavioralInsightsTeam/edx-platform,motion2015/edx-platform,apigee/edx-platform,caesar2164/edx-platform,chauhanhardik/populo_2,jonathan-beard/edx-platform,WatanabeYasumasa/edx-platform,MakeHer/edx-platform,nttks/jenkins-test,B-MOOC/edx-platform,MakeHer/edx-platform,pabloborrego93/edx-platform,bigdatauniversity/edx-platform,mjg2203/edx-platform-seas,dkarakats/edx-platform,mitocw/edx-platform,nttks/jenkins-test,abdoosh00/edx-rtl-final,alu042/edx-platform,eduNEXT/edunext-platform,SivilTaram/edx-platform,ampax/edx-platform-backup,RPI-OPENEDX/edx-platform,chudaol/edx-platform,cselis86/edx-platform,benpatterson/edx-platform,halvertoluke/edx-platform,ampax/edx-platform,rationalAgent/edx-platform-custom,amir-qayyum-khan/edx-platform,arbrandes/edx-platform,dsajkl/123,ahmadiga/min_edx,doismellburning/edx-platform,AkA84/edx-platform,devs1991/test_edx_docmode,AkA84/edx-platform,LICEF/edx-platform,dcosentino/edx-platform,rismalrv/edx-platform,xingyepei/edx-platform,miptliot/edx-platform,chudaol/edx-platform,itsjeyd/edx-platform,solashirai/edx-platform,motion2015/edx-platform,pomegranited/edx-platform,vikas1885/test1,RPI-OPENEDX/edx-platform,mahendra-r/edx-platform,jswope00/griffinx,doismellburning/edx-platform,IITBinterns13/edx-platform-dev,praveen-pal/edx-platform,chudaol/edx-platform,cpennington/edx-platform,Edraak/edx-platform,Edraak/circleci-edx-platform,ahmadio/edx-platform,vikas1885/test1,nanolearning/edx-platform,vikas1885/test1,knehez/edx-platform,zerobatu/edx-platform,IndonesiaX/edx-platform,romain-li/edx-platform,hamzehd/edx-platform,hkawasaki/kawasaki-aio8-0,UOMx/edx-platform,naresh21/synergetics-edx-platform,UOMx/edx-platform,cyanna/edx-platform,jruiperezv/ANALYSE,bitifirefly/edx-platform,jelugbo/tundex,hkawasaki/kawasaki-aio8-1,leansoft/edx-platform,solashirai/edx-platform,nikolas/edx-platform,Softmotions/edx-platform,OmarIthawi/edx-platform,ampax/edx-platform,shurihell/testasia,proversity-org/edx-platform,cyanna/edx-platform,jazkarta/edx-platform-for-isc,kmoocdev/edx-platform,edx/edx-platform,eemirtekin/edx-platform,Shrhawk/edx-platform,hastexo/edx-platform,ampax/edx-platform-backup,PepperPD/edx-pepper-platform,unicri/edx-platform,zadgroup/edx-platform,analyseuc3m/ANALYSE-v1,eduNEXT/edx-platform,mitocw/edx-platform,JCBarahona/edX,UXE/local-edx,kalebhartje/schoolboost,abdoosh00/edx-rtl-final,msegado/edx-platform,leansoft/edx-platform,antonve/s4-project-mooc,hastexo/edx-platform,zubair-arbi/edx-platform,praveen-pal/edx-platform,ahmadio/edx-platform,Lektorium-LLC/edx-platform,arifsetiawan/edx-platform,ZLLab-Mooc/edx-platform,chudaol/edx-platform,dcosentino/edx-platform,JCBarahona/edX,JCBarahona/edX,fly19890211/edx-platform,SravanthiSinha/edx-platform,TsinghuaX/edx-platform,jbassen/edx-platform,marcore/edx-platform,jolyonb/edx-platform,LearnEra/LearnEraPlaftform,edry/edx-platform,ampax/edx-platform,jolyonb/edx-platform,edx-solutions/edx-platform,msegado/edx-platform,lduarte1991/edx-platform,solashirai/edx-platform,deepsrijit1105/edx-platform,bitifirefly/edx-platform,knehez/edx-platform,eduNEXT/edunext-platform,BehavioralInsightsTeam/edx-platform,beni55/edx-platform,xuxiao19910803/edx-platform,LICEF/edx-platform,LICEF/edx-platform,cyanna/edx-platform,Semi-global/edx-platform,miptliot/edx-platform,zubair-arbi/edx-platform,wwj718/edx-platform,DNFcode/edx-platform,a-parhom/edx-platform,simbs/edx-platform,miptliot/edx-platform,halvertoluke/edx-platform,DefyVentures/edx-platform,zofuthan/edx-platform,dsajkl/reqiop,proversity-org/edx-platform,jazztpt/edx-platform,wwj718/ANALYSE,TsinghuaX/edx-platform,chauhanhardik/populo,hkawasaki/kawasaki-aio8-1,kmoocdev2/edx-platform,ak2703/edx-platform,Ayub-Khan/edx-platform,tiagochiavericosta/edx-platform,B-MOOC/edx-platform,nanolearningllc/edx-platform-cypress-2,defance/edx-platform,xinjiguaike/edx-platform,martynovp/edx-platform,jonathan-beard/edx-platform,BehavioralInsightsTeam/edx-platform,abdoosh00/edraak,mbareta/edx-platform-ft,mbareta/edx-platform-ft,tiagochiavericosta/edx-platform,valtech-mooc/edx-platform,CourseTalk/edx-platform,JioEducation/edx-platform,praveen-pal/edx-platform,zerobatu/edx-platform,antoviaque/edx-platform,mushtaqak/edx-platform,jzoldak/edx-platform,Ayub-Khan/edx-platform,pepeportela/edx-platform,EduPepperPD/pepper2013,CredoReference/edx-platform,rationalAgent/edx-platform-custom,JioEducation/edx-platform,louyihua/edx-platform,mjirayu/sit_academy,don-github/edx-platform,TeachAtTUM/edx-platform,gsehub/edx-platform,kamalx/edx-platform,andyzsf/edx,ferabra/edx-platform,4eek/edx-platform,shurihell/testasia,ovnicraft/edx-platform,auferack08/edx-platform,cyanna/edx-platform,nanolearningllc/edx-platform-cypress-2,xuxiao19910803/edx,stvstnfrd/edx-platform,bitifirefly/edx-platform,ak2703/edx-platform,Edraak/circleci-edx-platform,antoviaque/edx-platform,raccoongang/edx-platform,mcgachey/edx-platform,zhenzhai/edx-platform,nagyistoce/edx-platform,motion2015/a3,xuxiao19910803/edx-platform,stvstnfrd/edx-platform,tanmaykm/edx-platform,MakeHer/edx-platform,jbzdak/edx-platform,longmen21/edx-platform,kmoocdev/edx-platform,EduPepperPDTesting/pepper2013-testing,simbs/edx-platform,msegado/edx-platform,mcgachey/edx-platform,TsinghuaX/edx-platform,mbareta/edx-platform-ft,jjmiranda/edx-platform,chrisndodge/edx-platform,beni55/edx-platform,tiagochiavericosta/edx-platform,kmoocdev2/edx-platform,stvstnfrd/edx-platform,IITBinterns13/edx-platform-dev,shubhdev/openedx,leansoft/edx-platform,fly19890211/edx-platform,zadgroup/edx-platform,unicri/edx-platform,Shrhawk/edx-platform,kalebhartje/schoolboost,vismartltd/edx-platform,cecep-edu/edx-platform,IONISx/edx-platform,jamesblunt/edx-platform,doganov/edx-platform,jamiefolsom/edx-platform,jswope00/GAI,marcore/edx-platform,kursitet/edx-platform,doganov/edx-platform,CredoReference/edx-platform,Lektorium-LLC/edx-platform,LearnEra/LearnEraPlaftform,waheedahmed/edx-platform,polimediaupv/edx-platform,naresh21/synergetics-edx-platform,DefyVentures/edx-platform,romain-li/edx-platform,chrisndodge/edx-platform,dsajkl/123,mjirayu/sit_academy,zhenzhai/edx-platform,CredoReference/edx-platform,TsinghuaX/edx-platform,ZLLab-Mooc/edx-platform,y12uc231/edx-platform,wwj718/ANALYSE,pdehaye/theming-edx-platform,jbassen/edx-platform,nttks/edx-platform,PepperPD/edx-pepper-platform,motion2015/a3,knehez/edx-platform,jswope00/griffinx,jamiefolsom/edx-platform,rhndg/openedx,raccoongang/edx-platform,etzhou/edx-platform,doganov/edx-platform,sameetb-cuelogic/edx-platform-test,lduarte1991/edx-platform,jazkarta/edx-platform-for-isc,ubc/edx-platform,hmcmooc/muddx-platform,hastexo/edx-platform,syjeon/new_edx,ESOedX/edx-platform,nttks/edx-platform,zadgroup/edx-platform,CourseTalk/edx-platform,shabab12/edx-platform,simbs/edx-platform,zofuthan/edx-platform,sameetb-cuelogic/edx-platform-test,pomegranited/edx-platform,hkawasaki/kawasaki-aio8-0,jazkarta/edx-platform-for-isc,shashank971/edx-platform,Kalyzee/edx-platform,EduPepperPD/pepper2013,torchingloom/edx-platform,jzoldak/edx-platform,proversity-org/edx-platform,synergeticsedx/deployment-wipro,EduPepperPDTesting/pepper2013-testing,EduPepperPDTesting/pepper2013-testing
|
import json
from datetime import datetime
from django.http import HttpResponse
def heartbeat(request):
"""
Simple view that a loadbalancer can check to verify that the app is up
"""
output = {
'date': datetime.now().isoformat()
}
return HttpResponse(json.dumps(output, indent=4))
Make heartbeat url wait for courses to be loaded
|
import json
from datetime import datetime
from django.http import HttpResponse
from xmodule.modulestore.django import modulestore
def heartbeat(request):
"""
Simple view that a loadbalancer can check to verify that the app is up
"""
output = {
'date': datetime.now().isoformat(),
'courses': [course.location for course in modulestore().get_courses()],
}
return HttpResponse(json.dumps(output, indent=4))
|
<commit_before>import json
from datetime import datetime
from django.http import HttpResponse
def heartbeat(request):
"""
Simple view that a loadbalancer can check to verify that the app is up
"""
output = {
'date': datetime.now().isoformat()
}
return HttpResponse(json.dumps(output, indent=4))
<commit_msg>Make heartbeat url wait for courses to be loaded<commit_after>
|
import json
from datetime import datetime
from django.http import HttpResponse
from xmodule.modulestore.django import modulestore
def heartbeat(request):
"""
Simple view that a loadbalancer can check to verify that the app is up
"""
output = {
'date': datetime.now().isoformat(),
'courses': [course.location for course in modulestore().get_courses()],
}
return HttpResponse(json.dumps(output, indent=4))
|
import json
from datetime import datetime
from django.http import HttpResponse
def heartbeat(request):
"""
Simple view that a loadbalancer can check to verify that the app is up
"""
output = {
'date': datetime.now().isoformat()
}
return HttpResponse(json.dumps(output, indent=4))
Make heartbeat url wait for courses to be loadedimport json
from datetime import datetime
from django.http import HttpResponse
from xmodule.modulestore.django import modulestore
def heartbeat(request):
"""
Simple view that a loadbalancer can check to verify that the app is up
"""
output = {
'date': datetime.now().isoformat(),
'courses': [course.location for course in modulestore().get_courses()],
}
return HttpResponse(json.dumps(output, indent=4))
|
<commit_before>import json
from datetime import datetime
from django.http import HttpResponse
def heartbeat(request):
"""
Simple view that a loadbalancer can check to verify that the app is up
"""
output = {
'date': datetime.now().isoformat()
}
return HttpResponse(json.dumps(output, indent=4))
<commit_msg>Make heartbeat url wait for courses to be loaded<commit_after>import json
from datetime import datetime
from django.http import HttpResponse
from xmodule.modulestore.django import modulestore
def heartbeat(request):
"""
Simple view that a loadbalancer can check to verify that the app is up
"""
output = {
'date': datetime.now().isoformat(),
'courses': [course.location for course in modulestore().get_courses()],
}
return HttpResponse(json.dumps(output, indent=4))
|
59b920d3c5d699c180be4dafec86f50a0c636028
|
work/print-traceback.py
|
work/print-traceback.py
|
#!/usr/bin/python3
from pprint import pprint
import json
import sys
if __name__ == '__main__':
if len(sys.argv) >= 2:
path = sys.argv[1].split('.')
else:
path = ['error', 'stack']
obj = json.load(sys.stdin)
try:
for part in path:
obj = obj[part]
except KeyError:
pass
if isinstance(obj, str):
print(obj)
else:
pprint(obj)
|
#!/usr/bin/python3
from pprint import pprint
import json
import sys
def get(obj, path):
try:
for part in path:
obj = obj[part]
return obj
except KeyError:
return None
if __name__ == '__main__':
if len(sys.argv) >= 2:
paths = [sys.argv[1].split('.')]
else:
paths = [
['meta', 'error', 'stack'],
['error', 'stack'],
['traceback'],
]
obj = json.load(sys.stdin)
for path in paths:
subobj = get(obj, path)
if subobj is not None:
obj = subobj
break
if isinstance(obj, str):
print(obj)
else:
pprint(obj)
|
Improve stacktrace print for traceback.
|
Improve stacktrace print for traceback.
|
Python
|
mit
|
ammongit/scripts,ammongit/scripts,ammongit/scripts,ammongit/scripts
|
#!/usr/bin/python3
from pprint import pprint
import json
import sys
if __name__ == '__main__':
if len(sys.argv) >= 2:
path = sys.argv[1].split('.')
else:
path = ['error', 'stack']
obj = json.load(sys.stdin)
try:
for part in path:
obj = obj[part]
except KeyError:
pass
if isinstance(obj, str):
print(obj)
else:
pprint(obj)
Improve stacktrace print for traceback.
|
#!/usr/bin/python3
from pprint import pprint
import json
import sys
def get(obj, path):
try:
for part in path:
obj = obj[part]
return obj
except KeyError:
return None
if __name__ == '__main__':
if len(sys.argv) >= 2:
paths = [sys.argv[1].split('.')]
else:
paths = [
['meta', 'error', 'stack'],
['error', 'stack'],
['traceback'],
]
obj = json.load(sys.stdin)
for path in paths:
subobj = get(obj, path)
if subobj is not None:
obj = subobj
break
if isinstance(obj, str):
print(obj)
else:
pprint(obj)
|
<commit_before>#!/usr/bin/python3
from pprint import pprint
import json
import sys
if __name__ == '__main__':
if len(sys.argv) >= 2:
path = sys.argv[1].split('.')
else:
path = ['error', 'stack']
obj = json.load(sys.stdin)
try:
for part in path:
obj = obj[part]
except KeyError:
pass
if isinstance(obj, str):
print(obj)
else:
pprint(obj)
<commit_msg>Improve stacktrace print for traceback.<commit_after>
|
#!/usr/bin/python3
from pprint import pprint
import json
import sys
def get(obj, path):
try:
for part in path:
obj = obj[part]
return obj
except KeyError:
return None
if __name__ == '__main__':
if len(sys.argv) >= 2:
paths = [sys.argv[1].split('.')]
else:
paths = [
['meta', 'error', 'stack'],
['error', 'stack'],
['traceback'],
]
obj = json.load(sys.stdin)
for path in paths:
subobj = get(obj, path)
if subobj is not None:
obj = subobj
break
if isinstance(obj, str):
print(obj)
else:
pprint(obj)
|
#!/usr/bin/python3
from pprint import pprint
import json
import sys
if __name__ == '__main__':
if len(sys.argv) >= 2:
path = sys.argv[1].split('.')
else:
path = ['error', 'stack']
obj = json.load(sys.stdin)
try:
for part in path:
obj = obj[part]
except KeyError:
pass
if isinstance(obj, str):
print(obj)
else:
pprint(obj)
Improve stacktrace print for traceback.#!/usr/bin/python3
from pprint import pprint
import json
import sys
def get(obj, path):
try:
for part in path:
obj = obj[part]
return obj
except KeyError:
return None
if __name__ == '__main__':
if len(sys.argv) >= 2:
paths = [sys.argv[1].split('.')]
else:
paths = [
['meta', 'error', 'stack'],
['error', 'stack'],
['traceback'],
]
obj = json.load(sys.stdin)
for path in paths:
subobj = get(obj, path)
if subobj is not None:
obj = subobj
break
if isinstance(obj, str):
print(obj)
else:
pprint(obj)
|
<commit_before>#!/usr/bin/python3
from pprint import pprint
import json
import sys
if __name__ == '__main__':
if len(sys.argv) >= 2:
path = sys.argv[1].split('.')
else:
path = ['error', 'stack']
obj = json.load(sys.stdin)
try:
for part in path:
obj = obj[part]
except KeyError:
pass
if isinstance(obj, str):
print(obj)
else:
pprint(obj)
<commit_msg>Improve stacktrace print for traceback.<commit_after>#!/usr/bin/python3
from pprint import pprint
import json
import sys
def get(obj, path):
try:
for part in path:
obj = obj[part]
return obj
except KeyError:
return None
if __name__ == '__main__':
if len(sys.argv) >= 2:
paths = [sys.argv[1].split('.')]
else:
paths = [
['meta', 'error', 'stack'],
['error', 'stack'],
['traceback'],
]
obj = json.load(sys.stdin)
for path in paths:
subobj = get(obj, path)
if subobj is not None:
obj = subobj
break
if isinstance(obj, str):
print(obj)
else:
pprint(obj)
|
4922d53f95b3f7c055afe1d0af0088b505cbc0d2
|
addons/bestja_configuration_ucw/__openerp__.py
|
addons/bestja_configuration_ucw/__openerp__.py
|
# -*- coding: utf-8 -*-
{
'name': "Bestja: UCW",
'summary': "Installation configuration for UCW",
'description': "Installation configuration for Uniwersyteckie Centrum Wolontariatu",
'author': "Laboratorium EE",
'website': "http://www.laboratorium.ee",
'version': '0.1',
'category': 'Specific Industry Applications',
'depends': [
'base',
'bestja_base',
'bestja_volunteer',
'bestja_volunteer_notes',
'bestja_account_deletion',
'bestja_organization',
'bestja_project',
'bestja_offers',
'bestja_offers_moderation',
'bestja_offers_invitations',
'bestja_offers_categorization',
'bestja_files',
'bestja_application_moderation',
'bestja_ucw_permissions',
],
'data': [
'data.xml',
],
'application': True,
}
|
# -*- coding: utf-8 -*-
{
'name': "Bestja: UCW",
'summary': "Installation configuration for UCW",
'description': "Installation configuration for Uniwersyteckie Centrum Wolontariatu",
'author': "Laboratorium EE",
'website': "http://www.laboratorium.ee",
'version': '0.1',
'category': 'Specific Industry Applications',
'depends': [
'base',
'website_blog',
'bestja_base',
'bestja_volunteer',
'bestja_volunteer_notes',
'bestja_account_deletion',
'bestja_organization',
'bestja_project',
'bestja_offers',
'bestja_offers_moderation',
'bestja_offers_invitations',
'bestja_offers_categorization',
'bestja_files',
'bestja_application_moderation',
'bestja_ucw_permissions',
],
'data': [
'data.xml',
],
'application': True,
}
|
Enable Odoo blog for UCW
|
Enable Odoo blog for UCW
|
Python
|
agpl-3.0
|
EE/bestja,EE/bestja,KamilWo/bestja,KamilWo/bestja,KrzysiekJ/bestja,ludwiktrammer/bestja,EE/bestja,ludwiktrammer/bestja,KamilWo/bestja,KrzysiekJ/bestja,ludwiktrammer/bestja,KrzysiekJ/bestja
|
# -*- coding: utf-8 -*-
{
'name': "Bestja: UCW",
'summary': "Installation configuration for UCW",
'description': "Installation configuration for Uniwersyteckie Centrum Wolontariatu",
'author': "Laboratorium EE",
'website': "http://www.laboratorium.ee",
'version': '0.1',
'category': 'Specific Industry Applications',
'depends': [
'base',
'bestja_base',
'bestja_volunteer',
'bestja_volunteer_notes',
'bestja_account_deletion',
'bestja_organization',
'bestja_project',
'bestja_offers',
'bestja_offers_moderation',
'bestja_offers_invitations',
'bestja_offers_categorization',
'bestja_files',
'bestja_application_moderation',
'bestja_ucw_permissions',
],
'data': [
'data.xml',
],
'application': True,
}
Enable Odoo blog for UCW
|
# -*- coding: utf-8 -*-
{
'name': "Bestja: UCW",
'summary': "Installation configuration for UCW",
'description': "Installation configuration for Uniwersyteckie Centrum Wolontariatu",
'author': "Laboratorium EE",
'website': "http://www.laboratorium.ee",
'version': '0.1',
'category': 'Specific Industry Applications',
'depends': [
'base',
'website_blog',
'bestja_base',
'bestja_volunteer',
'bestja_volunteer_notes',
'bestja_account_deletion',
'bestja_organization',
'bestja_project',
'bestja_offers',
'bestja_offers_moderation',
'bestja_offers_invitations',
'bestja_offers_categorization',
'bestja_files',
'bestja_application_moderation',
'bestja_ucw_permissions',
],
'data': [
'data.xml',
],
'application': True,
}
|
<commit_before># -*- coding: utf-8 -*-
{
'name': "Bestja: UCW",
'summary': "Installation configuration for UCW",
'description': "Installation configuration for Uniwersyteckie Centrum Wolontariatu",
'author': "Laboratorium EE",
'website': "http://www.laboratorium.ee",
'version': '0.1',
'category': 'Specific Industry Applications',
'depends': [
'base',
'bestja_base',
'bestja_volunteer',
'bestja_volunteer_notes',
'bestja_account_deletion',
'bestja_organization',
'bestja_project',
'bestja_offers',
'bestja_offers_moderation',
'bestja_offers_invitations',
'bestja_offers_categorization',
'bestja_files',
'bestja_application_moderation',
'bestja_ucw_permissions',
],
'data': [
'data.xml',
],
'application': True,
}
<commit_msg>Enable Odoo blog for UCW<commit_after>
|
# -*- coding: utf-8 -*-
{
'name': "Bestja: UCW",
'summary': "Installation configuration for UCW",
'description': "Installation configuration for Uniwersyteckie Centrum Wolontariatu",
'author': "Laboratorium EE",
'website': "http://www.laboratorium.ee",
'version': '0.1',
'category': 'Specific Industry Applications',
'depends': [
'base',
'website_blog',
'bestja_base',
'bestja_volunteer',
'bestja_volunteer_notes',
'bestja_account_deletion',
'bestja_organization',
'bestja_project',
'bestja_offers',
'bestja_offers_moderation',
'bestja_offers_invitations',
'bestja_offers_categorization',
'bestja_files',
'bestja_application_moderation',
'bestja_ucw_permissions',
],
'data': [
'data.xml',
],
'application': True,
}
|
# -*- coding: utf-8 -*-
{
'name': "Bestja: UCW",
'summary': "Installation configuration for UCW",
'description': "Installation configuration for Uniwersyteckie Centrum Wolontariatu",
'author': "Laboratorium EE",
'website': "http://www.laboratorium.ee",
'version': '0.1',
'category': 'Specific Industry Applications',
'depends': [
'base',
'bestja_base',
'bestja_volunteer',
'bestja_volunteer_notes',
'bestja_account_deletion',
'bestja_organization',
'bestja_project',
'bestja_offers',
'bestja_offers_moderation',
'bestja_offers_invitations',
'bestja_offers_categorization',
'bestja_files',
'bestja_application_moderation',
'bestja_ucw_permissions',
],
'data': [
'data.xml',
],
'application': True,
}
Enable Odoo blog for UCW# -*- coding: utf-8 -*-
{
'name': "Bestja: UCW",
'summary': "Installation configuration for UCW",
'description': "Installation configuration for Uniwersyteckie Centrum Wolontariatu",
'author': "Laboratorium EE",
'website': "http://www.laboratorium.ee",
'version': '0.1',
'category': 'Specific Industry Applications',
'depends': [
'base',
'website_blog',
'bestja_base',
'bestja_volunteer',
'bestja_volunteer_notes',
'bestja_account_deletion',
'bestja_organization',
'bestja_project',
'bestja_offers',
'bestja_offers_moderation',
'bestja_offers_invitations',
'bestja_offers_categorization',
'bestja_files',
'bestja_application_moderation',
'bestja_ucw_permissions',
],
'data': [
'data.xml',
],
'application': True,
}
|
<commit_before># -*- coding: utf-8 -*-
{
'name': "Bestja: UCW",
'summary': "Installation configuration for UCW",
'description': "Installation configuration for Uniwersyteckie Centrum Wolontariatu",
'author': "Laboratorium EE",
'website': "http://www.laboratorium.ee",
'version': '0.1',
'category': 'Specific Industry Applications',
'depends': [
'base',
'bestja_base',
'bestja_volunteer',
'bestja_volunteer_notes',
'bestja_account_deletion',
'bestja_organization',
'bestja_project',
'bestja_offers',
'bestja_offers_moderation',
'bestja_offers_invitations',
'bestja_offers_categorization',
'bestja_files',
'bestja_application_moderation',
'bestja_ucw_permissions',
],
'data': [
'data.xml',
],
'application': True,
}
<commit_msg>Enable Odoo blog for UCW<commit_after># -*- coding: utf-8 -*-
{
'name': "Bestja: UCW",
'summary': "Installation configuration for UCW",
'description': "Installation configuration for Uniwersyteckie Centrum Wolontariatu",
'author': "Laboratorium EE",
'website': "http://www.laboratorium.ee",
'version': '0.1',
'category': 'Specific Industry Applications',
'depends': [
'base',
'website_blog',
'bestja_base',
'bestja_volunteer',
'bestja_volunteer_notes',
'bestja_account_deletion',
'bestja_organization',
'bestja_project',
'bestja_offers',
'bestja_offers_moderation',
'bestja_offers_invitations',
'bestja_offers_categorization',
'bestja_files',
'bestja_application_moderation',
'bestja_ucw_permissions',
],
'data': [
'data.xml',
],
'application': True,
}
|
1075f88c1a46c6fbacc74adc6a5b9b26c997be37
|
blanc_basic_events/templatetags/events_tags.py
|
blanc_basic_events/templatetags/events_tags.py
|
from django import template
from .. import get_special_events_model
import datetime
register = template.Library()
@register.assignment_tag
def get_upcoming_events(limit=None):
event_list = get_special_events_model().objects.filter(final_date__gte=datetime.date.today(),
published=True)
if limit is None:
return event_list
else:
return event_list[:limit]
|
from django import template
from .. import get_special_events_model
import datetime
register = template.Library()
@register.assignment_tag
def get_upcoming_events(limit=None):
event_list = get_special_events_model().objects.filter(end_date__gte=datetime.date.today(),
published=True)
if limit is None:
return event_list
else:
return event_list[:limit]
|
Fix for get_upcoming_events tag using the wrong filter
|
Fix for get_upcoming_events tag using the wrong filter
|
Python
|
bsd-3-clause
|
blancltd/blanc-basic-events
|
from django import template
from .. import get_special_events_model
import datetime
register = template.Library()
@register.assignment_tag
def get_upcoming_events(limit=None):
event_list = get_special_events_model().objects.filter(final_date__gte=datetime.date.today(),
published=True)
if limit is None:
return event_list
else:
return event_list[:limit]
Fix for get_upcoming_events tag using the wrong filter
|
from django import template
from .. import get_special_events_model
import datetime
register = template.Library()
@register.assignment_tag
def get_upcoming_events(limit=None):
event_list = get_special_events_model().objects.filter(end_date__gte=datetime.date.today(),
published=True)
if limit is None:
return event_list
else:
return event_list[:limit]
|
<commit_before>from django import template
from .. import get_special_events_model
import datetime
register = template.Library()
@register.assignment_tag
def get_upcoming_events(limit=None):
event_list = get_special_events_model().objects.filter(final_date__gte=datetime.date.today(),
published=True)
if limit is None:
return event_list
else:
return event_list[:limit]
<commit_msg>Fix for get_upcoming_events tag using the wrong filter<commit_after>
|
from django import template
from .. import get_special_events_model
import datetime
register = template.Library()
@register.assignment_tag
def get_upcoming_events(limit=None):
event_list = get_special_events_model().objects.filter(end_date__gte=datetime.date.today(),
published=True)
if limit is None:
return event_list
else:
return event_list[:limit]
|
from django import template
from .. import get_special_events_model
import datetime
register = template.Library()
@register.assignment_tag
def get_upcoming_events(limit=None):
event_list = get_special_events_model().objects.filter(final_date__gte=datetime.date.today(),
published=True)
if limit is None:
return event_list
else:
return event_list[:limit]
Fix for get_upcoming_events tag using the wrong filterfrom django import template
from .. import get_special_events_model
import datetime
register = template.Library()
@register.assignment_tag
def get_upcoming_events(limit=None):
event_list = get_special_events_model().objects.filter(end_date__gte=datetime.date.today(),
published=True)
if limit is None:
return event_list
else:
return event_list[:limit]
|
<commit_before>from django import template
from .. import get_special_events_model
import datetime
register = template.Library()
@register.assignment_tag
def get_upcoming_events(limit=None):
event_list = get_special_events_model().objects.filter(final_date__gte=datetime.date.today(),
published=True)
if limit is None:
return event_list
else:
return event_list[:limit]
<commit_msg>Fix for get_upcoming_events tag using the wrong filter<commit_after>from django import template
from .. import get_special_events_model
import datetime
register = template.Library()
@register.assignment_tag
def get_upcoming_events(limit=None):
event_list = get_special_events_model().objects.filter(end_date__gte=datetime.date.today(),
published=True)
if limit is None:
return event_list
else:
return event_list[:limit]
|
343524ddeac29e59d7c214a62a721c2065583503
|
setuptools_extversion/__init__.py
|
setuptools_extversion/__init__.py
|
"""
setuptools_extversion
Allows getting distribution version from external sources (e.g.: shell command,
Python function)
"""
VERSION_PROVIDER_KEY = 'extversion'
def version_calc(dist, attr, value):
"""
Handler for parameter to setup(extversion=value)
"""
if attr == VERSION_PROVIDER_KEY:
extversion = value
dist.metadata.version = extversion(dist)
class command(object):
def __init__(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs
def __call__(self, distribution, metadata, command):
return subprocess.check_output(*self.args, **self.kwargs).strip()
class function(object):
def __init__(self, func, *args, **kwargs):
self.func = func
self.args = args
self.kwargs = kwargs
def __call__(self, *args, **kwargs):
if isinstance(self.func, basestring):
ep = pkg_resources.EntryPoint.parse('x=' + self.func)
self.func = ep.load(False)
args = list(self.args + args)
kwargs = dict(self.kwargs)
kwargs.update(kwargs)
return self.func(*args, **kwargs)
|
"""
setuptools_extversion
Allows getting distribution version from external sources (e.g.: shell command,
Python function)
"""
import subprocess
VERSION_PROVIDER_KEY = 'extversion'
def version_calc(dist, attr, value):
"""
Handler for parameter to setup(extversion=value)
"""
if attr == VERSION_PROVIDER_KEY:
if callable(value):
extversion = value
elif hasattr(value, 'get'):
if value.get('command'):
extversion = command(value.get('command'), shell=True)
else:
raise Exception('Unknown type for %s = %r' % (attr, value))
dist.metadata.version = extversion(dist)
class command(object):
def __init__(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs
def __call__(self, distribution):
return subprocess.check_output(*self.args, **self.kwargs).strip()
class function(object):
def __init__(self, func, *args, **kwargs):
self.func = func
self.args = args
self.kwargs = kwargs
def __call__(self, *args, **kwargs):
if isinstance(self.func, basestring):
ep = pkg_resources.EntryPoint.parse('x=' + self.func)
self.func = ep.load(False)
args = list(self.args + args)
kwargs = dict(self.kwargs)
kwargs.update(kwargs)
return self.func(*args, **kwargs)
|
Add support for providing command string
|
Add support for providing command string
User can provide a command string in a 'command' key -- e.g.:
setup(
...
setup_requires='setuptools_extversion',
extversion={
'command': 'git describe --tags --dirty',
}
...
)
|
Python
|
mit
|
msabramo/python_setuptools_extversion
|
"""
setuptools_extversion
Allows getting distribution version from external sources (e.g.: shell command,
Python function)
"""
VERSION_PROVIDER_KEY = 'extversion'
def version_calc(dist, attr, value):
"""
Handler for parameter to setup(extversion=value)
"""
if attr == VERSION_PROVIDER_KEY:
extversion = value
dist.metadata.version = extversion(dist)
class command(object):
def __init__(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs
def __call__(self, distribution, metadata, command):
return subprocess.check_output(*self.args, **self.kwargs).strip()
class function(object):
def __init__(self, func, *args, **kwargs):
self.func = func
self.args = args
self.kwargs = kwargs
def __call__(self, *args, **kwargs):
if isinstance(self.func, basestring):
ep = pkg_resources.EntryPoint.parse('x=' + self.func)
self.func = ep.load(False)
args = list(self.args + args)
kwargs = dict(self.kwargs)
kwargs.update(kwargs)
return self.func(*args, **kwargs)
Add support for providing command string
User can provide a command string in a 'command' key -- e.g.:
setup(
...
setup_requires='setuptools_extversion',
extversion={
'command': 'git describe --tags --dirty',
}
...
)
|
"""
setuptools_extversion
Allows getting distribution version from external sources (e.g.: shell command,
Python function)
"""
import subprocess
VERSION_PROVIDER_KEY = 'extversion'
def version_calc(dist, attr, value):
"""
Handler for parameter to setup(extversion=value)
"""
if attr == VERSION_PROVIDER_KEY:
if callable(value):
extversion = value
elif hasattr(value, 'get'):
if value.get('command'):
extversion = command(value.get('command'), shell=True)
else:
raise Exception('Unknown type for %s = %r' % (attr, value))
dist.metadata.version = extversion(dist)
class command(object):
def __init__(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs
def __call__(self, distribution):
return subprocess.check_output(*self.args, **self.kwargs).strip()
class function(object):
def __init__(self, func, *args, **kwargs):
self.func = func
self.args = args
self.kwargs = kwargs
def __call__(self, *args, **kwargs):
if isinstance(self.func, basestring):
ep = pkg_resources.EntryPoint.parse('x=' + self.func)
self.func = ep.load(False)
args = list(self.args + args)
kwargs = dict(self.kwargs)
kwargs.update(kwargs)
return self.func(*args, **kwargs)
|
<commit_before>"""
setuptools_extversion
Allows getting distribution version from external sources (e.g.: shell command,
Python function)
"""
VERSION_PROVIDER_KEY = 'extversion'
def version_calc(dist, attr, value):
"""
Handler for parameter to setup(extversion=value)
"""
if attr == VERSION_PROVIDER_KEY:
extversion = value
dist.metadata.version = extversion(dist)
class command(object):
def __init__(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs
def __call__(self, distribution, metadata, command):
return subprocess.check_output(*self.args, **self.kwargs).strip()
class function(object):
def __init__(self, func, *args, **kwargs):
self.func = func
self.args = args
self.kwargs = kwargs
def __call__(self, *args, **kwargs):
if isinstance(self.func, basestring):
ep = pkg_resources.EntryPoint.parse('x=' + self.func)
self.func = ep.load(False)
args = list(self.args + args)
kwargs = dict(self.kwargs)
kwargs.update(kwargs)
return self.func(*args, **kwargs)
<commit_msg>Add support for providing command string
User can provide a command string in a 'command' key -- e.g.:
setup(
...
setup_requires='setuptools_extversion',
extversion={
'command': 'git describe --tags --dirty',
}
...
)<commit_after>
|
"""
setuptools_extversion
Allows getting distribution version from external sources (e.g.: shell command,
Python function)
"""
import subprocess
VERSION_PROVIDER_KEY = 'extversion'
def version_calc(dist, attr, value):
"""
Handler for parameter to setup(extversion=value)
"""
if attr == VERSION_PROVIDER_KEY:
if callable(value):
extversion = value
elif hasattr(value, 'get'):
if value.get('command'):
extversion = command(value.get('command'), shell=True)
else:
raise Exception('Unknown type for %s = %r' % (attr, value))
dist.metadata.version = extversion(dist)
class command(object):
def __init__(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs
def __call__(self, distribution):
return subprocess.check_output(*self.args, **self.kwargs).strip()
class function(object):
def __init__(self, func, *args, **kwargs):
self.func = func
self.args = args
self.kwargs = kwargs
def __call__(self, *args, **kwargs):
if isinstance(self.func, basestring):
ep = pkg_resources.EntryPoint.parse('x=' + self.func)
self.func = ep.load(False)
args = list(self.args + args)
kwargs = dict(self.kwargs)
kwargs.update(kwargs)
return self.func(*args, **kwargs)
|
"""
setuptools_extversion
Allows getting distribution version from external sources (e.g.: shell command,
Python function)
"""
VERSION_PROVIDER_KEY = 'extversion'
def version_calc(dist, attr, value):
"""
Handler for parameter to setup(extversion=value)
"""
if attr == VERSION_PROVIDER_KEY:
extversion = value
dist.metadata.version = extversion(dist)
class command(object):
def __init__(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs
def __call__(self, distribution, metadata, command):
return subprocess.check_output(*self.args, **self.kwargs).strip()
class function(object):
def __init__(self, func, *args, **kwargs):
self.func = func
self.args = args
self.kwargs = kwargs
def __call__(self, *args, **kwargs):
if isinstance(self.func, basestring):
ep = pkg_resources.EntryPoint.parse('x=' + self.func)
self.func = ep.load(False)
args = list(self.args + args)
kwargs = dict(self.kwargs)
kwargs.update(kwargs)
return self.func(*args, **kwargs)
Add support for providing command string
User can provide a command string in a 'command' key -- e.g.:
setup(
...
setup_requires='setuptools_extversion',
extversion={
'command': 'git describe --tags --dirty',
}
...
)"""
setuptools_extversion
Allows getting distribution version from external sources (e.g.: shell command,
Python function)
"""
import subprocess
VERSION_PROVIDER_KEY = 'extversion'
def version_calc(dist, attr, value):
"""
Handler for parameter to setup(extversion=value)
"""
if attr == VERSION_PROVIDER_KEY:
if callable(value):
extversion = value
elif hasattr(value, 'get'):
if value.get('command'):
extversion = command(value.get('command'), shell=True)
else:
raise Exception('Unknown type for %s = %r' % (attr, value))
dist.metadata.version = extversion(dist)
class command(object):
def __init__(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs
def __call__(self, distribution):
return subprocess.check_output(*self.args, **self.kwargs).strip()
class function(object):
def __init__(self, func, *args, **kwargs):
self.func = func
self.args = args
self.kwargs = kwargs
def __call__(self, *args, **kwargs):
if isinstance(self.func, basestring):
ep = pkg_resources.EntryPoint.parse('x=' + self.func)
self.func = ep.load(False)
args = list(self.args + args)
kwargs = dict(self.kwargs)
kwargs.update(kwargs)
return self.func(*args, **kwargs)
|
<commit_before>"""
setuptools_extversion
Allows getting distribution version from external sources (e.g.: shell command,
Python function)
"""
VERSION_PROVIDER_KEY = 'extversion'
def version_calc(dist, attr, value):
"""
Handler for parameter to setup(extversion=value)
"""
if attr == VERSION_PROVIDER_KEY:
extversion = value
dist.metadata.version = extversion(dist)
class command(object):
def __init__(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs
def __call__(self, distribution, metadata, command):
return subprocess.check_output(*self.args, **self.kwargs).strip()
class function(object):
def __init__(self, func, *args, **kwargs):
self.func = func
self.args = args
self.kwargs = kwargs
def __call__(self, *args, **kwargs):
if isinstance(self.func, basestring):
ep = pkg_resources.EntryPoint.parse('x=' + self.func)
self.func = ep.load(False)
args = list(self.args + args)
kwargs = dict(self.kwargs)
kwargs.update(kwargs)
return self.func(*args, **kwargs)
<commit_msg>Add support for providing command string
User can provide a command string in a 'command' key -- e.g.:
setup(
...
setup_requires='setuptools_extversion',
extversion={
'command': 'git describe --tags --dirty',
}
...
)<commit_after>"""
setuptools_extversion
Allows getting distribution version from external sources (e.g.: shell command,
Python function)
"""
import subprocess
VERSION_PROVIDER_KEY = 'extversion'
def version_calc(dist, attr, value):
"""
Handler for parameter to setup(extversion=value)
"""
if attr == VERSION_PROVIDER_KEY:
if callable(value):
extversion = value
elif hasattr(value, 'get'):
if value.get('command'):
extversion = command(value.get('command'), shell=True)
else:
raise Exception('Unknown type for %s = %r' % (attr, value))
dist.metadata.version = extversion(dist)
class command(object):
def __init__(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs
def __call__(self, distribution):
return subprocess.check_output(*self.args, **self.kwargs).strip()
class function(object):
def __init__(self, func, *args, **kwargs):
self.func = func
self.args = args
self.kwargs = kwargs
def __call__(self, *args, **kwargs):
if isinstance(self.func, basestring):
ep = pkg_resources.EntryPoint.parse('x=' + self.func)
self.func = ep.load(False)
args = list(self.args + args)
kwargs = dict(self.kwargs)
kwargs.update(kwargs)
return self.func(*args, **kwargs)
|
e61e633e122953774ee4246ad61b23d9b7d264f3
|
semillas_backend/users/serializers.py
|
semillas_backend/users/serializers.py
|
from rest_framework import serializers
from .models import User
class UserSerializer(serializers.ModelSerializer):
""" Usage:
from rest_framework.renderers import JSONRenderer
from semillas_backend.users.serializers import UserSerializer
JSONRenderer().render(UserSerializer(user_instance).data)
"""
class Meta:
model = User
fields = ('id', 'name', 'picture')
|
from rest_framework import serializers
from .models import User
class UserSerializer(serializers.ModelSerializer):
""" Usage:
from rest_framework.renderers import JSONRenderer
from semillas_backend.users.serializers import UserSerializer
JSONRenderer().render(UserSerializer(user_instance).data)
"""
class Meta:
model = User
fields = ('id', 'name', 'picture', 'location', 'email', 'username', 'last_login')
|
Add location, email, username and last_login to user serializer
|
Add location, email, username and last_login to user serializer
|
Python
|
mit
|
Semillas/semillas_backend,Semillas/semillas_backend,Semillas/semillas_platform,Semillas/semillas_backend,Semillas/semillas_platform,Semillas/semillas_platform,Semillas/semillas_platform,Semillas/semillas_backend
|
from rest_framework import serializers
from .models import User
class UserSerializer(serializers.ModelSerializer):
""" Usage:
from rest_framework.renderers import JSONRenderer
from semillas_backend.users.serializers import UserSerializer
JSONRenderer().render(UserSerializer(user_instance).data)
"""
class Meta:
model = User
fields = ('id', 'name', 'picture')
Add location, email, username and last_login to user serializer
|
from rest_framework import serializers
from .models import User
class UserSerializer(serializers.ModelSerializer):
""" Usage:
from rest_framework.renderers import JSONRenderer
from semillas_backend.users.serializers import UserSerializer
JSONRenderer().render(UserSerializer(user_instance).data)
"""
class Meta:
model = User
fields = ('id', 'name', 'picture', 'location', 'email', 'username', 'last_login')
|
<commit_before>from rest_framework import serializers
from .models import User
class UserSerializer(serializers.ModelSerializer):
""" Usage:
from rest_framework.renderers import JSONRenderer
from semillas_backend.users.serializers import UserSerializer
JSONRenderer().render(UserSerializer(user_instance).data)
"""
class Meta:
model = User
fields = ('id', 'name', 'picture')
<commit_msg>Add location, email, username and last_login to user serializer<commit_after>
|
from rest_framework import serializers
from .models import User
class UserSerializer(serializers.ModelSerializer):
""" Usage:
from rest_framework.renderers import JSONRenderer
from semillas_backend.users.serializers import UserSerializer
JSONRenderer().render(UserSerializer(user_instance).data)
"""
class Meta:
model = User
fields = ('id', 'name', 'picture', 'location', 'email', 'username', 'last_login')
|
from rest_framework import serializers
from .models import User
class UserSerializer(serializers.ModelSerializer):
""" Usage:
from rest_framework.renderers import JSONRenderer
from semillas_backend.users.serializers import UserSerializer
JSONRenderer().render(UserSerializer(user_instance).data)
"""
class Meta:
model = User
fields = ('id', 'name', 'picture')
Add location, email, username and last_login to user serializerfrom rest_framework import serializers
from .models import User
class UserSerializer(serializers.ModelSerializer):
""" Usage:
from rest_framework.renderers import JSONRenderer
from semillas_backend.users.serializers import UserSerializer
JSONRenderer().render(UserSerializer(user_instance).data)
"""
class Meta:
model = User
fields = ('id', 'name', 'picture', 'location', 'email', 'username', 'last_login')
|
<commit_before>from rest_framework import serializers
from .models import User
class UserSerializer(serializers.ModelSerializer):
""" Usage:
from rest_framework.renderers import JSONRenderer
from semillas_backend.users.serializers import UserSerializer
JSONRenderer().render(UserSerializer(user_instance).data)
"""
class Meta:
model = User
fields = ('id', 'name', 'picture')
<commit_msg>Add location, email, username and last_login to user serializer<commit_after>from rest_framework import serializers
from .models import User
class UserSerializer(serializers.ModelSerializer):
""" Usage:
from rest_framework.renderers import JSONRenderer
from semillas_backend.users.serializers import UserSerializer
JSONRenderer().render(UserSerializer(user_instance).data)
"""
class Meta:
model = User
fields = ('id', 'name', 'picture', 'location', 'email', 'username', 'last_login')
|
5d652eacf793dc3aa1873279708f88e16e1c0dfd
|
eloqua/endpoints_v2.py
|
eloqua/endpoints_v2.py
|
"""
API MAPPING FOR Eloqua API V2
"""
mapping_table = {
'content_type': 'application/json',
'path_prefix': '/API/REST/2.0',
# Campaigns
'get_campaign': {
'method': 'GET',
'path': '/assets/campaign/{{campaign_id}}',
'valid_params': ['depth']
},
'list_campaigns': {
'method': 'GET',
'path': '/assets/campaigns',
'valid_params': ['depth','count','page','search','sort','dir','orderBy','lastUpdatedAt']
},
'create_campaign': {
'method': 'POST',
'path': '/assets/campaign',
'status': 201
},
# Campaign folders - UNDOCUMENTED
'get_campaign_folder': {
'method': 'GET',
'path': '/assets/campaign/folder/{{campaign_folder_id}}',
'valid_params': ['depth']
},
'list_campaign_folders': {
'method': 'GET',
'path': '/assets/campaign/folders',
'valid_params': ['depth','count','page','search','sort','dir','orderBy','lastUpdatedAt']
},
}
|
"""
API MAPPING FOR Eloqua API V2
"""
mapping_table = {
'content_type': 'application/json',
'path_prefix': '/API/REST/2.0',
# Campaigns
'get_campaign': {
'method': 'GET',
'path': '/assets/campaign/{{campaign_id}}',
'valid_params': ['depth']
},
'list_campaigns': {
'method': 'GET',
'path': '/assets/campaigns',
'valid_params': ['depth','count','page','search','sort','dir','orderBy','lastUpdatedAt']
},
'create_campaign': {
'method': 'POST',
'path': '/assets/campaign',
'status': 201
},
'activate_campaign': {
'method': 'POST',
'path': '/assets/campaign/active/{{campaign_id}}',
'valid_params': ['activateNow','scheduledFor','runAsUserId']
},
# Campaign folders - UNDOCUMENTED
'get_campaign_folder': {
'method': 'GET',
'path': '/assets/campaign/folder/{{campaign_folder_id}}',
'valid_params': ['depth']
},
'list_campaign_folders': {
'method': 'GET',
'path': '/assets/campaign/folders',
'valid_params': ['depth','count','page','search','sort','dir','orderBy','lastUpdatedAt']
},
}
|
Add operation to activate campaign.
|
Add operation to activate campaign.
|
Python
|
mit
|
alexcchan/eloqua
|
"""
API MAPPING FOR Eloqua API V2
"""
mapping_table = {
'content_type': 'application/json',
'path_prefix': '/API/REST/2.0',
# Campaigns
'get_campaign': {
'method': 'GET',
'path': '/assets/campaign/{{campaign_id}}',
'valid_params': ['depth']
},
'list_campaigns': {
'method': 'GET',
'path': '/assets/campaigns',
'valid_params': ['depth','count','page','search','sort','dir','orderBy','lastUpdatedAt']
},
'create_campaign': {
'method': 'POST',
'path': '/assets/campaign',
'status': 201
},
# Campaign folders - UNDOCUMENTED
'get_campaign_folder': {
'method': 'GET',
'path': '/assets/campaign/folder/{{campaign_folder_id}}',
'valid_params': ['depth']
},
'list_campaign_folders': {
'method': 'GET',
'path': '/assets/campaign/folders',
'valid_params': ['depth','count','page','search','sort','dir','orderBy','lastUpdatedAt']
},
}
Add operation to activate campaign.
|
"""
API MAPPING FOR Eloqua API V2
"""
mapping_table = {
'content_type': 'application/json',
'path_prefix': '/API/REST/2.0',
# Campaigns
'get_campaign': {
'method': 'GET',
'path': '/assets/campaign/{{campaign_id}}',
'valid_params': ['depth']
},
'list_campaigns': {
'method': 'GET',
'path': '/assets/campaigns',
'valid_params': ['depth','count','page','search','sort','dir','orderBy','lastUpdatedAt']
},
'create_campaign': {
'method': 'POST',
'path': '/assets/campaign',
'status': 201
},
'activate_campaign': {
'method': 'POST',
'path': '/assets/campaign/active/{{campaign_id}}',
'valid_params': ['activateNow','scheduledFor','runAsUserId']
},
# Campaign folders - UNDOCUMENTED
'get_campaign_folder': {
'method': 'GET',
'path': '/assets/campaign/folder/{{campaign_folder_id}}',
'valid_params': ['depth']
},
'list_campaign_folders': {
'method': 'GET',
'path': '/assets/campaign/folders',
'valid_params': ['depth','count','page','search','sort','dir','orderBy','lastUpdatedAt']
},
}
|
<commit_before>"""
API MAPPING FOR Eloqua API V2
"""
mapping_table = {
'content_type': 'application/json',
'path_prefix': '/API/REST/2.0',
# Campaigns
'get_campaign': {
'method': 'GET',
'path': '/assets/campaign/{{campaign_id}}',
'valid_params': ['depth']
},
'list_campaigns': {
'method': 'GET',
'path': '/assets/campaigns',
'valid_params': ['depth','count','page','search','sort','dir','orderBy','lastUpdatedAt']
},
'create_campaign': {
'method': 'POST',
'path': '/assets/campaign',
'status': 201
},
# Campaign folders - UNDOCUMENTED
'get_campaign_folder': {
'method': 'GET',
'path': '/assets/campaign/folder/{{campaign_folder_id}}',
'valid_params': ['depth']
},
'list_campaign_folders': {
'method': 'GET',
'path': '/assets/campaign/folders',
'valid_params': ['depth','count','page','search','sort','dir','orderBy','lastUpdatedAt']
},
}
<commit_msg>Add operation to activate campaign.<commit_after>
|
"""
API MAPPING FOR Eloqua API V2
"""
mapping_table = {
'content_type': 'application/json',
'path_prefix': '/API/REST/2.0',
# Campaigns
'get_campaign': {
'method': 'GET',
'path': '/assets/campaign/{{campaign_id}}',
'valid_params': ['depth']
},
'list_campaigns': {
'method': 'GET',
'path': '/assets/campaigns',
'valid_params': ['depth','count','page','search','sort','dir','orderBy','lastUpdatedAt']
},
'create_campaign': {
'method': 'POST',
'path': '/assets/campaign',
'status': 201
},
'activate_campaign': {
'method': 'POST',
'path': '/assets/campaign/active/{{campaign_id}}',
'valid_params': ['activateNow','scheduledFor','runAsUserId']
},
# Campaign folders - UNDOCUMENTED
'get_campaign_folder': {
'method': 'GET',
'path': '/assets/campaign/folder/{{campaign_folder_id}}',
'valid_params': ['depth']
},
'list_campaign_folders': {
'method': 'GET',
'path': '/assets/campaign/folders',
'valid_params': ['depth','count','page','search','sort','dir','orderBy','lastUpdatedAt']
},
}
|
"""
API MAPPING FOR Eloqua API V2
"""
mapping_table = {
'content_type': 'application/json',
'path_prefix': '/API/REST/2.0',
# Campaigns
'get_campaign': {
'method': 'GET',
'path': '/assets/campaign/{{campaign_id}}',
'valid_params': ['depth']
},
'list_campaigns': {
'method': 'GET',
'path': '/assets/campaigns',
'valid_params': ['depth','count','page','search','sort','dir','orderBy','lastUpdatedAt']
},
'create_campaign': {
'method': 'POST',
'path': '/assets/campaign',
'status': 201
},
# Campaign folders - UNDOCUMENTED
'get_campaign_folder': {
'method': 'GET',
'path': '/assets/campaign/folder/{{campaign_folder_id}}',
'valid_params': ['depth']
},
'list_campaign_folders': {
'method': 'GET',
'path': '/assets/campaign/folders',
'valid_params': ['depth','count','page','search','sort','dir','orderBy','lastUpdatedAt']
},
}
Add operation to activate campaign."""
API MAPPING FOR Eloqua API V2
"""
mapping_table = {
'content_type': 'application/json',
'path_prefix': '/API/REST/2.0',
# Campaigns
'get_campaign': {
'method': 'GET',
'path': '/assets/campaign/{{campaign_id}}',
'valid_params': ['depth']
},
'list_campaigns': {
'method': 'GET',
'path': '/assets/campaigns',
'valid_params': ['depth','count','page','search','sort','dir','orderBy','lastUpdatedAt']
},
'create_campaign': {
'method': 'POST',
'path': '/assets/campaign',
'status': 201
},
'activate_campaign': {
'method': 'POST',
'path': '/assets/campaign/active/{{campaign_id}}',
'valid_params': ['activateNow','scheduledFor','runAsUserId']
},
# Campaign folders - UNDOCUMENTED
'get_campaign_folder': {
'method': 'GET',
'path': '/assets/campaign/folder/{{campaign_folder_id}}',
'valid_params': ['depth']
},
'list_campaign_folders': {
'method': 'GET',
'path': '/assets/campaign/folders',
'valid_params': ['depth','count','page','search','sort','dir','orderBy','lastUpdatedAt']
},
}
|
<commit_before>"""
API MAPPING FOR Eloqua API V2
"""
mapping_table = {
'content_type': 'application/json',
'path_prefix': '/API/REST/2.0',
# Campaigns
'get_campaign': {
'method': 'GET',
'path': '/assets/campaign/{{campaign_id}}',
'valid_params': ['depth']
},
'list_campaigns': {
'method': 'GET',
'path': '/assets/campaigns',
'valid_params': ['depth','count','page','search','sort','dir','orderBy','lastUpdatedAt']
},
'create_campaign': {
'method': 'POST',
'path': '/assets/campaign',
'status': 201
},
# Campaign folders - UNDOCUMENTED
'get_campaign_folder': {
'method': 'GET',
'path': '/assets/campaign/folder/{{campaign_folder_id}}',
'valid_params': ['depth']
},
'list_campaign_folders': {
'method': 'GET',
'path': '/assets/campaign/folders',
'valid_params': ['depth','count','page','search','sort','dir','orderBy','lastUpdatedAt']
},
}
<commit_msg>Add operation to activate campaign.<commit_after>"""
API MAPPING FOR Eloqua API V2
"""
mapping_table = {
'content_type': 'application/json',
'path_prefix': '/API/REST/2.0',
# Campaigns
'get_campaign': {
'method': 'GET',
'path': '/assets/campaign/{{campaign_id}}',
'valid_params': ['depth']
},
'list_campaigns': {
'method': 'GET',
'path': '/assets/campaigns',
'valid_params': ['depth','count','page','search','sort','dir','orderBy','lastUpdatedAt']
},
'create_campaign': {
'method': 'POST',
'path': '/assets/campaign',
'status': 201
},
'activate_campaign': {
'method': 'POST',
'path': '/assets/campaign/active/{{campaign_id}}',
'valid_params': ['activateNow','scheduledFor','runAsUserId']
},
# Campaign folders - UNDOCUMENTED
'get_campaign_folder': {
'method': 'GET',
'path': '/assets/campaign/folder/{{campaign_folder_id}}',
'valid_params': ['depth']
},
'list_campaign_folders': {
'method': 'GET',
'path': '/assets/campaign/folders',
'valid_params': ['depth','count','page','search','sort','dir','orderBy','lastUpdatedAt']
},
}
|
65d233f0137413fa72d7f991e3b308739f8ecf78
|
setup_unix.py
|
setup_unix.py
|
#!/usr/bin/python2.7
from distutils.core import setup, Extension
from sys import platform
from setup_config import NASSL_SETUP, NASSL_EXT_SETUP
from buildAll_config import OPENSSL_DIR, ZLIB_DIR
from buildAll_unix import OPENSSL_INSTALL_DIR
extra_compile_args = ['-Wall', '-Wno-deprecated-declarations']
if platform == 'darwin': # Workaround for Clang 3.4
# add as the element of an array rather than a string, py 2.7.5
extra_compile_args += ['-Wno-error=unused-command-line-argument-hard-error-in-future']
# Add arguments specific to Unix builds
unix_ext_args = NASSL_EXT_SETUP.copy()
unix_ext_args.update({
'include_dirs' : [OPENSSL_INSTALL_DIR + '/include'],
'extra_compile_args' : extra_compile_args,
'library_dirs' : [OPENSSL_DIR, ZLIB_DIR],
'libraries' : ['ssl', 'z', 'crypto']})
unix_setup = NASSL_SETUP.copy()
unix_setup.update({
'ext_modules' : [Extension(**unix_ext_args)] })
setup(**unix_setup)
|
#!/usr/bin/python2.7
from distutils.core import setup, Extension
from sys import platform
from setup_config import NASSL_SETUP, NASSL_EXT_SETUP
from buildAll_config import OPENSSL_DIR, ZLIB_DIR
from buildAll_unix import OPENSSL_INSTALL_DIR
extra_compile_args = ['-Wall', '-Wno-deprecated-declarations']
if platform == 'darwin': # Workaround for Clang 3.4
# add as the element of an array rather than a string, py 2.7.5
extra_compile_args += ['-Wno-error=unused-command-line-argument-hard-error-in-future']
# Add arguments specific to Unix builds
unix_ext_args = NASSL_EXT_SETUP.copy()
unix_ext_args.update({
'include_dirs' : [OPENSSL_INSTALL_DIR + '/include'],
'extra_compile_args' : extra_compile_args,
'library_dirs' : [OPENSSL_DIR, ZLIB_DIR],
'libraries' : ['ssl', 'crypto']})
unix_setup = NASSL_SETUP.copy()
unix_setup.update({
'ext_modules' : [Extension(**unix_ext_args)] })
setup(**unix_setup)
|
Remove un-needed dynamic dependency to zlib
|
Remove un-needed dynamic dependency to zlib
Discovered in issue #25
|
Python
|
agpl-3.0
|
nabla-c0d3/nassl,nabla-c0d3/nassl,nabla-c0d3/nassl
|
#!/usr/bin/python2.7
from distutils.core import setup, Extension
from sys import platform
from setup_config import NASSL_SETUP, NASSL_EXT_SETUP
from buildAll_config import OPENSSL_DIR, ZLIB_DIR
from buildAll_unix import OPENSSL_INSTALL_DIR
extra_compile_args = ['-Wall', '-Wno-deprecated-declarations']
if platform == 'darwin': # Workaround for Clang 3.4
# add as the element of an array rather than a string, py 2.7.5
extra_compile_args += ['-Wno-error=unused-command-line-argument-hard-error-in-future']
# Add arguments specific to Unix builds
unix_ext_args = NASSL_EXT_SETUP.copy()
unix_ext_args.update({
'include_dirs' : [OPENSSL_INSTALL_DIR + '/include'],
'extra_compile_args' : extra_compile_args,
'library_dirs' : [OPENSSL_DIR, ZLIB_DIR],
'libraries' : ['ssl', 'z', 'crypto']})
unix_setup = NASSL_SETUP.copy()
unix_setup.update({
'ext_modules' : [Extension(**unix_ext_args)] })
setup(**unix_setup)
Remove un-needed dynamic dependency to zlib
Discovered in issue #25
|
#!/usr/bin/python2.7
from distutils.core import setup, Extension
from sys import platform
from setup_config import NASSL_SETUP, NASSL_EXT_SETUP
from buildAll_config import OPENSSL_DIR, ZLIB_DIR
from buildAll_unix import OPENSSL_INSTALL_DIR
extra_compile_args = ['-Wall', '-Wno-deprecated-declarations']
if platform == 'darwin': # Workaround for Clang 3.4
# add as the element of an array rather than a string, py 2.7.5
extra_compile_args += ['-Wno-error=unused-command-line-argument-hard-error-in-future']
# Add arguments specific to Unix builds
unix_ext_args = NASSL_EXT_SETUP.copy()
unix_ext_args.update({
'include_dirs' : [OPENSSL_INSTALL_DIR + '/include'],
'extra_compile_args' : extra_compile_args,
'library_dirs' : [OPENSSL_DIR, ZLIB_DIR],
'libraries' : ['ssl', 'crypto']})
unix_setup = NASSL_SETUP.copy()
unix_setup.update({
'ext_modules' : [Extension(**unix_ext_args)] })
setup(**unix_setup)
|
<commit_before>#!/usr/bin/python2.7
from distutils.core import setup, Extension
from sys import platform
from setup_config import NASSL_SETUP, NASSL_EXT_SETUP
from buildAll_config import OPENSSL_DIR, ZLIB_DIR
from buildAll_unix import OPENSSL_INSTALL_DIR
extra_compile_args = ['-Wall', '-Wno-deprecated-declarations']
if platform == 'darwin': # Workaround for Clang 3.4
# add as the element of an array rather than a string, py 2.7.5
extra_compile_args += ['-Wno-error=unused-command-line-argument-hard-error-in-future']
# Add arguments specific to Unix builds
unix_ext_args = NASSL_EXT_SETUP.copy()
unix_ext_args.update({
'include_dirs' : [OPENSSL_INSTALL_DIR + '/include'],
'extra_compile_args' : extra_compile_args,
'library_dirs' : [OPENSSL_DIR, ZLIB_DIR],
'libraries' : ['ssl', 'z', 'crypto']})
unix_setup = NASSL_SETUP.copy()
unix_setup.update({
'ext_modules' : [Extension(**unix_ext_args)] })
setup(**unix_setup)
<commit_msg>Remove un-needed dynamic dependency to zlib
Discovered in issue #25<commit_after>
|
#!/usr/bin/python2.7
from distutils.core import setup, Extension
from sys import platform
from setup_config import NASSL_SETUP, NASSL_EXT_SETUP
from buildAll_config import OPENSSL_DIR, ZLIB_DIR
from buildAll_unix import OPENSSL_INSTALL_DIR
extra_compile_args = ['-Wall', '-Wno-deprecated-declarations']
if platform == 'darwin': # Workaround for Clang 3.4
# add as the element of an array rather than a string, py 2.7.5
extra_compile_args += ['-Wno-error=unused-command-line-argument-hard-error-in-future']
# Add arguments specific to Unix builds
unix_ext_args = NASSL_EXT_SETUP.copy()
unix_ext_args.update({
'include_dirs' : [OPENSSL_INSTALL_DIR + '/include'],
'extra_compile_args' : extra_compile_args,
'library_dirs' : [OPENSSL_DIR, ZLIB_DIR],
'libraries' : ['ssl', 'crypto']})
unix_setup = NASSL_SETUP.copy()
unix_setup.update({
'ext_modules' : [Extension(**unix_ext_args)] })
setup(**unix_setup)
|
#!/usr/bin/python2.7
from distutils.core import setup, Extension
from sys import platform
from setup_config import NASSL_SETUP, NASSL_EXT_SETUP
from buildAll_config import OPENSSL_DIR, ZLIB_DIR
from buildAll_unix import OPENSSL_INSTALL_DIR
extra_compile_args = ['-Wall', '-Wno-deprecated-declarations']
if platform == 'darwin': # Workaround for Clang 3.4
# add as the element of an array rather than a string, py 2.7.5
extra_compile_args += ['-Wno-error=unused-command-line-argument-hard-error-in-future']
# Add arguments specific to Unix builds
unix_ext_args = NASSL_EXT_SETUP.copy()
unix_ext_args.update({
'include_dirs' : [OPENSSL_INSTALL_DIR + '/include'],
'extra_compile_args' : extra_compile_args,
'library_dirs' : [OPENSSL_DIR, ZLIB_DIR],
'libraries' : ['ssl', 'z', 'crypto']})
unix_setup = NASSL_SETUP.copy()
unix_setup.update({
'ext_modules' : [Extension(**unix_ext_args)] })
setup(**unix_setup)
Remove un-needed dynamic dependency to zlib
Discovered in issue #25#!/usr/bin/python2.7
from distutils.core import setup, Extension
from sys import platform
from setup_config import NASSL_SETUP, NASSL_EXT_SETUP
from buildAll_config import OPENSSL_DIR, ZLIB_DIR
from buildAll_unix import OPENSSL_INSTALL_DIR
extra_compile_args = ['-Wall', '-Wno-deprecated-declarations']
if platform == 'darwin': # Workaround for Clang 3.4
# add as the element of an array rather than a string, py 2.7.5
extra_compile_args += ['-Wno-error=unused-command-line-argument-hard-error-in-future']
# Add arguments specific to Unix builds
unix_ext_args = NASSL_EXT_SETUP.copy()
unix_ext_args.update({
'include_dirs' : [OPENSSL_INSTALL_DIR + '/include'],
'extra_compile_args' : extra_compile_args,
'library_dirs' : [OPENSSL_DIR, ZLIB_DIR],
'libraries' : ['ssl', 'crypto']})
unix_setup = NASSL_SETUP.copy()
unix_setup.update({
'ext_modules' : [Extension(**unix_ext_args)] })
setup(**unix_setup)
|
<commit_before>#!/usr/bin/python2.7
from distutils.core import setup, Extension
from sys import platform
from setup_config import NASSL_SETUP, NASSL_EXT_SETUP
from buildAll_config import OPENSSL_DIR, ZLIB_DIR
from buildAll_unix import OPENSSL_INSTALL_DIR
extra_compile_args = ['-Wall', '-Wno-deprecated-declarations']
if platform == 'darwin': # Workaround for Clang 3.4
# add as the element of an array rather than a string, py 2.7.5
extra_compile_args += ['-Wno-error=unused-command-line-argument-hard-error-in-future']
# Add arguments specific to Unix builds
unix_ext_args = NASSL_EXT_SETUP.copy()
unix_ext_args.update({
'include_dirs' : [OPENSSL_INSTALL_DIR + '/include'],
'extra_compile_args' : extra_compile_args,
'library_dirs' : [OPENSSL_DIR, ZLIB_DIR],
'libraries' : ['ssl', 'z', 'crypto']})
unix_setup = NASSL_SETUP.copy()
unix_setup.update({
'ext_modules' : [Extension(**unix_ext_args)] })
setup(**unix_setup)
<commit_msg>Remove un-needed dynamic dependency to zlib
Discovered in issue #25<commit_after>#!/usr/bin/python2.7
from distutils.core import setup, Extension
from sys import platform
from setup_config import NASSL_SETUP, NASSL_EXT_SETUP
from buildAll_config import OPENSSL_DIR, ZLIB_DIR
from buildAll_unix import OPENSSL_INSTALL_DIR
extra_compile_args = ['-Wall', '-Wno-deprecated-declarations']
if platform == 'darwin': # Workaround for Clang 3.4
# add as the element of an array rather than a string, py 2.7.5
extra_compile_args += ['-Wno-error=unused-command-line-argument-hard-error-in-future']
# Add arguments specific to Unix builds
unix_ext_args = NASSL_EXT_SETUP.copy()
unix_ext_args.update({
'include_dirs' : [OPENSSL_INSTALL_DIR + '/include'],
'extra_compile_args' : extra_compile_args,
'library_dirs' : [OPENSSL_DIR, ZLIB_DIR],
'libraries' : ['ssl', 'crypto']})
unix_setup = NASSL_SETUP.copy()
unix_setup.update({
'ext_modules' : [Extension(**unix_ext_args)] })
setup(**unix_setup)
|
3ad750a875fb436f163c6ecb893430f6db2bed94
|
odeintw/__init__.py
|
odeintw/__init__.py
|
# Copyright (c) 2014, Warren Weckesser
# All rights reserved.
# See the LICENSE file for license information.
from numpy.testing import Tester as _Tester
from ._odeintw import odeintw
__version__ = "0.1.1"
test = _Tester().test
|
# Copyright (c) 2014, Warren Weckesser
# All rights reserved.
# See the LICENSE file for license information.
from numpy.testing import Tester as _Tester
from ._odeintw import odeintw
__version__ = "0.1.2.dev1"
test = _Tester().test
|
Update master branch version to 0.1.2.dev1
|
REL: Update master branch version to 0.1.2.dev1
|
Python
|
bsd-3-clause
|
WarrenWeckesser/odeintw
|
# Copyright (c) 2014, Warren Weckesser
# All rights reserved.
# See the LICENSE file for license information.
from numpy.testing import Tester as _Tester
from ._odeintw import odeintw
__version__ = "0.1.1"
test = _Tester().test
REL: Update master branch version to 0.1.2.dev1
|
# Copyright (c) 2014, Warren Weckesser
# All rights reserved.
# See the LICENSE file for license information.
from numpy.testing import Tester as _Tester
from ._odeintw import odeintw
__version__ = "0.1.2.dev1"
test = _Tester().test
|
<commit_before># Copyright (c) 2014, Warren Weckesser
# All rights reserved.
# See the LICENSE file for license information.
from numpy.testing import Tester as _Tester
from ._odeintw import odeintw
__version__ = "0.1.1"
test = _Tester().test
<commit_msg>REL: Update master branch version to 0.1.2.dev1<commit_after>
|
# Copyright (c) 2014, Warren Weckesser
# All rights reserved.
# See the LICENSE file for license information.
from numpy.testing import Tester as _Tester
from ._odeintw import odeintw
__version__ = "0.1.2.dev1"
test = _Tester().test
|
# Copyright (c) 2014, Warren Weckesser
# All rights reserved.
# See the LICENSE file for license information.
from numpy.testing import Tester as _Tester
from ._odeintw import odeintw
__version__ = "0.1.1"
test = _Tester().test
REL: Update master branch version to 0.1.2.dev1# Copyright (c) 2014, Warren Weckesser
# All rights reserved.
# See the LICENSE file for license information.
from numpy.testing import Tester as _Tester
from ._odeintw import odeintw
__version__ = "0.1.2.dev1"
test = _Tester().test
|
<commit_before># Copyright (c) 2014, Warren Weckesser
# All rights reserved.
# See the LICENSE file for license information.
from numpy.testing import Tester as _Tester
from ._odeintw import odeintw
__version__ = "0.1.1"
test = _Tester().test
<commit_msg>REL: Update master branch version to 0.1.2.dev1<commit_after># Copyright (c) 2014, Warren Weckesser
# All rights reserved.
# See the LICENSE file for license information.
from numpy.testing import Tester as _Tester
from ._odeintw import odeintw
__version__ = "0.1.2.dev1"
test = _Tester().test
|
de8b0680401c04ff768355c86bd1beb643501491
|
indra/tools/plot_formatting.py
|
indra/tools/plot_formatting.py
|
from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import matplotlib
fontsize=7
def set_fig_params():
matplotlib.rcParams['font.sans-serif'] = 'Arial'
matplotlib.rcParams['text.usetex'] = True
matplotlib.rcParams['text.latex.preamble'] = [
r'\usepackage{helvet}',
r'\usepackage{sansmath}',
r'\sansmath',
r'\usepackage{underscore}',]
def format_axis(ax, label_padding=2, tick_padding=0, yticks_position='left'):
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position(yticks_position)
ax.yaxis.set_tick_params(which='both', direction='out', labelsize=fontsize,
pad=tick_padding, length=2, width=0.5)
ax.xaxis.set_tick_params(which='both', direction='out', labelsize=fontsize,
pad=tick_padding, length=2, width=0.5)
ax.xaxis.labelpad = label_padding
ax.yaxis.labelpad = label_padding
ax.xaxis.label.set_size(fontsize)
ax.yaxis.label.set_size(fontsize)
|
from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import matplotlib
fontsize=7
def set_fig_params():
matplotlib.rcParams['font.sans-serif'] = 'Arial'
matplotlib.rcParams['text.usetex'] = True
matplotlib.rcParams['text.latex.preamble'] = [
'\\usepackage{helvet}',
'\\usepackage{sansmath}',
'\\sansmath',
'\\usepackage{underscore}',]
def format_axis(ax, label_padding=2, tick_padding=0, yticks_position='left'):
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position(yticks_position)
ax.yaxis.set_tick_params(which='both', direction='out', labelsize=fontsize,
pad=tick_padding, length=2, width=0.5)
ax.xaxis.set_tick_params(which='both', direction='out', labelsize=fontsize,
pad=tick_padding, length=2, width=0.5)
ax.xaxis.labelpad = label_padding
ax.yaxis.labelpad = label_padding
ax.xaxis.label.set_size(fontsize)
ax.yaxis.label.set_size(fontsize)
|
Remove strings with r'\use...' getting interp as Unicode!
|
Remove strings with r'\use...' getting interp as Unicode!
|
Python
|
bsd-2-clause
|
sorgerlab/belpy,sorgerlab/belpy,bgyori/indra,johnbachman/belpy,johnbachman/indra,johnbachman/belpy,johnbachman/indra,pvtodorov/indra,jmuhlich/indra,pvtodorov/indra,sorgerlab/indra,sorgerlab/belpy,bgyori/indra,pvtodorov/indra,sorgerlab/indra,johnbachman/belpy,pvtodorov/indra,jmuhlich/indra,sorgerlab/indra,bgyori/indra,johnbachman/indra,jmuhlich/indra
|
from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import matplotlib
fontsize=7
def set_fig_params():
matplotlib.rcParams['font.sans-serif'] = 'Arial'
matplotlib.rcParams['text.usetex'] = True
matplotlib.rcParams['text.latex.preamble'] = [
r'\usepackage{helvet}',
r'\usepackage{sansmath}',
r'\sansmath',
r'\usepackage{underscore}',]
def format_axis(ax, label_padding=2, tick_padding=0, yticks_position='left'):
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position(yticks_position)
ax.yaxis.set_tick_params(which='both', direction='out', labelsize=fontsize,
pad=tick_padding, length=2, width=0.5)
ax.xaxis.set_tick_params(which='both', direction='out', labelsize=fontsize,
pad=tick_padding, length=2, width=0.5)
ax.xaxis.labelpad = label_padding
ax.yaxis.labelpad = label_padding
ax.xaxis.label.set_size(fontsize)
ax.yaxis.label.set_size(fontsize)
Remove strings with r'\use...' getting interp as Unicode!
|
from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import matplotlib
fontsize=7
def set_fig_params():
matplotlib.rcParams['font.sans-serif'] = 'Arial'
matplotlib.rcParams['text.usetex'] = True
matplotlib.rcParams['text.latex.preamble'] = [
'\\usepackage{helvet}',
'\\usepackage{sansmath}',
'\\sansmath',
'\\usepackage{underscore}',]
def format_axis(ax, label_padding=2, tick_padding=0, yticks_position='left'):
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position(yticks_position)
ax.yaxis.set_tick_params(which='both', direction='out', labelsize=fontsize,
pad=tick_padding, length=2, width=0.5)
ax.xaxis.set_tick_params(which='both', direction='out', labelsize=fontsize,
pad=tick_padding, length=2, width=0.5)
ax.xaxis.labelpad = label_padding
ax.yaxis.labelpad = label_padding
ax.xaxis.label.set_size(fontsize)
ax.yaxis.label.set_size(fontsize)
|
<commit_before>from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import matplotlib
fontsize=7
def set_fig_params():
matplotlib.rcParams['font.sans-serif'] = 'Arial'
matplotlib.rcParams['text.usetex'] = True
matplotlib.rcParams['text.latex.preamble'] = [
r'\usepackage{helvet}',
r'\usepackage{sansmath}',
r'\sansmath',
r'\usepackage{underscore}',]
def format_axis(ax, label_padding=2, tick_padding=0, yticks_position='left'):
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position(yticks_position)
ax.yaxis.set_tick_params(which='both', direction='out', labelsize=fontsize,
pad=tick_padding, length=2, width=0.5)
ax.xaxis.set_tick_params(which='both', direction='out', labelsize=fontsize,
pad=tick_padding, length=2, width=0.5)
ax.xaxis.labelpad = label_padding
ax.yaxis.labelpad = label_padding
ax.xaxis.label.set_size(fontsize)
ax.yaxis.label.set_size(fontsize)
<commit_msg>Remove strings with r'\use...' getting interp as Unicode!<commit_after>
|
from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import matplotlib
fontsize=7
def set_fig_params():
matplotlib.rcParams['font.sans-serif'] = 'Arial'
matplotlib.rcParams['text.usetex'] = True
matplotlib.rcParams['text.latex.preamble'] = [
'\\usepackage{helvet}',
'\\usepackage{sansmath}',
'\\sansmath',
'\\usepackage{underscore}',]
def format_axis(ax, label_padding=2, tick_padding=0, yticks_position='left'):
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position(yticks_position)
ax.yaxis.set_tick_params(which='both', direction='out', labelsize=fontsize,
pad=tick_padding, length=2, width=0.5)
ax.xaxis.set_tick_params(which='both', direction='out', labelsize=fontsize,
pad=tick_padding, length=2, width=0.5)
ax.xaxis.labelpad = label_padding
ax.yaxis.labelpad = label_padding
ax.xaxis.label.set_size(fontsize)
ax.yaxis.label.set_size(fontsize)
|
from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import matplotlib
fontsize=7
def set_fig_params():
matplotlib.rcParams['font.sans-serif'] = 'Arial'
matplotlib.rcParams['text.usetex'] = True
matplotlib.rcParams['text.latex.preamble'] = [
r'\usepackage{helvet}',
r'\usepackage{sansmath}',
r'\sansmath',
r'\usepackage{underscore}',]
def format_axis(ax, label_padding=2, tick_padding=0, yticks_position='left'):
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position(yticks_position)
ax.yaxis.set_tick_params(which='both', direction='out', labelsize=fontsize,
pad=tick_padding, length=2, width=0.5)
ax.xaxis.set_tick_params(which='both', direction='out', labelsize=fontsize,
pad=tick_padding, length=2, width=0.5)
ax.xaxis.labelpad = label_padding
ax.yaxis.labelpad = label_padding
ax.xaxis.label.set_size(fontsize)
ax.yaxis.label.set_size(fontsize)
Remove strings with r'\use...' getting interp as Unicode!from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import matplotlib
fontsize=7
def set_fig_params():
matplotlib.rcParams['font.sans-serif'] = 'Arial'
matplotlib.rcParams['text.usetex'] = True
matplotlib.rcParams['text.latex.preamble'] = [
'\\usepackage{helvet}',
'\\usepackage{sansmath}',
'\\sansmath',
'\\usepackage{underscore}',]
def format_axis(ax, label_padding=2, tick_padding=0, yticks_position='left'):
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position(yticks_position)
ax.yaxis.set_tick_params(which='both', direction='out', labelsize=fontsize,
pad=tick_padding, length=2, width=0.5)
ax.xaxis.set_tick_params(which='both', direction='out', labelsize=fontsize,
pad=tick_padding, length=2, width=0.5)
ax.xaxis.labelpad = label_padding
ax.yaxis.labelpad = label_padding
ax.xaxis.label.set_size(fontsize)
ax.yaxis.label.set_size(fontsize)
|
<commit_before>from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import matplotlib
fontsize=7
def set_fig_params():
matplotlib.rcParams['font.sans-serif'] = 'Arial'
matplotlib.rcParams['text.usetex'] = True
matplotlib.rcParams['text.latex.preamble'] = [
r'\usepackage{helvet}',
r'\usepackage{sansmath}',
r'\sansmath',
r'\usepackage{underscore}',]
def format_axis(ax, label_padding=2, tick_padding=0, yticks_position='left'):
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position(yticks_position)
ax.yaxis.set_tick_params(which='both', direction='out', labelsize=fontsize,
pad=tick_padding, length=2, width=0.5)
ax.xaxis.set_tick_params(which='both', direction='out', labelsize=fontsize,
pad=tick_padding, length=2, width=0.5)
ax.xaxis.labelpad = label_padding
ax.yaxis.labelpad = label_padding
ax.xaxis.label.set_size(fontsize)
ax.yaxis.label.set_size(fontsize)
<commit_msg>Remove strings with r'\use...' getting interp as Unicode!<commit_after>from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import matplotlib
fontsize=7
def set_fig_params():
matplotlib.rcParams['font.sans-serif'] = 'Arial'
matplotlib.rcParams['text.usetex'] = True
matplotlib.rcParams['text.latex.preamble'] = [
'\\usepackage{helvet}',
'\\usepackage{sansmath}',
'\\sansmath',
'\\usepackage{underscore}',]
def format_axis(ax, label_padding=2, tick_padding=0, yticks_position='left'):
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position(yticks_position)
ax.yaxis.set_tick_params(which='both', direction='out', labelsize=fontsize,
pad=tick_padding, length=2, width=0.5)
ax.xaxis.set_tick_params(which='both', direction='out', labelsize=fontsize,
pad=tick_padding, length=2, width=0.5)
ax.xaxis.labelpad = label_padding
ax.yaxis.labelpad = label_padding
ax.xaxis.label.set_size(fontsize)
ax.yaxis.label.set_size(fontsize)
|
1e218ba94c774372929d890780ab12efbfaae181
|
core/management/commands/heroku.py
|
core/management/commands/heroku.py
|
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from django.core.management import call_command
class Command(BaseCommand):
help = 'Creates a superuser for Heroku'
def handle(self, *args, **kwargs):
verbosity = kwargs['verbosity']
call_command('migrate', verbosity=0)
User.objects.create_superuser(
username='admin',
email='admin@example.com',
password='changeme123'
)
if verbosity > 0:
self.stdout.write(
self.style.SUCCESS('Successfully run all Heroku commands.')
)
|
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from django.core.management import call_command
class Command(BaseCommand):
help = 'Runs migrations for Heroku'
def handle(self, *args, **kwargs):
verbosity = kwargs['verbosity']
call_command('migrate', verbosity=0)
if verbosity > 0:
self.stdout.write(
self.style.SUCCESS('Successfully ran all Heroku commands.')
)
|
Remove Heroku createsuperuser command. Migrate now creates a default user.
|
Remove Heroku createsuperuser command. Migrate now creates a default user.
|
Python
|
bsd-2-clause
|
cdubz/timestrap,muhleder/timestrap,muhleder/timestrap,muhleder/timestrap,overshard/timestrap,cdubz/timestrap,overshard/timestrap,overshard/timestrap,cdubz/timestrap
|
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from django.core.management import call_command
class Command(BaseCommand):
help = 'Creates a superuser for Heroku'
def handle(self, *args, **kwargs):
verbosity = kwargs['verbosity']
call_command('migrate', verbosity=0)
User.objects.create_superuser(
username='admin',
email='admin@example.com',
password='changeme123'
)
if verbosity > 0:
self.stdout.write(
self.style.SUCCESS('Successfully run all Heroku commands.')
)
Remove Heroku createsuperuser command. Migrate now creates a default user.
|
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from django.core.management import call_command
class Command(BaseCommand):
help = 'Runs migrations for Heroku'
def handle(self, *args, **kwargs):
verbosity = kwargs['verbosity']
call_command('migrate', verbosity=0)
if verbosity > 0:
self.stdout.write(
self.style.SUCCESS('Successfully ran all Heroku commands.')
)
|
<commit_before>from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from django.core.management import call_command
class Command(BaseCommand):
help = 'Creates a superuser for Heroku'
def handle(self, *args, **kwargs):
verbosity = kwargs['verbosity']
call_command('migrate', verbosity=0)
User.objects.create_superuser(
username='admin',
email='admin@example.com',
password='changeme123'
)
if verbosity > 0:
self.stdout.write(
self.style.SUCCESS('Successfully run all Heroku commands.')
)
<commit_msg>Remove Heroku createsuperuser command. Migrate now creates a default user.<commit_after>
|
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from django.core.management import call_command
class Command(BaseCommand):
help = 'Runs migrations for Heroku'
def handle(self, *args, **kwargs):
verbosity = kwargs['verbosity']
call_command('migrate', verbosity=0)
if verbosity > 0:
self.stdout.write(
self.style.SUCCESS('Successfully ran all Heroku commands.')
)
|
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from django.core.management import call_command
class Command(BaseCommand):
help = 'Creates a superuser for Heroku'
def handle(self, *args, **kwargs):
verbosity = kwargs['verbosity']
call_command('migrate', verbosity=0)
User.objects.create_superuser(
username='admin',
email='admin@example.com',
password='changeme123'
)
if verbosity > 0:
self.stdout.write(
self.style.SUCCESS('Successfully run all Heroku commands.')
)
Remove Heroku createsuperuser command. Migrate now creates a default user.from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from django.core.management import call_command
class Command(BaseCommand):
help = 'Runs migrations for Heroku'
def handle(self, *args, **kwargs):
verbosity = kwargs['verbosity']
call_command('migrate', verbosity=0)
if verbosity > 0:
self.stdout.write(
self.style.SUCCESS('Successfully ran all Heroku commands.')
)
|
<commit_before>from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from django.core.management import call_command
class Command(BaseCommand):
help = 'Creates a superuser for Heroku'
def handle(self, *args, **kwargs):
verbosity = kwargs['verbosity']
call_command('migrate', verbosity=0)
User.objects.create_superuser(
username='admin',
email='admin@example.com',
password='changeme123'
)
if verbosity > 0:
self.stdout.write(
self.style.SUCCESS('Successfully run all Heroku commands.')
)
<commit_msg>Remove Heroku createsuperuser command. Migrate now creates a default user.<commit_after>from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from django.core.management import call_command
class Command(BaseCommand):
help = 'Runs migrations for Heroku'
def handle(self, *args, **kwargs):
verbosity = kwargs['verbosity']
call_command('migrate', verbosity=0)
if verbosity > 0:
self.stdout.write(
self.style.SUCCESS('Successfully ran all Heroku commands.')
)
|
fba09b10f7df5a75d7886ba304dff9e7c79f2197
|
appengine/components/test_support/test_env.py
|
appengine/components/test_support/test_env.py
|
# Copyright 2013 The LUCI Authors. All rights reserved.
# Use of this source code is governed under the Apache License, Version 2.0
# that can be found in the LICENSE file.
import os
import sys
# /appengine/
ROOT_DIR = os.path.dirname(
os.path.dirname(os.path.realpath(os.path.abspath(__file__))))
_INITIALIZED = False
def setup_test_env(app_id='sample-app'):
"""Sets up App Engine/Django test environment."""
global _INITIALIZED
if _INITIALIZED:
raise Exception('Do not call test_env.setup_test_env() twice.')
_INITIALIZED = True
# For depot_tools.
sys.path.insert(
0, os.path.join(ROOT_DIR, '..', '..', 'client', 'third_party'))
# For 'from components import ...' and 'from test_support import ...'.
sys.path.insert(0, ROOT_DIR)
sys.path.insert(0, os.path.join(ROOT_DIR, '..', 'third_party_local'))
from tool_support import gae_sdk_utils
gae_sdk_utils.setup_gae_env()
gae_sdk_utils.setup_env(None, app_id, 'v1a', None)
from components import utils
utils.fix_protobuf_package()
|
# Copyright 2013 The LUCI Authors. All rights reserved.
# Use of this source code is governed under the Apache License, Version 2.0
# that can be found in the LICENSE file.
import os
import sys
# /appengine/
ROOT_DIR = os.path.dirname(
os.path.dirname(os.path.realpath(os.path.abspath(__file__))))
_INITIALIZED = False
def setup_test_env(app_id='sample-app'):
"""Sets up App Engine test environment."""
global _INITIALIZED
if _INITIALIZED:
raise Exception('Do not call test_env.setup_test_env() twice.')
_INITIALIZED = True
# TODO(vadimsh): Remove this once LUCI_PY_USE_GCLOUD is set by default.
os.environ['LUCI_PY_USE_GCLOUD'] = '1'
# For depot_tools.
sys.path.insert(
0, os.path.join(ROOT_DIR, '..', '..', 'client', 'third_party'))
# For 'from components import ...' and 'from test_support import ...'.
sys.path.insert(0, ROOT_DIR)
sys.path.insert(0, os.path.join(ROOT_DIR, '..', 'third_party_local'))
from tool_support import gae_sdk_utils
gae_sdk_utils.setup_gae_env()
gae_sdk_utils.setup_env(None, app_id, 'v1a', None)
from components import utils
utils.fix_protobuf_package()
|
Switch luci-py tests to use gcloud SDK.
|
Switch luci-py tests to use gcloud SDK.
R=maruel@chromium.org, iannucci@chromium.org
BUG=835919
Change-Id: Iaf7f361343dfebfc7fd603b8b996ad9fa5412f52
Reviewed-on: https://chromium-review.googlesource.com/c/infra/luci/luci-py/+/1684451
Reviewed-by: Andrii Shyshkalov <a30c74fa30536fe7ea81ed6dec202e35e149e1fd@chromium.org>
Commit-Queue: Vadim Shtayura <9f116ddb1b24f6fc1916a676eb17161b6c07dfc1@chromium.org>
|
Python
|
apache-2.0
|
luci/luci-py,luci/luci-py,luci/luci-py,luci/luci-py
|
# Copyright 2013 The LUCI Authors. All rights reserved.
# Use of this source code is governed under the Apache License, Version 2.0
# that can be found in the LICENSE file.
import os
import sys
# /appengine/
ROOT_DIR = os.path.dirname(
os.path.dirname(os.path.realpath(os.path.abspath(__file__))))
_INITIALIZED = False
def setup_test_env(app_id='sample-app'):
"""Sets up App Engine/Django test environment."""
global _INITIALIZED
if _INITIALIZED:
raise Exception('Do not call test_env.setup_test_env() twice.')
_INITIALIZED = True
# For depot_tools.
sys.path.insert(
0, os.path.join(ROOT_DIR, '..', '..', 'client', 'third_party'))
# For 'from components import ...' and 'from test_support import ...'.
sys.path.insert(0, ROOT_DIR)
sys.path.insert(0, os.path.join(ROOT_DIR, '..', 'third_party_local'))
from tool_support import gae_sdk_utils
gae_sdk_utils.setup_gae_env()
gae_sdk_utils.setup_env(None, app_id, 'v1a', None)
from components import utils
utils.fix_protobuf_package()
Switch luci-py tests to use gcloud SDK.
R=maruel@chromium.org, iannucci@chromium.org
BUG=835919
Change-Id: Iaf7f361343dfebfc7fd603b8b996ad9fa5412f52
Reviewed-on: https://chromium-review.googlesource.com/c/infra/luci/luci-py/+/1684451
Reviewed-by: Andrii Shyshkalov <a30c74fa30536fe7ea81ed6dec202e35e149e1fd@chromium.org>
Commit-Queue: Vadim Shtayura <9f116ddb1b24f6fc1916a676eb17161b6c07dfc1@chromium.org>
|
# Copyright 2013 The LUCI Authors. All rights reserved.
# Use of this source code is governed under the Apache License, Version 2.0
# that can be found in the LICENSE file.
import os
import sys
# /appengine/
ROOT_DIR = os.path.dirname(
os.path.dirname(os.path.realpath(os.path.abspath(__file__))))
_INITIALIZED = False
def setup_test_env(app_id='sample-app'):
"""Sets up App Engine test environment."""
global _INITIALIZED
if _INITIALIZED:
raise Exception('Do not call test_env.setup_test_env() twice.')
_INITIALIZED = True
# TODO(vadimsh): Remove this once LUCI_PY_USE_GCLOUD is set by default.
os.environ['LUCI_PY_USE_GCLOUD'] = '1'
# For depot_tools.
sys.path.insert(
0, os.path.join(ROOT_DIR, '..', '..', 'client', 'third_party'))
# For 'from components import ...' and 'from test_support import ...'.
sys.path.insert(0, ROOT_DIR)
sys.path.insert(0, os.path.join(ROOT_DIR, '..', 'third_party_local'))
from tool_support import gae_sdk_utils
gae_sdk_utils.setup_gae_env()
gae_sdk_utils.setup_env(None, app_id, 'v1a', None)
from components import utils
utils.fix_protobuf_package()
|
<commit_before># Copyright 2013 The LUCI Authors. All rights reserved.
# Use of this source code is governed under the Apache License, Version 2.0
# that can be found in the LICENSE file.
import os
import sys
# /appengine/
ROOT_DIR = os.path.dirname(
os.path.dirname(os.path.realpath(os.path.abspath(__file__))))
_INITIALIZED = False
def setup_test_env(app_id='sample-app'):
"""Sets up App Engine/Django test environment."""
global _INITIALIZED
if _INITIALIZED:
raise Exception('Do not call test_env.setup_test_env() twice.')
_INITIALIZED = True
# For depot_tools.
sys.path.insert(
0, os.path.join(ROOT_DIR, '..', '..', 'client', 'third_party'))
# For 'from components import ...' and 'from test_support import ...'.
sys.path.insert(0, ROOT_DIR)
sys.path.insert(0, os.path.join(ROOT_DIR, '..', 'third_party_local'))
from tool_support import gae_sdk_utils
gae_sdk_utils.setup_gae_env()
gae_sdk_utils.setup_env(None, app_id, 'v1a', None)
from components import utils
utils.fix_protobuf_package()
<commit_msg>Switch luci-py tests to use gcloud SDK.
R=maruel@chromium.org, iannucci@chromium.org
BUG=835919
Change-Id: Iaf7f361343dfebfc7fd603b8b996ad9fa5412f52
Reviewed-on: https://chromium-review.googlesource.com/c/infra/luci/luci-py/+/1684451
Reviewed-by: Andrii Shyshkalov <a30c74fa30536fe7ea81ed6dec202e35e149e1fd@chromium.org>
Commit-Queue: Vadim Shtayura <9f116ddb1b24f6fc1916a676eb17161b6c07dfc1@chromium.org><commit_after>
|
# Copyright 2013 The LUCI Authors. All rights reserved.
# Use of this source code is governed under the Apache License, Version 2.0
# that can be found in the LICENSE file.
import os
import sys
# /appengine/
ROOT_DIR = os.path.dirname(
os.path.dirname(os.path.realpath(os.path.abspath(__file__))))
_INITIALIZED = False
def setup_test_env(app_id='sample-app'):
"""Sets up App Engine test environment."""
global _INITIALIZED
if _INITIALIZED:
raise Exception('Do not call test_env.setup_test_env() twice.')
_INITIALIZED = True
# TODO(vadimsh): Remove this once LUCI_PY_USE_GCLOUD is set by default.
os.environ['LUCI_PY_USE_GCLOUD'] = '1'
# For depot_tools.
sys.path.insert(
0, os.path.join(ROOT_DIR, '..', '..', 'client', 'third_party'))
# For 'from components import ...' and 'from test_support import ...'.
sys.path.insert(0, ROOT_DIR)
sys.path.insert(0, os.path.join(ROOT_DIR, '..', 'third_party_local'))
from tool_support import gae_sdk_utils
gae_sdk_utils.setup_gae_env()
gae_sdk_utils.setup_env(None, app_id, 'v1a', None)
from components import utils
utils.fix_protobuf_package()
|
# Copyright 2013 The LUCI Authors. All rights reserved.
# Use of this source code is governed under the Apache License, Version 2.0
# that can be found in the LICENSE file.
import os
import sys
# /appengine/
ROOT_DIR = os.path.dirname(
os.path.dirname(os.path.realpath(os.path.abspath(__file__))))
_INITIALIZED = False
def setup_test_env(app_id='sample-app'):
"""Sets up App Engine/Django test environment."""
global _INITIALIZED
if _INITIALIZED:
raise Exception('Do not call test_env.setup_test_env() twice.')
_INITIALIZED = True
# For depot_tools.
sys.path.insert(
0, os.path.join(ROOT_DIR, '..', '..', 'client', 'third_party'))
# For 'from components import ...' and 'from test_support import ...'.
sys.path.insert(0, ROOT_DIR)
sys.path.insert(0, os.path.join(ROOT_DIR, '..', 'third_party_local'))
from tool_support import gae_sdk_utils
gae_sdk_utils.setup_gae_env()
gae_sdk_utils.setup_env(None, app_id, 'v1a', None)
from components import utils
utils.fix_protobuf_package()
Switch luci-py tests to use gcloud SDK.
R=maruel@chromium.org, iannucci@chromium.org
BUG=835919
Change-Id: Iaf7f361343dfebfc7fd603b8b996ad9fa5412f52
Reviewed-on: https://chromium-review.googlesource.com/c/infra/luci/luci-py/+/1684451
Reviewed-by: Andrii Shyshkalov <a30c74fa30536fe7ea81ed6dec202e35e149e1fd@chromium.org>
Commit-Queue: Vadim Shtayura <9f116ddb1b24f6fc1916a676eb17161b6c07dfc1@chromium.org># Copyright 2013 The LUCI Authors. All rights reserved.
# Use of this source code is governed under the Apache License, Version 2.0
# that can be found in the LICENSE file.
import os
import sys
# /appengine/
ROOT_DIR = os.path.dirname(
os.path.dirname(os.path.realpath(os.path.abspath(__file__))))
_INITIALIZED = False
def setup_test_env(app_id='sample-app'):
"""Sets up App Engine test environment."""
global _INITIALIZED
if _INITIALIZED:
raise Exception('Do not call test_env.setup_test_env() twice.')
_INITIALIZED = True
# TODO(vadimsh): Remove this once LUCI_PY_USE_GCLOUD is set by default.
os.environ['LUCI_PY_USE_GCLOUD'] = '1'
# For depot_tools.
sys.path.insert(
0, os.path.join(ROOT_DIR, '..', '..', 'client', 'third_party'))
# For 'from components import ...' and 'from test_support import ...'.
sys.path.insert(0, ROOT_DIR)
sys.path.insert(0, os.path.join(ROOT_DIR, '..', 'third_party_local'))
from tool_support import gae_sdk_utils
gae_sdk_utils.setup_gae_env()
gae_sdk_utils.setup_env(None, app_id, 'v1a', None)
from components import utils
utils.fix_protobuf_package()
|
<commit_before># Copyright 2013 The LUCI Authors. All rights reserved.
# Use of this source code is governed under the Apache License, Version 2.0
# that can be found in the LICENSE file.
import os
import sys
# /appengine/
ROOT_DIR = os.path.dirname(
os.path.dirname(os.path.realpath(os.path.abspath(__file__))))
_INITIALIZED = False
def setup_test_env(app_id='sample-app'):
"""Sets up App Engine/Django test environment."""
global _INITIALIZED
if _INITIALIZED:
raise Exception('Do not call test_env.setup_test_env() twice.')
_INITIALIZED = True
# For depot_tools.
sys.path.insert(
0, os.path.join(ROOT_DIR, '..', '..', 'client', 'third_party'))
# For 'from components import ...' and 'from test_support import ...'.
sys.path.insert(0, ROOT_DIR)
sys.path.insert(0, os.path.join(ROOT_DIR, '..', 'third_party_local'))
from tool_support import gae_sdk_utils
gae_sdk_utils.setup_gae_env()
gae_sdk_utils.setup_env(None, app_id, 'v1a', None)
from components import utils
utils.fix_protobuf_package()
<commit_msg>Switch luci-py tests to use gcloud SDK.
R=maruel@chromium.org, iannucci@chromium.org
BUG=835919
Change-Id: Iaf7f361343dfebfc7fd603b8b996ad9fa5412f52
Reviewed-on: https://chromium-review.googlesource.com/c/infra/luci/luci-py/+/1684451
Reviewed-by: Andrii Shyshkalov <a30c74fa30536fe7ea81ed6dec202e35e149e1fd@chromium.org>
Commit-Queue: Vadim Shtayura <9f116ddb1b24f6fc1916a676eb17161b6c07dfc1@chromium.org><commit_after># Copyright 2013 The LUCI Authors. All rights reserved.
# Use of this source code is governed under the Apache License, Version 2.0
# that can be found in the LICENSE file.
import os
import sys
# /appengine/
ROOT_DIR = os.path.dirname(
os.path.dirname(os.path.realpath(os.path.abspath(__file__))))
_INITIALIZED = False
def setup_test_env(app_id='sample-app'):
"""Sets up App Engine test environment."""
global _INITIALIZED
if _INITIALIZED:
raise Exception('Do not call test_env.setup_test_env() twice.')
_INITIALIZED = True
# TODO(vadimsh): Remove this once LUCI_PY_USE_GCLOUD is set by default.
os.environ['LUCI_PY_USE_GCLOUD'] = '1'
# For depot_tools.
sys.path.insert(
0, os.path.join(ROOT_DIR, '..', '..', 'client', 'third_party'))
# For 'from components import ...' and 'from test_support import ...'.
sys.path.insert(0, ROOT_DIR)
sys.path.insert(0, os.path.join(ROOT_DIR, '..', 'third_party_local'))
from tool_support import gae_sdk_utils
gae_sdk_utils.setup_gae_env()
gae_sdk_utils.setup_env(None, app_id, 'v1a', None)
from components import utils
utils.fix_protobuf_package()
|
2d55cf766baeb6c9f3ad0c1925b049464680cf7e
|
saleor/integrations/utils.py
|
saleor/integrations/utils.py
|
import gzip
import csv
from django.core.files.storage import default_storage
def update_feed(feed):
with default_storage.open(feed.file_path, 'w') as output_file:
if feed.compression:
output = gzip.GzipFile(fileobj=output_file)
else:
output = output_file
writer = csv.DictWriter(output,feed.attributes,
delimiter=str("\t"))
writer.writeheader()
for item in feed.items():
writer.writerow(feed.item_attributes(item))
if feed.compression:
output.close()
|
from __future__ import unicode_literals
import gzip
import csv
from django.core.files.storage import default_storage
def update_feed(feed):
with default_storage.open(feed.file_path, 'wb') as output_file:
if feed.compression:
try:
output = gzip.open(output_file, 'wt')
except TypeError:
output = gzip.GzipFile(fileobj=output_file, mode='w')
else:
output = output_file
writer = csv.DictWriter(output, feed.attributes,
dialect=csv.excel_tab)
writer.writeheader()
for item in feed.items():
writer.writerow(feed.item_attributes(item))
if feed.compression:
output.close()
|
Fix compressed feeds in python3
|
Fix compressed feeds in python3
|
Python
|
bsd-3-clause
|
KenMutemi/saleor,tfroehlich82/saleor,itbabu/saleor,itbabu/saleor,car3oon/saleor,UITools/saleor,tfroehlich82/saleor,UITools/saleor,HyperManTT/ECommerceSaleor,UITools/saleor,jreigel/saleor,KenMutemi/saleor,itbabu/saleor,car3oon/saleor,mociepka/saleor,maferelo/saleor,maferelo/saleor,UITools/saleor,HyperManTT/ECommerceSaleor,jreigel/saleor,maferelo/saleor,mociepka/saleor,jreigel/saleor,mociepka/saleor,UITools/saleor,tfroehlich82/saleor,KenMutemi/saleor,HyperManTT/ECommerceSaleor,car3oon/saleor
|
import gzip
import csv
from django.core.files.storage import default_storage
def update_feed(feed):
with default_storage.open(feed.file_path, 'w') as output_file:
if feed.compression:
output = gzip.GzipFile(fileobj=output_file)
else:
output = output_file
writer = csv.DictWriter(output,feed.attributes,
delimiter=str("\t"))
writer.writeheader()
for item in feed.items():
writer.writerow(feed.item_attributes(item))
if feed.compression:
output.close()
Fix compressed feeds in python3
|
from __future__ import unicode_literals
import gzip
import csv
from django.core.files.storage import default_storage
def update_feed(feed):
with default_storage.open(feed.file_path, 'wb') as output_file:
if feed.compression:
try:
output = gzip.open(output_file, 'wt')
except TypeError:
output = gzip.GzipFile(fileobj=output_file, mode='w')
else:
output = output_file
writer = csv.DictWriter(output, feed.attributes,
dialect=csv.excel_tab)
writer.writeheader()
for item in feed.items():
writer.writerow(feed.item_attributes(item))
if feed.compression:
output.close()
|
<commit_before>import gzip
import csv
from django.core.files.storage import default_storage
def update_feed(feed):
with default_storage.open(feed.file_path, 'w') as output_file:
if feed.compression:
output = gzip.GzipFile(fileobj=output_file)
else:
output = output_file
writer = csv.DictWriter(output,feed.attributes,
delimiter=str("\t"))
writer.writeheader()
for item in feed.items():
writer.writerow(feed.item_attributes(item))
if feed.compression:
output.close()
<commit_msg>Fix compressed feeds in python3<commit_after>
|
from __future__ import unicode_literals
import gzip
import csv
from django.core.files.storage import default_storage
def update_feed(feed):
with default_storage.open(feed.file_path, 'wb') as output_file:
if feed.compression:
try:
output = gzip.open(output_file, 'wt')
except TypeError:
output = gzip.GzipFile(fileobj=output_file, mode='w')
else:
output = output_file
writer = csv.DictWriter(output, feed.attributes,
dialect=csv.excel_tab)
writer.writeheader()
for item in feed.items():
writer.writerow(feed.item_attributes(item))
if feed.compression:
output.close()
|
import gzip
import csv
from django.core.files.storage import default_storage
def update_feed(feed):
with default_storage.open(feed.file_path, 'w') as output_file:
if feed.compression:
output = gzip.GzipFile(fileobj=output_file)
else:
output = output_file
writer = csv.DictWriter(output,feed.attributes,
delimiter=str("\t"))
writer.writeheader()
for item in feed.items():
writer.writerow(feed.item_attributes(item))
if feed.compression:
output.close()
Fix compressed feeds in python3from __future__ import unicode_literals
import gzip
import csv
from django.core.files.storage import default_storage
def update_feed(feed):
with default_storage.open(feed.file_path, 'wb') as output_file:
if feed.compression:
try:
output = gzip.open(output_file, 'wt')
except TypeError:
output = gzip.GzipFile(fileobj=output_file, mode='w')
else:
output = output_file
writer = csv.DictWriter(output, feed.attributes,
dialect=csv.excel_tab)
writer.writeheader()
for item in feed.items():
writer.writerow(feed.item_attributes(item))
if feed.compression:
output.close()
|
<commit_before>import gzip
import csv
from django.core.files.storage import default_storage
def update_feed(feed):
with default_storage.open(feed.file_path, 'w') as output_file:
if feed.compression:
output = gzip.GzipFile(fileobj=output_file)
else:
output = output_file
writer = csv.DictWriter(output,feed.attributes,
delimiter=str("\t"))
writer.writeheader()
for item in feed.items():
writer.writerow(feed.item_attributes(item))
if feed.compression:
output.close()
<commit_msg>Fix compressed feeds in python3<commit_after>from __future__ import unicode_literals
import gzip
import csv
from django.core.files.storage import default_storage
def update_feed(feed):
with default_storage.open(feed.file_path, 'wb') as output_file:
if feed.compression:
try:
output = gzip.open(output_file, 'wt')
except TypeError:
output = gzip.GzipFile(fileobj=output_file, mode='w')
else:
output = output_file
writer = csv.DictWriter(output, feed.attributes,
dialect=csv.excel_tab)
writer.writeheader()
for item in feed.items():
writer.writerow(feed.item_attributes(item))
if feed.compression:
output.close()
|
2d2fb47e321faa032c98e92d34e6215b6026f1f0
|
keras/applications/__init__.py
|
keras/applications/__init__.py
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from .. import backend
from .. import layers
from .. import models
from .. import utils
import keras_applications
if not hasattr(keras_applications, 'get_submodules_from_kwargs'):
keras_applications.set_keras_submodules(
backend=backend,
layers=layers,
models=models,
utils=utils)
def keras_modules_injection(base_fun):
def wrapper(*args, **kwargs):
if hasattr(keras_applications, 'get_submodules_from_kwargs'):
kwargs['backend'] = backend
kwargs['layers'] = layers
kwargs['models'] = models
kwargs['utils'] = utils
return base_fun(*args, **kwargs)
return wrapper
from .vgg16 import VGG16
from .vgg19 import VGG19
from .resnet50 import ResNet50
from .inception_v3 import InceptionV3
from .inception_resnet_v2 import InceptionResNetV2
from .xception import Xception
from .mobilenet import MobileNet
from .mobilenet_v2 import MobileNetV2
from .densenet import DenseNet121, DenseNet169, DenseNet201
from .nasnet import NASNetMobile, NASNetLarge
from .resnet import ResNet101, ResNet152
from .resnet_v2 import ResNet50V2, ResNet101V2, ResNet152V2
from .resnext import ResNeXt50, ResNeXt101
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from .. import backend
from .. import layers
from .. import models
from .. import utils
import keras_applications
def keras_modules_injection(base_fun):
def wrapper(*args, **kwargs):
kwargs['backend'] = backend
kwargs['layers'] = layers
kwargs['models'] = models
kwargs['utils'] = utils
return base_fun(*args, **kwargs)
return wrapper
from .vgg16 import VGG16
from .vgg19 import VGG19
from .resnet50 import ResNet50
from .inception_v3 import InceptionV3
from .inception_resnet_v2 import InceptionResNetV2
from .xception import Xception
from .mobilenet import MobileNet
from .mobilenet_v2 import MobileNetV2
from .densenet import DenseNet121, DenseNet169, DenseNet201
from .nasnet import NASNetMobile, NASNetLarge
from .resnet import ResNet101, ResNet152
from .resnet_v2 import ResNet50V2, ResNet101V2, ResNet152V2
|
Remove deprecated applications adapter code
|
Remove deprecated applications adapter code
|
Python
|
apache-2.0
|
keras-team/keras,keras-team/keras
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from .. import backend
from .. import layers
from .. import models
from .. import utils
import keras_applications
if not hasattr(keras_applications, 'get_submodules_from_kwargs'):
keras_applications.set_keras_submodules(
backend=backend,
layers=layers,
models=models,
utils=utils)
def keras_modules_injection(base_fun):
def wrapper(*args, **kwargs):
if hasattr(keras_applications, 'get_submodules_from_kwargs'):
kwargs['backend'] = backend
kwargs['layers'] = layers
kwargs['models'] = models
kwargs['utils'] = utils
return base_fun(*args, **kwargs)
return wrapper
from .vgg16 import VGG16
from .vgg19 import VGG19
from .resnet50 import ResNet50
from .inception_v3 import InceptionV3
from .inception_resnet_v2 import InceptionResNetV2
from .xception import Xception
from .mobilenet import MobileNet
from .mobilenet_v2 import MobileNetV2
from .densenet import DenseNet121, DenseNet169, DenseNet201
from .nasnet import NASNetMobile, NASNetLarge
from .resnet import ResNet101, ResNet152
from .resnet_v2 import ResNet50V2, ResNet101V2, ResNet152V2
from .resnext import ResNeXt50, ResNeXt101
Remove deprecated applications adapter code
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from .. import backend
from .. import layers
from .. import models
from .. import utils
import keras_applications
def keras_modules_injection(base_fun):
def wrapper(*args, **kwargs):
kwargs['backend'] = backend
kwargs['layers'] = layers
kwargs['models'] = models
kwargs['utils'] = utils
return base_fun(*args, **kwargs)
return wrapper
from .vgg16 import VGG16
from .vgg19 import VGG19
from .resnet50 import ResNet50
from .inception_v3 import InceptionV3
from .inception_resnet_v2 import InceptionResNetV2
from .xception import Xception
from .mobilenet import MobileNet
from .mobilenet_v2 import MobileNetV2
from .densenet import DenseNet121, DenseNet169, DenseNet201
from .nasnet import NASNetMobile, NASNetLarge
from .resnet import ResNet101, ResNet152
from .resnet_v2 import ResNet50V2, ResNet101V2, ResNet152V2
|
<commit_before>from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from .. import backend
from .. import layers
from .. import models
from .. import utils
import keras_applications
if not hasattr(keras_applications, 'get_submodules_from_kwargs'):
keras_applications.set_keras_submodules(
backend=backend,
layers=layers,
models=models,
utils=utils)
def keras_modules_injection(base_fun):
def wrapper(*args, **kwargs):
if hasattr(keras_applications, 'get_submodules_from_kwargs'):
kwargs['backend'] = backend
kwargs['layers'] = layers
kwargs['models'] = models
kwargs['utils'] = utils
return base_fun(*args, **kwargs)
return wrapper
from .vgg16 import VGG16
from .vgg19 import VGG19
from .resnet50 import ResNet50
from .inception_v3 import InceptionV3
from .inception_resnet_v2 import InceptionResNetV2
from .xception import Xception
from .mobilenet import MobileNet
from .mobilenet_v2 import MobileNetV2
from .densenet import DenseNet121, DenseNet169, DenseNet201
from .nasnet import NASNetMobile, NASNetLarge
from .resnet import ResNet101, ResNet152
from .resnet_v2 import ResNet50V2, ResNet101V2, ResNet152V2
from .resnext import ResNeXt50, ResNeXt101
<commit_msg>Remove deprecated applications adapter code<commit_after>
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from .. import backend
from .. import layers
from .. import models
from .. import utils
import keras_applications
def keras_modules_injection(base_fun):
def wrapper(*args, **kwargs):
kwargs['backend'] = backend
kwargs['layers'] = layers
kwargs['models'] = models
kwargs['utils'] = utils
return base_fun(*args, **kwargs)
return wrapper
from .vgg16 import VGG16
from .vgg19 import VGG19
from .resnet50 import ResNet50
from .inception_v3 import InceptionV3
from .inception_resnet_v2 import InceptionResNetV2
from .xception import Xception
from .mobilenet import MobileNet
from .mobilenet_v2 import MobileNetV2
from .densenet import DenseNet121, DenseNet169, DenseNet201
from .nasnet import NASNetMobile, NASNetLarge
from .resnet import ResNet101, ResNet152
from .resnet_v2 import ResNet50V2, ResNet101V2, ResNet152V2
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from .. import backend
from .. import layers
from .. import models
from .. import utils
import keras_applications
if not hasattr(keras_applications, 'get_submodules_from_kwargs'):
keras_applications.set_keras_submodules(
backend=backend,
layers=layers,
models=models,
utils=utils)
def keras_modules_injection(base_fun):
def wrapper(*args, **kwargs):
if hasattr(keras_applications, 'get_submodules_from_kwargs'):
kwargs['backend'] = backend
kwargs['layers'] = layers
kwargs['models'] = models
kwargs['utils'] = utils
return base_fun(*args, **kwargs)
return wrapper
from .vgg16 import VGG16
from .vgg19 import VGG19
from .resnet50 import ResNet50
from .inception_v3 import InceptionV3
from .inception_resnet_v2 import InceptionResNetV2
from .xception import Xception
from .mobilenet import MobileNet
from .mobilenet_v2 import MobileNetV2
from .densenet import DenseNet121, DenseNet169, DenseNet201
from .nasnet import NASNetMobile, NASNetLarge
from .resnet import ResNet101, ResNet152
from .resnet_v2 import ResNet50V2, ResNet101V2, ResNet152V2
from .resnext import ResNeXt50, ResNeXt101
Remove deprecated applications adapter codefrom __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from .. import backend
from .. import layers
from .. import models
from .. import utils
import keras_applications
def keras_modules_injection(base_fun):
def wrapper(*args, **kwargs):
kwargs['backend'] = backend
kwargs['layers'] = layers
kwargs['models'] = models
kwargs['utils'] = utils
return base_fun(*args, **kwargs)
return wrapper
from .vgg16 import VGG16
from .vgg19 import VGG19
from .resnet50 import ResNet50
from .inception_v3 import InceptionV3
from .inception_resnet_v2 import InceptionResNetV2
from .xception import Xception
from .mobilenet import MobileNet
from .mobilenet_v2 import MobileNetV2
from .densenet import DenseNet121, DenseNet169, DenseNet201
from .nasnet import NASNetMobile, NASNetLarge
from .resnet import ResNet101, ResNet152
from .resnet_v2 import ResNet50V2, ResNet101V2, ResNet152V2
|
<commit_before>from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from .. import backend
from .. import layers
from .. import models
from .. import utils
import keras_applications
if not hasattr(keras_applications, 'get_submodules_from_kwargs'):
keras_applications.set_keras_submodules(
backend=backend,
layers=layers,
models=models,
utils=utils)
def keras_modules_injection(base_fun):
def wrapper(*args, **kwargs):
if hasattr(keras_applications, 'get_submodules_from_kwargs'):
kwargs['backend'] = backend
kwargs['layers'] = layers
kwargs['models'] = models
kwargs['utils'] = utils
return base_fun(*args, **kwargs)
return wrapper
from .vgg16 import VGG16
from .vgg19 import VGG19
from .resnet50 import ResNet50
from .inception_v3 import InceptionV3
from .inception_resnet_v2 import InceptionResNetV2
from .xception import Xception
from .mobilenet import MobileNet
from .mobilenet_v2 import MobileNetV2
from .densenet import DenseNet121, DenseNet169, DenseNet201
from .nasnet import NASNetMobile, NASNetLarge
from .resnet import ResNet101, ResNet152
from .resnet_v2 import ResNet50V2, ResNet101V2, ResNet152V2
from .resnext import ResNeXt50, ResNeXt101
<commit_msg>Remove deprecated applications adapter code<commit_after>from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from .. import backend
from .. import layers
from .. import models
from .. import utils
import keras_applications
def keras_modules_injection(base_fun):
def wrapper(*args, **kwargs):
kwargs['backend'] = backend
kwargs['layers'] = layers
kwargs['models'] = models
kwargs['utils'] = utils
return base_fun(*args, **kwargs)
return wrapper
from .vgg16 import VGG16
from .vgg19 import VGG19
from .resnet50 import ResNet50
from .inception_v3 import InceptionV3
from .inception_resnet_v2 import InceptionResNetV2
from .xception import Xception
from .mobilenet import MobileNet
from .mobilenet_v2 import MobileNetV2
from .densenet import DenseNet121, DenseNet169, DenseNet201
from .nasnet import NASNetMobile, NASNetLarge
from .resnet import ResNet101, ResNet152
from .resnet_v2 import ResNet50V2, ResNet101V2, ResNet152V2
|
eb8177cdc1c9b8bb38844786bc66f362eef7c7ee
|
{{cookiecutter.app_name}}/src/{{cookiecutter.app_name}}/__init__.py
|
{{cookiecutter.app_name}}/src/{{cookiecutter.app_name}}/__init__.py
|
from flask import Flask
from raven.contrib.flask import Sentry
from flask_debugtoolbar import DebugToolbarExtension
from werkzeug.contrib.profiler import ProfilerMiddleware
from {{cookiecutter.app_name}}.views import CatAPI
from {{cookiecutter.app_name}}.views import api, cache
from {{cookiecutter.app_name}}.models import db
def create_app(config={}):
app = Flask("{{cookiecutter.app_name}}")
app.config.from_envvar("FLASK_CONFIG")
app.config.update(config)
#External
sentry.init_app(app)
api.init_app(app)
cache.init_app(app)
#Internal
db.init_app(app)
#API Endpoints
api.add_resource(CatAPI, "/cats/<int:cat_id>")
with app.app_context():
db.create_all()
#Debug tools
if app.debug:
DebugToolbarExtension(app)
if app.config.get("PROFILE", False):
app.wsgi_app = ProfilerMiddleware(app.wsgi_app,
restrictions=[30],
sort_by=("time", "cumulative"))
return app
sentry = Sentry()
|
from flask import Flask
from raven.contrib.flask import Sentry
from flask_debugtoolbar import DebugToolbarExtension
from werkzeug.contrib.profiler import ProfilerMiddleware
from {{cookiecutter.app_name}}.views import CatAPI
from {{cookiecutter.app_name}}.views import api, cache
from {{cookiecutter.app_name}}.models import db
def create_app(config={}):
app = Flask("{{cookiecutter.app_name}}")
app.config.from_envvar("FLASK_CONFIG")
app.config.update(config)
#API Endpoints
api.add_resource(CatAPI, "/cats/<int:cat_id>")
#External
sentry.init_app(app)
api.init_app(app)
cache.init_app(app)
#Internal
db.init_app(app)
with app.app_context():
db.create_all()
#Debug tools
if app.debug:
DebugToolbarExtension(app)
if app.config.get("PROFILE", False):
app.wsgi_app = ProfilerMiddleware(app.wsgi_app,
restrictions=[30],
sort_by=("time", "cumulative"))
return app
sentry = Sentry()
|
Move flask-restful api defs before init_app, since it doesn't work otherwise with new version of flask-restful
|
Move flask-restful api defs before init_app, since it doesn't work
otherwise with new version of flask-restful
|
Python
|
mit
|
makmanalp/flask-chassis
|
from flask import Flask
from raven.contrib.flask import Sentry
from flask_debugtoolbar import DebugToolbarExtension
from werkzeug.contrib.profiler import ProfilerMiddleware
from {{cookiecutter.app_name}}.views import CatAPI
from {{cookiecutter.app_name}}.views import api, cache
from {{cookiecutter.app_name}}.models import db
def create_app(config={}):
app = Flask("{{cookiecutter.app_name}}")
app.config.from_envvar("FLASK_CONFIG")
app.config.update(config)
#External
sentry.init_app(app)
api.init_app(app)
cache.init_app(app)
#Internal
db.init_app(app)
#API Endpoints
api.add_resource(CatAPI, "/cats/<int:cat_id>")
with app.app_context():
db.create_all()
#Debug tools
if app.debug:
DebugToolbarExtension(app)
if app.config.get("PROFILE", False):
app.wsgi_app = ProfilerMiddleware(app.wsgi_app,
restrictions=[30],
sort_by=("time", "cumulative"))
return app
sentry = Sentry()
Move flask-restful api defs before init_app, since it doesn't work
otherwise with new version of flask-restful
|
from flask import Flask
from raven.contrib.flask import Sentry
from flask_debugtoolbar import DebugToolbarExtension
from werkzeug.contrib.profiler import ProfilerMiddleware
from {{cookiecutter.app_name}}.views import CatAPI
from {{cookiecutter.app_name}}.views import api, cache
from {{cookiecutter.app_name}}.models import db
def create_app(config={}):
app = Flask("{{cookiecutter.app_name}}")
app.config.from_envvar("FLASK_CONFIG")
app.config.update(config)
#API Endpoints
api.add_resource(CatAPI, "/cats/<int:cat_id>")
#External
sentry.init_app(app)
api.init_app(app)
cache.init_app(app)
#Internal
db.init_app(app)
with app.app_context():
db.create_all()
#Debug tools
if app.debug:
DebugToolbarExtension(app)
if app.config.get("PROFILE", False):
app.wsgi_app = ProfilerMiddleware(app.wsgi_app,
restrictions=[30],
sort_by=("time", "cumulative"))
return app
sentry = Sentry()
|
<commit_before>from flask import Flask
from raven.contrib.flask import Sentry
from flask_debugtoolbar import DebugToolbarExtension
from werkzeug.contrib.profiler import ProfilerMiddleware
from {{cookiecutter.app_name}}.views import CatAPI
from {{cookiecutter.app_name}}.views import api, cache
from {{cookiecutter.app_name}}.models import db
def create_app(config={}):
app = Flask("{{cookiecutter.app_name}}")
app.config.from_envvar("FLASK_CONFIG")
app.config.update(config)
#External
sentry.init_app(app)
api.init_app(app)
cache.init_app(app)
#Internal
db.init_app(app)
#API Endpoints
api.add_resource(CatAPI, "/cats/<int:cat_id>")
with app.app_context():
db.create_all()
#Debug tools
if app.debug:
DebugToolbarExtension(app)
if app.config.get("PROFILE", False):
app.wsgi_app = ProfilerMiddleware(app.wsgi_app,
restrictions=[30],
sort_by=("time", "cumulative"))
return app
sentry = Sentry()
<commit_msg>Move flask-restful api defs before init_app, since it doesn't work
otherwise with new version of flask-restful<commit_after>
|
from flask import Flask
from raven.contrib.flask import Sentry
from flask_debugtoolbar import DebugToolbarExtension
from werkzeug.contrib.profiler import ProfilerMiddleware
from {{cookiecutter.app_name}}.views import CatAPI
from {{cookiecutter.app_name}}.views import api, cache
from {{cookiecutter.app_name}}.models import db
def create_app(config={}):
app = Flask("{{cookiecutter.app_name}}")
app.config.from_envvar("FLASK_CONFIG")
app.config.update(config)
#API Endpoints
api.add_resource(CatAPI, "/cats/<int:cat_id>")
#External
sentry.init_app(app)
api.init_app(app)
cache.init_app(app)
#Internal
db.init_app(app)
with app.app_context():
db.create_all()
#Debug tools
if app.debug:
DebugToolbarExtension(app)
if app.config.get("PROFILE", False):
app.wsgi_app = ProfilerMiddleware(app.wsgi_app,
restrictions=[30],
sort_by=("time", "cumulative"))
return app
sentry = Sentry()
|
from flask import Flask
from raven.contrib.flask import Sentry
from flask_debugtoolbar import DebugToolbarExtension
from werkzeug.contrib.profiler import ProfilerMiddleware
from {{cookiecutter.app_name}}.views import CatAPI
from {{cookiecutter.app_name}}.views import api, cache
from {{cookiecutter.app_name}}.models import db
def create_app(config={}):
app = Flask("{{cookiecutter.app_name}}")
app.config.from_envvar("FLASK_CONFIG")
app.config.update(config)
#External
sentry.init_app(app)
api.init_app(app)
cache.init_app(app)
#Internal
db.init_app(app)
#API Endpoints
api.add_resource(CatAPI, "/cats/<int:cat_id>")
with app.app_context():
db.create_all()
#Debug tools
if app.debug:
DebugToolbarExtension(app)
if app.config.get("PROFILE", False):
app.wsgi_app = ProfilerMiddleware(app.wsgi_app,
restrictions=[30],
sort_by=("time", "cumulative"))
return app
sentry = Sentry()
Move flask-restful api defs before init_app, since it doesn't work
otherwise with new version of flask-restfulfrom flask import Flask
from raven.contrib.flask import Sentry
from flask_debugtoolbar import DebugToolbarExtension
from werkzeug.contrib.profiler import ProfilerMiddleware
from {{cookiecutter.app_name}}.views import CatAPI
from {{cookiecutter.app_name}}.views import api, cache
from {{cookiecutter.app_name}}.models import db
def create_app(config={}):
app = Flask("{{cookiecutter.app_name}}")
app.config.from_envvar("FLASK_CONFIG")
app.config.update(config)
#API Endpoints
api.add_resource(CatAPI, "/cats/<int:cat_id>")
#External
sentry.init_app(app)
api.init_app(app)
cache.init_app(app)
#Internal
db.init_app(app)
with app.app_context():
db.create_all()
#Debug tools
if app.debug:
DebugToolbarExtension(app)
if app.config.get("PROFILE", False):
app.wsgi_app = ProfilerMiddleware(app.wsgi_app,
restrictions=[30],
sort_by=("time", "cumulative"))
return app
sentry = Sentry()
|
<commit_before>from flask import Flask
from raven.contrib.flask import Sentry
from flask_debugtoolbar import DebugToolbarExtension
from werkzeug.contrib.profiler import ProfilerMiddleware
from {{cookiecutter.app_name}}.views import CatAPI
from {{cookiecutter.app_name}}.views import api, cache
from {{cookiecutter.app_name}}.models import db
def create_app(config={}):
app = Flask("{{cookiecutter.app_name}}")
app.config.from_envvar("FLASK_CONFIG")
app.config.update(config)
#External
sentry.init_app(app)
api.init_app(app)
cache.init_app(app)
#Internal
db.init_app(app)
#API Endpoints
api.add_resource(CatAPI, "/cats/<int:cat_id>")
with app.app_context():
db.create_all()
#Debug tools
if app.debug:
DebugToolbarExtension(app)
if app.config.get("PROFILE", False):
app.wsgi_app = ProfilerMiddleware(app.wsgi_app,
restrictions=[30],
sort_by=("time", "cumulative"))
return app
sentry = Sentry()
<commit_msg>Move flask-restful api defs before init_app, since it doesn't work
otherwise with new version of flask-restful<commit_after>from flask import Flask
from raven.contrib.flask import Sentry
from flask_debugtoolbar import DebugToolbarExtension
from werkzeug.contrib.profiler import ProfilerMiddleware
from {{cookiecutter.app_name}}.views import CatAPI
from {{cookiecutter.app_name}}.views import api, cache
from {{cookiecutter.app_name}}.models import db
def create_app(config={}):
app = Flask("{{cookiecutter.app_name}}")
app.config.from_envvar("FLASK_CONFIG")
app.config.update(config)
#API Endpoints
api.add_resource(CatAPI, "/cats/<int:cat_id>")
#External
sentry.init_app(app)
api.init_app(app)
cache.init_app(app)
#Internal
db.init_app(app)
with app.app_context():
db.create_all()
#Debug tools
if app.debug:
DebugToolbarExtension(app)
if app.config.get("PROFILE", False):
app.wsgi_app = ProfilerMiddleware(app.wsgi_app,
restrictions=[30],
sort_by=("time", "cumulative"))
return app
sentry = Sentry()
|
3899893177f6d149d638ad5ae32c2135f0bfdcf2
|
startServers.py
|
startServers.py
|
import sys
import time
import subprocess
def main(baseCommand, startingPort, count):
procs = []
for i in range(1,count + 1):
command = baseCommand + ' ' + str(startingPort + i)
if sys.platform.startswith('win'):
process = subprocess.Popen(command, creationflags=subprocess.CREATE_NEW_CONSOLE)
else:
linuxCommand = 'xterm -hold -e "%s"' % command
process = subprocess.Popen(linuxCommand, shell=True)
procs.append(process)
time.sleep(3)
try:
input('Enter to exit from Python script...')
except:
pass
if __name__ == '__main__':
print sys.argv
main(sys.argv[1], int(sys.argv[2]), int(sys.argv[3]))
|
import sys
import time
import subprocess
import psutil
def startServer(command):
if sys.platform.startswith('win'):
return psutil.Popen(command, creationflags=subprocess.CREATE_NEW_CONSOLE)
else:
linuxCommand = 'xterm -hold -e "%s"' % command
return psutil.Popen(linuxCommand, shell=True)
def main(baseCommand, startingPort, count):
servers = {}
for i in range(1,count + 1):
command = baseCommand + ' ' + str(startingPort + i)
servers[i] = {
'command': command,
'process': startServer(command),
}
time.sleep(3)
while True:
for i, server in servers.iteritems():
if not server['process'].is_running():
servers[i]['process'] = startServer(servers[i]['command'])
if __name__ == '__main__':
print sys.argv
main(sys.argv[1], int(sys.argv[2]), int(sys.argv[3]))
|
Revert "Revert "keep servers running for fun and profit""
|
Revert "Revert "keep servers running for fun and profit""
This reverts commit cc7253020251bc96d7d7f22a991b094a60bbc104.
|
Python
|
mit
|
IngenuityEngine/coren_proxy,IngenuityEngine/coren_proxy
|
import sys
import time
import subprocess
def main(baseCommand, startingPort, count):
procs = []
for i in range(1,count + 1):
command = baseCommand + ' ' + str(startingPort + i)
if sys.platform.startswith('win'):
process = subprocess.Popen(command, creationflags=subprocess.CREATE_NEW_CONSOLE)
else:
linuxCommand = 'xterm -hold -e "%s"' % command
process = subprocess.Popen(linuxCommand, shell=True)
procs.append(process)
time.sleep(3)
try:
input('Enter to exit from Python script...')
except:
pass
if __name__ == '__main__':
print sys.argv
main(sys.argv[1], int(sys.argv[2]), int(sys.argv[3]))
Revert "Revert "keep servers running for fun and profit""
This reverts commit cc7253020251bc96d7d7f22a991b094a60bbc104.
|
import sys
import time
import subprocess
import psutil
def startServer(command):
if sys.platform.startswith('win'):
return psutil.Popen(command, creationflags=subprocess.CREATE_NEW_CONSOLE)
else:
linuxCommand = 'xterm -hold -e "%s"' % command
return psutil.Popen(linuxCommand, shell=True)
def main(baseCommand, startingPort, count):
servers = {}
for i in range(1,count + 1):
command = baseCommand + ' ' + str(startingPort + i)
servers[i] = {
'command': command,
'process': startServer(command),
}
time.sleep(3)
while True:
for i, server in servers.iteritems():
if not server['process'].is_running():
servers[i]['process'] = startServer(servers[i]['command'])
if __name__ == '__main__':
print sys.argv
main(sys.argv[1], int(sys.argv[2]), int(sys.argv[3]))
|
<commit_before>
import sys
import time
import subprocess
def main(baseCommand, startingPort, count):
procs = []
for i in range(1,count + 1):
command = baseCommand + ' ' + str(startingPort + i)
if sys.platform.startswith('win'):
process = subprocess.Popen(command, creationflags=subprocess.CREATE_NEW_CONSOLE)
else:
linuxCommand = 'xterm -hold -e "%s"' % command
process = subprocess.Popen(linuxCommand, shell=True)
procs.append(process)
time.sleep(3)
try:
input('Enter to exit from Python script...')
except:
pass
if __name__ == '__main__':
print sys.argv
main(sys.argv[1], int(sys.argv[2]), int(sys.argv[3]))
<commit_msg>Revert "Revert "keep servers running for fun and profit""
This reverts commit cc7253020251bc96d7d7f22a991b094a60bbc104.<commit_after>
|
import sys
import time
import subprocess
import psutil
def startServer(command):
if sys.platform.startswith('win'):
return psutil.Popen(command, creationflags=subprocess.CREATE_NEW_CONSOLE)
else:
linuxCommand = 'xterm -hold -e "%s"' % command
return psutil.Popen(linuxCommand, shell=True)
def main(baseCommand, startingPort, count):
servers = {}
for i in range(1,count + 1):
command = baseCommand + ' ' + str(startingPort + i)
servers[i] = {
'command': command,
'process': startServer(command),
}
time.sleep(3)
while True:
for i, server in servers.iteritems():
if not server['process'].is_running():
servers[i]['process'] = startServer(servers[i]['command'])
if __name__ == '__main__':
print sys.argv
main(sys.argv[1], int(sys.argv[2]), int(sys.argv[3]))
|
import sys
import time
import subprocess
def main(baseCommand, startingPort, count):
procs = []
for i in range(1,count + 1):
command = baseCommand + ' ' + str(startingPort + i)
if sys.platform.startswith('win'):
process = subprocess.Popen(command, creationflags=subprocess.CREATE_NEW_CONSOLE)
else:
linuxCommand = 'xterm -hold -e "%s"' % command
process = subprocess.Popen(linuxCommand, shell=True)
procs.append(process)
time.sleep(3)
try:
input('Enter to exit from Python script...')
except:
pass
if __name__ == '__main__':
print sys.argv
main(sys.argv[1], int(sys.argv[2]), int(sys.argv[3]))
Revert "Revert "keep servers running for fun and profit""
This reverts commit cc7253020251bc96d7d7f22a991b094a60bbc104.
import sys
import time
import subprocess
import psutil
def startServer(command):
if sys.platform.startswith('win'):
return psutil.Popen(command, creationflags=subprocess.CREATE_NEW_CONSOLE)
else:
linuxCommand = 'xterm -hold -e "%s"' % command
return psutil.Popen(linuxCommand, shell=True)
def main(baseCommand, startingPort, count):
servers = {}
for i in range(1,count + 1):
command = baseCommand + ' ' + str(startingPort + i)
servers[i] = {
'command': command,
'process': startServer(command),
}
time.sleep(3)
while True:
for i, server in servers.iteritems():
if not server['process'].is_running():
servers[i]['process'] = startServer(servers[i]['command'])
if __name__ == '__main__':
print sys.argv
main(sys.argv[1], int(sys.argv[2]), int(sys.argv[3]))
|
<commit_before>
import sys
import time
import subprocess
def main(baseCommand, startingPort, count):
procs = []
for i in range(1,count + 1):
command = baseCommand + ' ' + str(startingPort + i)
if sys.platform.startswith('win'):
process = subprocess.Popen(command, creationflags=subprocess.CREATE_NEW_CONSOLE)
else:
linuxCommand = 'xterm -hold -e "%s"' % command
process = subprocess.Popen(linuxCommand, shell=True)
procs.append(process)
time.sleep(3)
try:
input('Enter to exit from Python script...')
except:
pass
if __name__ == '__main__':
print sys.argv
main(sys.argv[1], int(sys.argv[2]), int(sys.argv[3]))
<commit_msg>Revert "Revert "keep servers running for fun and profit""
This reverts commit cc7253020251bc96d7d7f22a991b094a60bbc104.<commit_after>
import sys
import time
import subprocess
import psutil
def startServer(command):
if sys.platform.startswith('win'):
return psutil.Popen(command, creationflags=subprocess.CREATE_NEW_CONSOLE)
else:
linuxCommand = 'xterm -hold -e "%s"' % command
return psutil.Popen(linuxCommand, shell=True)
def main(baseCommand, startingPort, count):
servers = {}
for i in range(1,count + 1):
command = baseCommand + ' ' + str(startingPort + i)
servers[i] = {
'command': command,
'process': startServer(command),
}
time.sleep(3)
while True:
for i, server in servers.iteritems():
if not server['process'].is_running():
servers[i]['process'] = startServer(servers[i]['command'])
if __name__ == '__main__':
print sys.argv
main(sys.argv[1], int(sys.argv[2]), int(sys.argv[3]))
|
d52b47eaad73f818974b7feec83fa3b15ddb5aac
|
form_utils_bootstrap3/tests/__init__.py
|
form_utils_bootstrap3/tests/__init__.py
|
import os
import django
from django.conf import settings
if not settings.configured:
settings_dict = dict(
INSTALLED_APPS=[
'django.contrib.contenttypes',
'django.contrib.auth',
'bootstrap3',
'form_utils',
],
DATABASES={
"default": {
"ENGINE": "django.db.backends.sqlite3",
}
},
MEDIA_ROOT=os.path.join(os.path.dirname(__file__), 'media'),
MEDIA_URL='/media/',
STATIC_URL='/static/',
MIDDLEWARE_CLASSES=[],
BOOTSTRAP3={
'form_renderers': {
'default': 'form_utils_bootstrap3.renderers.BetterFormRenderer'
}
}
)
settings.configure(**settings_dict)
if django.VERSION >= (1, 7):
django.setup()
|
import os
import django
from django.conf import settings
if not settings.configured:
settings_dict = dict(
INSTALLED_APPS=[
'django.contrib.contenttypes',
'django.contrib.auth',
'bootstrap3',
'form_utils',
],
DATABASES={
"default": {
"ENGINE": "django.db.backends.sqlite3",
}
},
MEDIA_ROOT=os.path.join(os.path.dirname(__file__), 'media'),
MEDIA_URL='/media/',
STATIC_URL='/static/',
MIDDLEWARE_CLASSES=[],
BOOTSTRAP3={
'form_renderers': {
'default': 'form_utils_bootstrap3.renderers.BetterFormRenderer'
}
}
)
if django.VERSION >= (1, 8):
settings_dict['TEMPLATES'] = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': []
}
]
settings.configure(**settings_dict)
if django.VERSION >= (1, 7):
django.setup()
|
Fix tests for Django trunk
|
Fix tests for Django trunk
|
Python
|
mit
|
federicobond/django-form-utils-bootstrap3
|
import os
import django
from django.conf import settings
if not settings.configured:
settings_dict = dict(
INSTALLED_APPS=[
'django.contrib.contenttypes',
'django.contrib.auth',
'bootstrap3',
'form_utils',
],
DATABASES={
"default": {
"ENGINE": "django.db.backends.sqlite3",
}
},
MEDIA_ROOT=os.path.join(os.path.dirname(__file__), 'media'),
MEDIA_URL='/media/',
STATIC_URL='/static/',
MIDDLEWARE_CLASSES=[],
BOOTSTRAP3={
'form_renderers': {
'default': 'form_utils_bootstrap3.renderers.BetterFormRenderer'
}
}
)
settings.configure(**settings_dict)
if django.VERSION >= (1, 7):
django.setup()
Fix tests for Django trunk
|
import os
import django
from django.conf import settings
if not settings.configured:
settings_dict = dict(
INSTALLED_APPS=[
'django.contrib.contenttypes',
'django.contrib.auth',
'bootstrap3',
'form_utils',
],
DATABASES={
"default": {
"ENGINE": "django.db.backends.sqlite3",
}
},
MEDIA_ROOT=os.path.join(os.path.dirname(__file__), 'media'),
MEDIA_URL='/media/',
STATIC_URL='/static/',
MIDDLEWARE_CLASSES=[],
BOOTSTRAP3={
'form_renderers': {
'default': 'form_utils_bootstrap3.renderers.BetterFormRenderer'
}
}
)
if django.VERSION >= (1, 8):
settings_dict['TEMPLATES'] = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': []
}
]
settings.configure(**settings_dict)
if django.VERSION >= (1, 7):
django.setup()
|
<commit_before>import os
import django
from django.conf import settings
if not settings.configured:
settings_dict = dict(
INSTALLED_APPS=[
'django.contrib.contenttypes',
'django.contrib.auth',
'bootstrap3',
'form_utils',
],
DATABASES={
"default": {
"ENGINE": "django.db.backends.sqlite3",
}
},
MEDIA_ROOT=os.path.join(os.path.dirname(__file__), 'media'),
MEDIA_URL='/media/',
STATIC_URL='/static/',
MIDDLEWARE_CLASSES=[],
BOOTSTRAP3={
'form_renderers': {
'default': 'form_utils_bootstrap3.renderers.BetterFormRenderer'
}
}
)
settings.configure(**settings_dict)
if django.VERSION >= (1, 7):
django.setup()
<commit_msg>Fix tests for Django trunk<commit_after>
|
import os
import django
from django.conf import settings
if not settings.configured:
settings_dict = dict(
INSTALLED_APPS=[
'django.contrib.contenttypes',
'django.contrib.auth',
'bootstrap3',
'form_utils',
],
DATABASES={
"default": {
"ENGINE": "django.db.backends.sqlite3",
}
},
MEDIA_ROOT=os.path.join(os.path.dirname(__file__), 'media'),
MEDIA_URL='/media/',
STATIC_URL='/static/',
MIDDLEWARE_CLASSES=[],
BOOTSTRAP3={
'form_renderers': {
'default': 'form_utils_bootstrap3.renderers.BetterFormRenderer'
}
}
)
if django.VERSION >= (1, 8):
settings_dict['TEMPLATES'] = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': []
}
]
settings.configure(**settings_dict)
if django.VERSION >= (1, 7):
django.setup()
|
import os
import django
from django.conf import settings
if not settings.configured:
settings_dict = dict(
INSTALLED_APPS=[
'django.contrib.contenttypes',
'django.contrib.auth',
'bootstrap3',
'form_utils',
],
DATABASES={
"default": {
"ENGINE": "django.db.backends.sqlite3",
}
},
MEDIA_ROOT=os.path.join(os.path.dirname(__file__), 'media'),
MEDIA_URL='/media/',
STATIC_URL='/static/',
MIDDLEWARE_CLASSES=[],
BOOTSTRAP3={
'form_renderers': {
'default': 'form_utils_bootstrap3.renderers.BetterFormRenderer'
}
}
)
settings.configure(**settings_dict)
if django.VERSION >= (1, 7):
django.setup()
Fix tests for Django trunkimport os
import django
from django.conf import settings
if not settings.configured:
settings_dict = dict(
INSTALLED_APPS=[
'django.contrib.contenttypes',
'django.contrib.auth',
'bootstrap3',
'form_utils',
],
DATABASES={
"default": {
"ENGINE": "django.db.backends.sqlite3",
}
},
MEDIA_ROOT=os.path.join(os.path.dirname(__file__), 'media'),
MEDIA_URL='/media/',
STATIC_URL='/static/',
MIDDLEWARE_CLASSES=[],
BOOTSTRAP3={
'form_renderers': {
'default': 'form_utils_bootstrap3.renderers.BetterFormRenderer'
}
}
)
if django.VERSION >= (1, 8):
settings_dict['TEMPLATES'] = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': []
}
]
settings.configure(**settings_dict)
if django.VERSION >= (1, 7):
django.setup()
|
<commit_before>import os
import django
from django.conf import settings
if not settings.configured:
settings_dict = dict(
INSTALLED_APPS=[
'django.contrib.contenttypes',
'django.contrib.auth',
'bootstrap3',
'form_utils',
],
DATABASES={
"default": {
"ENGINE": "django.db.backends.sqlite3",
}
},
MEDIA_ROOT=os.path.join(os.path.dirname(__file__), 'media'),
MEDIA_URL='/media/',
STATIC_URL='/static/',
MIDDLEWARE_CLASSES=[],
BOOTSTRAP3={
'form_renderers': {
'default': 'form_utils_bootstrap3.renderers.BetterFormRenderer'
}
}
)
settings.configure(**settings_dict)
if django.VERSION >= (1, 7):
django.setup()
<commit_msg>Fix tests for Django trunk<commit_after>import os
import django
from django.conf import settings
if not settings.configured:
settings_dict = dict(
INSTALLED_APPS=[
'django.contrib.contenttypes',
'django.contrib.auth',
'bootstrap3',
'form_utils',
],
DATABASES={
"default": {
"ENGINE": "django.db.backends.sqlite3",
}
},
MEDIA_ROOT=os.path.join(os.path.dirname(__file__), 'media'),
MEDIA_URL='/media/',
STATIC_URL='/static/',
MIDDLEWARE_CLASSES=[],
BOOTSTRAP3={
'form_renderers': {
'default': 'form_utils_bootstrap3.renderers.BetterFormRenderer'
}
}
)
if django.VERSION >= (1, 8):
settings_dict['TEMPLATES'] = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': []
}
]
settings.configure(**settings_dict)
if django.VERSION >= (1, 7):
django.setup()
|
c0cc820b933913a3d5967d377f557a26ff21dcf7
|
tests/test_utils.py
|
tests/test_utils.py
|
from io import UnsupportedOperation
from pilkit.exceptions import UnknownFormat, UnknownExtension
from pilkit.utils import extension_to_format, format_to_extension, FileWrapper
from nose.tools import eq_, raises
def test_extension_to_format():
eq_(extension_to_format('.jpeg'), 'JPEG')
eq_(extension_to_format('.rgba'), 'SGI')
def test_format_to_extension_no_init():
eq_(format_to_extension('PNG'), '.png')
eq_(format_to_extension('ICO'), '.ico')
@raises(UnknownFormat)
def test_unknown_format():
format_to_extension('TXT')
@raises(UnknownExtension)
def test_unknown_extension():
extension_to_format('.txt')
def test_default_extension():
"""
Ensure default extensions are honored.
Since PIL's ``Image.EXTENSION`` lists ``'.jpe'`` before the more common
JPEG extensions, it would normally be the extension we'd get for that
format. ``pilkit.utils.DEFAULT_EXTENSIONS`` is our way of specifying which
extensions we'd prefer, and this tests to make sure it's working.
"""
eq_(format_to_extension('JPEG'), '.jpg')
@raises(AttributeError)
def test_filewrapper():
class K(object):
def fileno(self):
raise UnsupportedOperation
FileWrapper(K()).fileno()
|
from io import UnsupportedOperation
from pilkit.exceptions import UnknownFormat, UnknownExtension
from pilkit.utils import (extension_to_format, format_to_extension, FileWrapper,
save_image)
from nose.tools import eq_, raises
from tempfile import NamedTemporaryFile
from .utils import create_image
def test_extension_to_format():
eq_(extension_to_format('.jpeg'), 'JPEG')
eq_(extension_to_format('.rgba'), 'SGI')
def test_format_to_extension_no_init():
eq_(format_to_extension('PNG'), '.png')
eq_(format_to_extension('ICO'), '.ico')
@raises(UnknownFormat)
def test_unknown_format():
format_to_extension('TXT')
@raises(UnknownExtension)
def test_unknown_extension():
extension_to_format('.txt')
def test_default_extension():
"""
Ensure default extensions are honored.
Since PIL's ``Image.EXTENSION`` lists ``'.jpe'`` before the more common
JPEG extensions, it would normally be the extension we'd get for that
format. ``pilkit.utils.DEFAULT_EXTENSIONS`` is our way of specifying which
extensions we'd prefer, and this tests to make sure it's working.
"""
eq_(format_to_extension('JPEG'), '.jpg')
@raises(AttributeError)
def test_filewrapper():
class K(object):
def fileno(self):
raise UnsupportedOperation
FileWrapper(K()).fileno()
def test_save_with_filename():
"""
Test that ``save_image`` accepts filename strings (not just file objects).
This is a test for GH-8.
"""
im = create_image()
outfile = NamedTemporaryFile()
save_image(im, outfile.name, 'JPEG')
outfile.close()
|
Test that filename string can be used with save_image
|
Test that filename string can be used with save_image
|
Python
|
bsd-3-clause
|
kezabelle/pilkit,fladi/pilkit
|
from io import UnsupportedOperation
from pilkit.exceptions import UnknownFormat, UnknownExtension
from pilkit.utils import extension_to_format, format_to_extension, FileWrapper
from nose.tools import eq_, raises
def test_extension_to_format():
eq_(extension_to_format('.jpeg'), 'JPEG')
eq_(extension_to_format('.rgba'), 'SGI')
def test_format_to_extension_no_init():
eq_(format_to_extension('PNG'), '.png')
eq_(format_to_extension('ICO'), '.ico')
@raises(UnknownFormat)
def test_unknown_format():
format_to_extension('TXT')
@raises(UnknownExtension)
def test_unknown_extension():
extension_to_format('.txt')
def test_default_extension():
"""
Ensure default extensions are honored.
Since PIL's ``Image.EXTENSION`` lists ``'.jpe'`` before the more common
JPEG extensions, it would normally be the extension we'd get for that
format. ``pilkit.utils.DEFAULT_EXTENSIONS`` is our way of specifying which
extensions we'd prefer, and this tests to make sure it's working.
"""
eq_(format_to_extension('JPEG'), '.jpg')
@raises(AttributeError)
def test_filewrapper():
class K(object):
def fileno(self):
raise UnsupportedOperation
FileWrapper(K()).fileno()
Test that filename string can be used with save_image
|
from io import UnsupportedOperation
from pilkit.exceptions import UnknownFormat, UnknownExtension
from pilkit.utils import (extension_to_format, format_to_extension, FileWrapper,
save_image)
from nose.tools import eq_, raises
from tempfile import NamedTemporaryFile
from .utils import create_image
def test_extension_to_format():
eq_(extension_to_format('.jpeg'), 'JPEG')
eq_(extension_to_format('.rgba'), 'SGI')
def test_format_to_extension_no_init():
eq_(format_to_extension('PNG'), '.png')
eq_(format_to_extension('ICO'), '.ico')
@raises(UnknownFormat)
def test_unknown_format():
format_to_extension('TXT')
@raises(UnknownExtension)
def test_unknown_extension():
extension_to_format('.txt')
def test_default_extension():
"""
Ensure default extensions are honored.
Since PIL's ``Image.EXTENSION`` lists ``'.jpe'`` before the more common
JPEG extensions, it would normally be the extension we'd get for that
format. ``pilkit.utils.DEFAULT_EXTENSIONS`` is our way of specifying which
extensions we'd prefer, and this tests to make sure it's working.
"""
eq_(format_to_extension('JPEG'), '.jpg')
@raises(AttributeError)
def test_filewrapper():
class K(object):
def fileno(self):
raise UnsupportedOperation
FileWrapper(K()).fileno()
def test_save_with_filename():
"""
Test that ``save_image`` accepts filename strings (not just file objects).
This is a test for GH-8.
"""
im = create_image()
outfile = NamedTemporaryFile()
save_image(im, outfile.name, 'JPEG')
outfile.close()
|
<commit_before>from io import UnsupportedOperation
from pilkit.exceptions import UnknownFormat, UnknownExtension
from pilkit.utils import extension_to_format, format_to_extension, FileWrapper
from nose.tools import eq_, raises
def test_extension_to_format():
eq_(extension_to_format('.jpeg'), 'JPEG')
eq_(extension_to_format('.rgba'), 'SGI')
def test_format_to_extension_no_init():
eq_(format_to_extension('PNG'), '.png')
eq_(format_to_extension('ICO'), '.ico')
@raises(UnknownFormat)
def test_unknown_format():
format_to_extension('TXT')
@raises(UnknownExtension)
def test_unknown_extension():
extension_to_format('.txt')
def test_default_extension():
"""
Ensure default extensions are honored.
Since PIL's ``Image.EXTENSION`` lists ``'.jpe'`` before the more common
JPEG extensions, it would normally be the extension we'd get for that
format. ``pilkit.utils.DEFAULT_EXTENSIONS`` is our way of specifying which
extensions we'd prefer, and this tests to make sure it's working.
"""
eq_(format_to_extension('JPEG'), '.jpg')
@raises(AttributeError)
def test_filewrapper():
class K(object):
def fileno(self):
raise UnsupportedOperation
FileWrapper(K()).fileno()
<commit_msg>Test that filename string can be used with save_image<commit_after>
|
from io import UnsupportedOperation
from pilkit.exceptions import UnknownFormat, UnknownExtension
from pilkit.utils import (extension_to_format, format_to_extension, FileWrapper,
save_image)
from nose.tools import eq_, raises
from tempfile import NamedTemporaryFile
from .utils import create_image
def test_extension_to_format():
eq_(extension_to_format('.jpeg'), 'JPEG')
eq_(extension_to_format('.rgba'), 'SGI')
def test_format_to_extension_no_init():
eq_(format_to_extension('PNG'), '.png')
eq_(format_to_extension('ICO'), '.ico')
@raises(UnknownFormat)
def test_unknown_format():
format_to_extension('TXT')
@raises(UnknownExtension)
def test_unknown_extension():
extension_to_format('.txt')
def test_default_extension():
"""
Ensure default extensions are honored.
Since PIL's ``Image.EXTENSION`` lists ``'.jpe'`` before the more common
JPEG extensions, it would normally be the extension we'd get for that
format. ``pilkit.utils.DEFAULT_EXTENSIONS`` is our way of specifying which
extensions we'd prefer, and this tests to make sure it's working.
"""
eq_(format_to_extension('JPEG'), '.jpg')
@raises(AttributeError)
def test_filewrapper():
class K(object):
def fileno(self):
raise UnsupportedOperation
FileWrapper(K()).fileno()
def test_save_with_filename():
"""
Test that ``save_image`` accepts filename strings (not just file objects).
This is a test for GH-8.
"""
im = create_image()
outfile = NamedTemporaryFile()
save_image(im, outfile.name, 'JPEG')
outfile.close()
|
from io import UnsupportedOperation
from pilkit.exceptions import UnknownFormat, UnknownExtension
from pilkit.utils import extension_to_format, format_to_extension, FileWrapper
from nose.tools import eq_, raises
def test_extension_to_format():
eq_(extension_to_format('.jpeg'), 'JPEG')
eq_(extension_to_format('.rgba'), 'SGI')
def test_format_to_extension_no_init():
eq_(format_to_extension('PNG'), '.png')
eq_(format_to_extension('ICO'), '.ico')
@raises(UnknownFormat)
def test_unknown_format():
format_to_extension('TXT')
@raises(UnknownExtension)
def test_unknown_extension():
extension_to_format('.txt')
def test_default_extension():
"""
Ensure default extensions are honored.
Since PIL's ``Image.EXTENSION`` lists ``'.jpe'`` before the more common
JPEG extensions, it would normally be the extension we'd get for that
format. ``pilkit.utils.DEFAULT_EXTENSIONS`` is our way of specifying which
extensions we'd prefer, and this tests to make sure it's working.
"""
eq_(format_to_extension('JPEG'), '.jpg')
@raises(AttributeError)
def test_filewrapper():
class K(object):
def fileno(self):
raise UnsupportedOperation
FileWrapper(K()).fileno()
Test that filename string can be used with save_imagefrom io import UnsupportedOperation
from pilkit.exceptions import UnknownFormat, UnknownExtension
from pilkit.utils import (extension_to_format, format_to_extension, FileWrapper,
save_image)
from nose.tools import eq_, raises
from tempfile import NamedTemporaryFile
from .utils import create_image
def test_extension_to_format():
eq_(extension_to_format('.jpeg'), 'JPEG')
eq_(extension_to_format('.rgba'), 'SGI')
def test_format_to_extension_no_init():
eq_(format_to_extension('PNG'), '.png')
eq_(format_to_extension('ICO'), '.ico')
@raises(UnknownFormat)
def test_unknown_format():
format_to_extension('TXT')
@raises(UnknownExtension)
def test_unknown_extension():
extension_to_format('.txt')
def test_default_extension():
"""
Ensure default extensions are honored.
Since PIL's ``Image.EXTENSION`` lists ``'.jpe'`` before the more common
JPEG extensions, it would normally be the extension we'd get for that
format. ``pilkit.utils.DEFAULT_EXTENSIONS`` is our way of specifying which
extensions we'd prefer, and this tests to make sure it's working.
"""
eq_(format_to_extension('JPEG'), '.jpg')
@raises(AttributeError)
def test_filewrapper():
class K(object):
def fileno(self):
raise UnsupportedOperation
FileWrapper(K()).fileno()
def test_save_with_filename():
"""
Test that ``save_image`` accepts filename strings (not just file objects).
This is a test for GH-8.
"""
im = create_image()
outfile = NamedTemporaryFile()
save_image(im, outfile.name, 'JPEG')
outfile.close()
|
<commit_before>from io import UnsupportedOperation
from pilkit.exceptions import UnknownFormat, UnknownExtension
from pilkit.utils import extension_to_format, format_to_extension, FileWrapper
from nose.tools import eq_, raises
def test_extension_to_format():
eq_(extension_to_format('.jpeg'), 'JPEG')
eq_(extension_to_format('.rgba'), 'SGI')
def test_format_to_extension_no_init():
eq_(format_to_extension('PNG'), '.png')
eq_(format_to_extension('ICO'), '.ico')
@raises(UnknownFormat)
def test_unknown_format():
format_to_extension('TXT')
@raises(UnknownExtension)
def test_unknown_extension():
extension_to_format('.txt')
def test_default_extension():
"""
Ensure default extensions are honored.
Since PIL's ``Image.EXTENSION`` lists ``'.jpe'`` before the more common
JPEG extensions, it would normally be the extension we'd get for that
format. ``pilkit.utils.DEFAULT_EXTENSIONS`` is our way of specifying which
extensions we'd prefer, and this tests to make sure it's working.
"""
eq_(format_to_extension('JPEG'), '.jpg')
@raises(AttributeError)
def test_filewrapper():
class K(object):
def fileno(self):
raise UnsupportedOperation
FileWrapper(K()).fileno()
<commit_msg>Test that filename string can be used with save_image<commit_after>from io import UnsupportedOperation
from pilkit.exceptions import UnknownFormat, UnknownExtension
from pilkit.utils import (extension_to_format, format_to_extension, FileWrapper,
save_image)
from nose.tools import eq_, raises
from tempfile import NamedTemporaryFile
from .utils import create_image
def test_extension_to_format():
eq_(extension_to_format('.jpeg'), 'JPEG')
eq_(extension_to_format('.rgba'), 'SGI')
def test_format_to_extension_no_init():
eq_(format_to_extension('PNG'), '.png')
eq_(format_to_extension('ICO'), '.ico')
@raises(UnknownFormat)
def test_unknown_format():
format_to_extension('TXT')
@raises(UnknownExtension)
def test_unknown_extension():
extension_to_format('.txt')
def test_default_extension():
"""
Ensure default extensions are honored.
Since PIL's ``Image.EXTENSION`` lists ``'.jpe'`` before the more common
JPEG extensions, it would normally be the extension we'd get for that
format. ``pilkit.utils.DEFAULT_EXTENSIONS`` is our way of specifying which
extensions we'd prefer, and this tests to make sure it's working.
"""
eq_(format_to_extension('JPEG'), '.jpg')
@raises(AttributeError)
def test_filewrapper():
class K(object):
def fileno(self):
raise UnsupportedOperation
FileWrapper(K()).fileno()
def test_save_with_filename():
"""
Test that ``save_image`` accepts filename strings (not just file objects).
This is a test for GH-8.
"""
im = create_image()
outfile = NamedTemporaryFile()
save_image(im, outfile.name, 'JPEG')
outfile.close()
|
3579bf97ae6b4232e063babcedf3c0ba2a813d41
|
mapclientplugins/heartsurfacesegmenterstep/__init__.py
|
mapclientplugins/heartsurfacesegmenterstep/__init__.py
|
'''
MAP Client Plugin
'''
__version__ = '0.1.0'
__author__ = 'Hugh Sorby'
__stepname__ = 'Heart Surface'
__location__ = 'https://github.com/mapclient-plugins/heartsurfacesegmenter/archive/master.zip'
# import class that derives itself from the step mountpoint.
from mapclientplugins.heartsurfacesegmenterstep import step
|
'''
MAP Client Plugin
'''
__version__ = '0.1.0'
__author__ = 'Hugh Sorby'
__stepname__ = 'Heart Surface'
__location__ = 'https://github.com/mapclient-plugins/heartsurfacesegmenter/archive/v0.1.0.zip'
# import class that derives itself from the step mountpoint.
from mapclientplugins.heartsurfacesegmenterstep import step
|
Set location of source code to version tag.
|
Set location of source code to version tag.
|
Python
|
apache-2.0
|
mapclient-plugins/heartsurfacesegmenter
|
'''
MAP Client Plugin
'''
__version__ = '0.1.0'
__author__ = 'Hugh Sorby'
__stepname__ = 'Heart Surface'
__location__ = 'https://github.com/mapclient-plugins/heartsurfacesegmenter/archive/master.zip'
# import class that derives itself from the step mountpoint.
from mapclientplugins.heartsurfacesegmenterstep import step
Set location of source code to version tag.
|
'''
MAP Client Plugin
'''
__version__ = '0.1.0'
__author__ = 'Hugh Sorby'
__stepname__ = 'Heart Surface'
__location__ = 'https://github.com/mapclient-plugins/heartsurfacesegmenter/archive/v0.1.0.zip'
# import class that derives itself from the step mountpoint.
from mapclientplugins.heartsurfacesegmenterstep import step
|
<commit_before>
'''
MAP Client Plugin
'''
__version__ = '0.1.0'
__author__ = 'Hugh Sorby'
__stepname__ = 'Heart Surface'
__location__ = 'https://github.com/mapclient-plugins/heartsurfacesegmenter/archive/master.zip'
# import class that derives itself from the step mountpoint.
from mapclientplugins.heartsurfacesegmenterstep import step
<commit_msg>Set location of source code to version tag.<commit_after>
|
'''
MAP Client Plugin
'''
__version__ = '0.1.0'
__author__ = 'Hugh Sorby'
__stepname__ = 'Heart Surface'
__location__ = 'https://github.com/mapclient-plugins/heartsurfacesegmenter/archive/v0.1.0.zip'
# import class that derives itself from the step mountpoint.
from mapclientplugins.heartsurfacesegmenterstep import step
|
'''
MAP Client Plugin
'''
__version__ = '0.1.0'
__author__ = 'Hugh Sorby'
__stepname__ = 'Heart Surface'
__location__ = 'https://github.com/mapclient-plugins/heartsurfacesegmenter/archive/master.zip'
# import class that derives itself from the step mountpoint.
from mapclientplugins.heartsurfacesegmenterstep import step
Set location of source code to version tag.
'''
MAP Client Plugin
'''
__version__ = '0.1.0'
__author__ = 'Hugh Sorby'
__stepname__ = 'Heart Surface'
__location__ = 'https://github.com/mapclient-plugins/heartsurfacesegmenter/archive/v0.1.0.zip'
# import class that derives itself from the step mountpoint.
from mapclientplugins.heartsurfacesegmenterstep import step
|
<commit_before>
'''
MAP Client Plugin
'''
__version__ = '0.1.0'
__author__ = 'Hugh Sorby'
__stepname__ = 'Heart Surface'
__location__ = 'https://github.com/mapclient-plugins/heartsurfacesegmenter/archive/master.zip'
# import class that derives itself from the step mountpoint.
from mapclientplugins.heartsurfacesegmenterstep import step
<commit_msg>Set location of source code to version tag.<commit_after>
'''
MAP Client Plugin
'''
__version__ = '0.1.0'
__author__ = 'Hugh Sorby'
__stepname__ = 'Heart Surface'
__location__ = 'https://github.com/mapclient-plugins/heartsurfacesegmenter/archive/v0.1.0.zip'
# import class that derives itself from the step mountpoint.
from mapclientplugins.heartsurfacesegmenterstep import step
|
99d0f754b39bdddf58e44e669d24157227a43107
|
heliotron/__init__.py
|
heliotron/__init__.py
|
#from requests import get
from heliotron.bridge import Bridge
from heliotron.light import Light
import heliotron.presets
__all__ = ['Bridge', 'Light', 'presets']
|
#from requests import get
from heliotron.bridge import Bridge
from heliotron.light import Light
from heliotron import presets
__all__ = ['Bridge', 'Light', 'presets']
|
Change module import to squash a code smell
|
Change module import to squash a code smell
|
Python
|
mit
|
briancline/heliotron
|
#from requests import get
from heliotron.bridge import Bridge
from heliotron.light import Light
import heliotron.presets
__all__ = ['Bridge', 'Light', 'presets']
Change module import to squash a code smell
|
#from requests import get
from heliotron.bridge import Bridge
from heliotron.light import Light
from heliotron import presets
__all__ = ['Bridge', 'Light', 'presets']
|
<commit_before>#from requests import get
from heliotron.bridge import Bridge
from heliotron.light import Light
import heliotron.presets
__all__ = ['Bridge', 'Light', 'presets']
<commit_msg>Change module import to squash a code smell<commit_after>
|
#from requests import get
from heliotron.bridge import Bridge
from heliotron.light import Light
from heliotron import presets
__all__ = ['Bridge', 'Light', 'presets']
|
#from requests import get
from heliotron.bridge import Bridge
from heliotron.light import Light
import heliotron.presets
__all__ = ['Bridge', 'Light', 'presets']
Change module import to squash a code smell#from requests import get
from heliotron.bridge import Bridge
from heliotron.light import Light
from heliotron import presets
__all__ = ['Bridge', 'Light', 'presets']
|
<commit_before>#from requests import get
from heliotron.bridge import Bridge
from heliotron.light import Light
import heliotron.presets
__all__ = ['Bridge', 'Light', 'presets']
<commit_msg>Change module import to squash a code smell<commit_after>#from requests import get
from heliotron.bridge import Bridge
from heliotron.light import Light
from heliotron import presets
__all__ = ['Bridge', 'Light', 'presets']
|
20506c1463c1be9639bceae1168ba97178280796
|
mrburns/main/tests.py
|
mrburns/main/tests.py
|
from django.test import TestCase
from nose.tools import ok_
from mrburns.main import views
class TestViewHelpers(TestCase):
def test_twitter_share_url_fn(self):
"""Should return a proper and endoded twitter share url."""
url = views.get_tw_share_url(url='http://example.com', text='The Dude abides.')
ok_(url.startswith(views.TWITTER_URL + '?'))
ok_('dnt=true' in url)
ok_('hashtags=firefox' in url)
ok_('url=http%3A%2F%2Fexample.com' in url)
ok_('text=The+Dude+abides.' in url)
def test_facebook_share_url_fn(self):
"""Should return a proper and encoded facebook share url."""
url = views.get_fb_share_url('http://example.com')
ok_(url.startswith(views.FB_URL + '?'))
ok_('u=http%3A%2F%2Fexample.com' in url)
|
from django.test import TestCase
from nose.tools import ok_
from mrburns.main import views
class TestViewHelpers(TestCase):
def test_twitter_share_url_fn(self):
"""Should return a proper and endoded twitter share url."""
url = views.get_tw_share_url(url='http://example.com', text='The Dude abides.',
hashtags='firefox')
ok_(url.startswith(views.TWITTER_URL + '?'))
ok_('dnt=true' in url)
ok_('hashtags=firefox' in url)
ok_('url=http%3A%2F%2Fexample.com' in url)
ok_('text=The+Dude+abides.' in url)
def test_facebook_share_url_fn(self):
"""Should return a proper and encoded facebook share url."""
url = views.get_fb_share_url('http://example.com')
ok_(url.startswith(views.FB_URL + '?'))
ok_('u=http%3A%2F%2Fexample.com' in url)
|
Fix twitter url helper test.
|
Fix twitter url helper test.
|
Python
|
mpl-2.0
|
almossawi/mrburns,almossawi/mrburns,mozilla/mrburns,mozilla/mrburns,mozilla/mrburns,almossawi/mrburns,almossawi/mrburns
|
from django.test import TestCase
from nose.tools import ok_
from mrburns.main import views
class TestViewHelpers(TestCase):
def test_twitter_share_url_fn(self):
"""Should return a proper and endoded twitter share url."""
url = views.get_tw_share_url(url='http://example.com', text='The Dude abides.')
ok_(url.startswith(views.TWITTER_URL + '?'))
ok_('dnt=true' in url)
ok_('hashtags=firefox' in url)
ok_('url=http%3A%2F%2Fexample.com' in url)
ok_('text=The+Dude+abides.' in url)
def test_facebook_share_url_fn(self):
"""Should return a proper and encoded facebook share url."""
url = views.get_fb_share_url('http://example.com')
ok_(url.startswith(views.FB_URL + '?'))
ok_('u=http%3A%2F%2Fexample.com' in url)
Fix twitter url helper test.
|
from django.test import TestCase
from nose.tools import ok_
from mrburns.main import views
class TestViewHelpers(TestCase):
def test_twitter_share_url_fn(self):
"""Should return a proper and endoded twitter share url."""
url = views.get_tw_share_url(url='http://example.com', text='The Dude abides.',
hashtags='firefox')
ok_(url.startswith(views.TWITTER_URL + '?'))
ok_('dnt=true' in url)
ok_('hashtags=firefox' in url)
ok_('url=http%3A%2F%2Fexample.com' in url)
ok_('text=The+Dude+abides.' in url)
def test_facebook_share_url_fn(self):
"""Should return a proper and encoded facebook share url."""
url = views.get_fb_share_url('http://example.com')
ok_(url.startswith(views.FB_URL + '?'))
ok_('u=http%3A%2F%2Fexample.com' in url)
|
<commit_before>from django.test import TestCase
from nose.tools import ok_
from mrburns.main import views
class TestViewHelpers(TestCase):
def test_twitter_share_url_fn(self):
"""Should return a proper and endoded twitter share url."""
url = views.get_tw_share_url(url='http://example.com', text='The Dude abides.')
ok_(url.startswith(views.TWITTER_URL + '?'))
ok_('dnt=true' in url)
ok_('hashtags=firefox' in url)
ok_('url=http%3A%2F%2Fexample.com' in url)
ok_('text=The+Dude+abides.' in url)
def test_facebook_share_url_fn(self):
"""Should return a proper and encoded facebook share url."""
url = views.get_fb_share_url('http://example.com')
ok_(url.startswith(views.FB_URL + '?'))
ok_('u=http%3A%2F%2Fexample.com' in url)
<commit_msg>Fix twitter url helper test.<commit_after>
|
from django.test import TestCase
from nose.tools import ok_
from mrburns.main import views
class TestViewHelpers(TestCase):
def test_twitter_share_url_fn(self):
"""Should return a proper and endoded twitter share url."""
url = views.get_tw_share_url(url='http://example.com', text='The Dude abides.',
hashtags='firefox')
ok_(url.startswith(views.TWITTER_URL + '?'))
ok_('dnt=true' in url)
ok_('hashtags=firefox' in url)
ok_('url=http%3A%2F%2Fexample.com' in url)
ok_('text=The+Dude+abides.' in url)
def test_facebook_share_url_fn(self):
"""Should return a proper and encoded facebook share url."""
url = views.get_fb_share_url('http://example.com')
ok_(url.startswith(views.FB_URL + '?'))
ok_('u=http%3A%2F%2Fexample.com' in url)
|
from django.test import TestCase
from nose.tools import ok_
from mrburns.main import views
class TestViewHelpers(TestCase):
def test_twitter_share_url_fn(self):
"""Should return a proper and endoded twitter share url."""
url = views.get_tw_share_url(url='http://example.com', text='The Dude abides.')
ok_(url.startswith(views.TWITTER_URL + '?'))
ok_('dnt=true' in url)
ok_('hashtags=firefox' in url)
ok_('url=http%3A%2F%2Fexample.com' in url)
ok_('text=The+Dude+abides.' in url)
def test_facebook_share_url_fn(self):
"""Should return a proper and encoded facebook share url."""
url = views.get_fb_share_url('http://example.com')
ok_(url.startswith(views.FB_URL + '?'))
ok_('u=http%3A%2F%2Fexample.com' in url)
Fix twitter url helper test.from django.test import TestCase
from nose.tools import ok_
from mrburns.main import views
class TestViewHelpers(TestCase):
def test_twitter_share_url_fn(self):
"""Should return a proper and endoded twitter share url."""
url = views.get_tw_share_url(url='http://example.com', text='The Dude abides.',
hashtags='firefox')
ok_(url.startswith(views.TWITTER_URL + '?'))
ok_('dnt=true' in url)
ok_('hashtags=firefox' in url)
ok_('url=http%3A%2F%2Fexample.com' in url)
ok_('text=The+Dude+abides.' in url)
def test_facebook_share_url_fn(self):
"""Should return a proper and encoded facebook share url."""
url = views.get_fb_share_url('http://example.com')
ok_(url.startswith(views.FB_URL + '?'))
ok_('u=http%3A%2F%2Fexample.com' in url)
|
<commit_before>from django.test import TestCase
from nose.tools import ok_
from mrburns.main import views
class TestViewHelpers(TestCase):
def test_twitter_share_url_fn(self):
"""Should return a proper and endoded twitter share url."""
url = views.get_tw_share_url(url='http://example.com', text='The Dude abides.')
ok_(url.startswith(views.TWITTER_URL + '?'))
ok_('dnt=true' in url)
ok_('hashtags=firefox' in url)
ok_('url=http%3A%2F%2Fexample.com' in url)
ok_('text=The+Dude+abides.' in url)
def test_facebook_share_url_fn(self):
"""Should return a proper and encoded facebook share url."""
url = views.get_fb_share_url('http://example.com')
ok_(url.startswith(views.FB_URL + '?'))
ok_('u=http%3A%2F%2Fexample.com' in url)
<commit_msg>Fix twitter url helper test.<commit_after>from django.test import TestCase
from nose.tools import ok_
from mrburns.main import views
class TestViewHelpers(TestCase):
def test_twitter_share_url_fn(self):
"""Should return a proper and endoded twitter share url."""
url = views.get_tw_share_url(url='http://example.com', text='The Dude abides.',
hashtags='firefox')
ok_(url.startswith(views.TWITTER_URL + '?'))
ok_('dnt=true' in url)
ok_('hashtags=firefox' in url)
ok_('url=http%3A%2F%2Fexample.com' in url)
ok_('text=The+Dude+abides.' in url)
def test_facebook_share_url_fn(self):
"""Should return a proper and encoded facebook share url."""
url = views.get_fb_share_url('http://example.com')
ok_(url.startswith(views.FB_URL + '?'))
ok_('u=http%3A%2F%2Fexample.com' in url)
|
8f31a87ace324c519eac8d883cf0327d08f48df0
|
lib/ansiblelint/rules/VariableHasSpacesRule.py
|
lib/ansiblelint/rules/VariableHasSpacesRule.py
|
# Copyright (c) 2016, Will Thames and contributors
# Copyright (c) 2018, Ansible Project
from ansiblelint import AnsibleLintRule
import re
class VariableHasSpacesRule(AnsibleLintRule):
id = '206'
shortdesc = 'Variables should have spaces before and after: {{ var_name }}'
description = 'Variables should have spaces before and after: ``{{ var_name }}``'
severity = 'LOW'
tags = ['formatting']
version_added = 'v4.0.0'
variable_syntax = re.compile(r"{{.*}}")
bracket_regex = re.compile(r"{{[^{' -]|[^ '}-]}}")
def match(self, file, line):
if not self.variable_syntax.search(line):
return
return self.bracket_regex.search(line)
|
# Copyright (c) 2016, Will Thames and contributors
# Copyright (c) 2018, Ansible Project
from ansiblelint import AnsibleLintRule
import re
class VariableHasSpacesRule(AnsibleLintRule):
id = '206'
shortdesc = 'Variables should have spaces before and after: {{ var_name }}'
description = 'Variables should have spaces before and after: ``{{ var_name }}``'
severity = 'LOW'
tags = ['formatting']
version_added = 'v4.0.0'
variable_syntax = re.compile(r"{{.*}}")
bracket_regex = re.compile(r"{{[^{' -]|[^ '}-]}}")
def match(self, file, line):
if not self.variable_syntax.search(line):
return
line_exclude_json = re.sub(r"[^{]{'\w+': ?[^{]{.*?}}", "", line)
return self.bracket_regex.search(line_exclude_json)
|
Fix nested JSON obj false positive
|
var-space-rule: Fix nested JSON obj false positive
When using compact form nested JSON object within a
Jinja2 context as shown in the following example:
set_fact:"{{ {'test': {'subtest': variable}} }}"
'variable}}' will raise a false positive [206] error.
This commit adds an intermediate step within 206
(VariableHasSpacesRule.py) rule to exclude nested
JSON object before matching for an actual error.
Fixes: #665
Signed-off-by: Simon Kheng <765fd267c62104898c4dfafd2f027edd838d8b13@gmail.com>
|
Python
|
mit
|
willthames/ansible-lint
|
# Copyright (c) 2016, Will Thames and contributors
# Copyright (c) 2018, Ansible Project
from ansiblelint import AnsibleLintRule
import re
class VariableHasSpacesRule(AnsibleLintRule):
id = '206'
shortdesc = 'Variables should have spaces before and after: {{ var_name }}'
description = 'Variables should have spaces before and after: ``{{ var_name }}``'
severity = 'LOW'
tags = ['formatting']
version_added = 'v4.0.0'
variable_syntax = re.compile(r"{{.*}}")
bracket_regex = re.compile(r"{{[^{' -]|[^ '}-]}}")
def match(self, file, line):
if not self.variable_syntax.search(line):
return
return self.bracket_regex.search(line)
var-space-rule: Fix nested JSON obj false positive
When using compact form nested JSON object within a
Jinja2 context as shown in the following example:
set_fact:"{{ {'test': {'subtest': variable}} }}"
'variable}}' will raise a false positive [206] error.
This commit adds an intermediate step within 206
(VariableHasSpacesRule.py) rule to exclude nested
JSON object before matching for an actual error.
Fixes: #665
Signed-off-by: Simon Kheng <765fd267c62104898c4dfafd2f027edd838d8b13@gmail.com>
|
# Copyright (c) 2016, Will Thames and contributors
# Copyright (c) 2018, Ansible Project
from ansiblelint import AnsibleLintRule
import re
class VariableHasSpacesRule(AnsibleLintRule):
id = '206'
shortdesc = 'Variables should have spaces before and after: {{ var_name }}'
description = 'Variables should have spaces before and after: ``{{ var_name }}``'
severity = 'LOW'
tags = ['formatting']
version_added = 'v4.0.0'
variable_syntax = re.compile(r"{{.*}}")
bracket_regex = re.compile(r"{{[^{' -]|[^ '}-]}}")
def match(self, file, line):
if not self.variable_syntax.search(line):
return
line_exclude_json = re.sub(r"[^{]{'\w+': ?[^{]{.*?}}", "", line)
return self.bracket_regex.search(line_exclude_json)
|
<commit_before># Copyright (c) 2016, Will Thames and contributors
# Copyright (c) 2018, Ansible Project
from ansiblelint import AnsibleLintRule
import re
class VariableHasSpacesRule(AnsibleLintRule):
id = '206'
shortdesc = 'Variables should have spaces before and after: {{ var_name }}'
description = 'Variables should have spaces before and after: ``{{ var_name }}``'
severity = 'LOW'
tags = ['formatting']
version_added = 'v4.0.0'
variable_syntax = re.compile(r"{{.*}}")
bracket_regex = re.compile(r"{{[^{' -]|[^ '}-]}}")
def match(self, file, line):
if not self.variable_syntax.search(line):
return
return self.bracket_regex.search(line)
<commit_msg>var-space-rule: Fix nested JSON obj false positive
When using compact form nested JSON object within a
Jinja2 context as shown in the following example:
set_fact:"{{ {'test': {'subtest': variable}} }}"
'variable}}' will raise a false positive [206] error.
This commit adds an intermediate step within 206
(VariableHasSpacesRule.py) rule to exclude nested
JSON object before matching for an actual error.
Fixes: #665
Signed-off-by: Simon Kheng <765fd267c62104898c4dfafd2f027edd838d8b13@gmail.com><commit_after>
|
# Copyright (c) 2016, Will Thames and contributors
# Copyright (c) 2018, Ansible Project
from ansiblelint import AnsibleLintRule
import re
class VariableHasSpacesRule(AnsibleLintRule):
id = '206'
shortdesc = 'Variables should have spaces before and after: {{ var_name }}'
description = 'Variables should have spaces before and after: ``{{ var_name }}``'
severity = 'LOW'
tags = ['formatting']
version_added = 'v4.0.0'
variable_syntax = re.compile(r"{{.*}}")
bracket_regex = re.compile(r"{{[^{' -]|[^ '}-]}}")
def match(self, file, line):
if not self.variable_syntax.search(line):
return
line_exclude_json = re.sub(r"[^{]{'\w+': ?[^{]{.*?}}", "", line)
return self.bracket_regex.search(line_exclude_json)
|
# Copyright (c) 2016, Will Thames and contributors
# Copyright (c) 2018, Ansible Project
from ansiblelint import AnsibleLintRule
import re
class VariableHasSpacesRule(AnsibleLintRule):
id = '206'
shortdesc = 'Variables should have spaces before and after: {{ var_name }}'
description = 'Variables should have spaces before and after: ``{{ var_name }}``'
severity = 'LOW'
tags = ['formatting']
version_added = 'v4.0.0'
variable_syntax = re.compile(r"{{.*}}")
bracket_regex = re.compile(r"{{[^{' -]|[^ '}-]}}")
def match(self, file, line):
if not self.variable_syntax.search(line):
return
return self.bracket_regex.search(line)
var-space-rule: Fix nested JSON obj false positive
When using compact form nested JSON object within a
Jinja2 context as shown in the following example:
set_fact:"{{ {'test': {'subtest': variable}} }}"
'variable}}' will raise a false positive [206] error.
This commit adds an intermediate step within 206
(VariableHasSpacesRule.py) rule to exclude nested
JSON object before matching for an actual error.
Fixes: #665
Signed-off-by: Simon Kheng <765fd267c62104898c4dfafd2f027edd838d8b13@gmail.com># Copyright (c) 2016, Will Thames and contributors
# Copyright (c) 2018, Ansible Project
from ansiblelint import AnsibleLintRule
import re
class VariableHasSpacesRule(AnsibleLintRule):
id = '206'
shortdesc = 'Variables should have spaces before and after: {{ var_name }}'
description = 'Variables should have spaces before and after: ``{{ var_name }}``'
severity = 'LOW'
tags = ['formatting']
version_added = 'v4.0.0'
variable_syntax = re.compile(r"{{.*}}")
bracket_regex = re.compile(r"{{[^{' -]|[^ '}-]}}")
def match(self, file, line):
if not self.variable_syntax.search(line):
return
line_exclude_json = re.sub(r"[^{]{'\w+': ?[^{]{.*?}}", "", line)
return self.bracket_regex.search(line_exclude_json)
|
<commit_before># Copyright (c) 2016, Will Thames and contributors
# Copyright (c) 2018, Ansible Project
from ansiblelint import AnsibleLintRule
import re
class VariableHasSpacesRule(AnsibleLintRule):
id = '206'
shortdesc = 'Variables should have spaces before and after: {{ var_name }}'
description = 'Variables should have spaces before and after: ``{{ var_name }}``'
severity = 'LOW'
tags = ['formatting']
version_added = 'v4.0.0'
variable_syntax = re.compile(r"{{.*}}")
bracket_regex = re.compile(r"{{[^{' -]|[^ '}-]}}")
def match(self, file, line):
if not self.variable_syntax.search(line):
return
return self.bracket_regex.search(line)
<commit_msg>var-space-rule: Fix nested JSON obj false positive
When using compact form nested JSON object within a
Jinja2 context as shown in the following example:
set_fact:"{{ {'test': {'subtest': variable}} }}"
'variable}}' will raise a false positive [206] error.
This commit adds an intermediate step within 206
(VariableHasSpacesRule.py) rule to exclude nested
JSON object before matching for an actual error.
Fixes: #665
Signed-off-by: Simon Kheng <765fd267c62104898c4dfafd2f027edd838d8b13@gmail.com><commit_after># Copyright (c) 2016, Will Thames and contributors
# Copyright (c) 2018, Ansible Project
from ansiblelint import AnsibleLintRule
import re
class VariableHasSpacesRule(AnsibleLintRule):
id = '206'
shortdesc = 'Variables should have spaces before and after: {{ var_name }}'
description = 'Variables should have spaces before and after: ``{{ var_name }}``'
severity = 'LOW'
tags = ['formatting']
version_added = 'v4.0.0'
variable_syntax = re.compile(r"{{.*}}")
bracket_regex = re.compile(r"{{[^{' -]|[^ '}-]}}")
def match(self, file, line):
if not self.variable_syntax.search(line):
return
line_exclude_json = re.sub(r"[^{]{'\w+': ?[^{]{.*?}}", "", line)
return self.bracket_regex.search(line_exclude_json)
|
8fc4713375c4eadd83ec376c3e839d921c39b5dc
|
src/encoded/predicates.py
|
src/encoded/predicates.py
|
from pyramid.security import has_permission
def includeme(config):
config.add_view_predicate('subpath_segments', SubpathSegmentsPredicate)
config.add_view_predicate('additional_permission', AdditionalPermissionPredicate)
class SubpathSegmentsPredicate(object):
def __init__(self, val, config):
self.val = val
def text(self):
return 'subpath_segments = %r' % self.val
phash = text
def __call__(self, context, request):
return len(request.subpath) == self.val
class AdditionalPermissionPredicate(object):
def __init__(self, val, config):
self.val = val
def text(self):
return 'additional_permission = %r' % self.val
phash = text
def __call__(self, context, request):
return has_permission(self.val, context, request)
|
from pyramid.security import has_permission
def includeme(config):
config.add_view_predicate('subpath_segments', SubpathSegmentsPredicate)
config.add_view_predicate('additional_permission', AdditionalPermissionPredicate)
class SubpathSegmentsPredicate(object):
def __init__(self, val, config):
if isinstance(val, int):
val = (val,)
self.val = frozenset(val)
def text(self):
return 'subpath_segments in %r' % sorted(self.val)
phash = text
def __call__(self, context, request):
return len(request.subpath) in self.val
class AdditionalPermissionPredicate(object):
def __init__(self, val, config):
self.val = val
def text(self):
return 'additional_permission = %r' % self.val
phash = text
def __call__(self, context, request):
return has_permission(self.val, context, request)
|
Allow specification of multiple subpath_segments
|
Allow specification of multiple subpath_segments
|
Python
|
mit
|
4dn-dcic/fourfront,ClinGen/clincoded,kidaa/encoded,T2DREAM/t2dream-portal,philiptzou/clincoded,hms-dbmi/fourfront,philiptzou/clincoded,4dn-dcic/fourfront,4dn-dcic/fourfront,ENCODE-DCC/encoded,ENCODE-DCC/encoded,ClinGen/clincoded,T2DREAM/t2dream-portal,kidaa/encoded,ENCODE-DCC/snovault,ENCODE-DCC/snovault,ClinGen/clincoded,ENCODE-DCC/encoded,kidaa/encoded,T2DREAM/t2dream-portal,kidaa/encoded,4dn-dcic/fourfront,philiptzou/clincoded,ENCODE-DCC/snovault,ClinGen/clincoded,hms-dbmi/fourfront,hms-dbmi/fourfront,kidaa/encoded,hms-dbmi/fourfront,philiptzou/clincoded,philiptzou/clincoded,hms-dbmi/fourfront,ENCODE-DCC/snovault,ClinGen/clincoded,T2DREAM/t2dream-portal,ENCODE-DCC/snovault,ENCODE-DCC/encoded
|
from pyramid.security import has_permission
def includeme(config):
config.add_view_predicate('subpath_segments', SubpathSegmentsPredicate)
config.add_view_predicate('additional_permission', AdditionalPermissionPredicate)
class SubpathSegmentsPredicate(object):
def __init__(self, val, config):
self.val = val
def text(self):
return 'subpath_segments = %r' % self.val
phash = text
def __call__(self, context, request):
return len(request.subpath) == self.val
class AdditionalPermissionPredicate(object):
def __init__(self, val, config):
self.val = val
def text(self):
return 'additional_permission = %r' % self.val
phash = text
def __call__(self, context, request):
return has_permission(self.val, context, request)
Allow specification of multiple subpath_segments
|
from pyramid.security import has_permission
def includeme(config):
config.add_view_predicate('subpath_segments', SubpathSegmentsPredicate)
config.add_view_predicate('additional_permission', AdditionalPermissionPredicate)
class SubpathSegmentsPredicate(object):
def __init__(self, val, config):
if isinstance(val, int):
val = (val,)
self.val = frozenset(val)
def text(self):
return 'subpath_segments in %r' % sorted(self.val)
phash = text
def __call__(self, context, request):
return len(request.subpath) in self.val
class AdditionalPermissionPredicate(object):
def __init__(self, val, config):
self.val = val
def text(self):
return 'additional_permission = %r' % self.val
phash = text
def __call__(self, context, request):
return has_permission(self.val, context, request)
|
<commit_before>from pyramid.security import has_permission
def includeme(config):
config.add_view_predicate('subpath_segments', SubpathSegmentsPredicate)
config.add_view_predicate('additional_permission', AdditionalPermissionPredicate)
class SubpathSegmentsPredicate(object):
def __init__(self, val, config):
self.val = val
def text(self):
return 'subpath_segments = %r' % self.val
phash = text
def __call__(self, context, request):
return len(request.subpath) == self.val
class AdditionalPermissionPredicate(object):
def __init__(self, val, config):
self.val = val
def text(self):
return 'additional_permission = %r' % self.val
phash = text
def __call__(self, context, request):
return has_permission(self.val, context, request)
<commit_msg>Allow specification of multiple subpath_segments<commit_after>
|
from pyramid.security import has_permission
def includeme(config):
config.add_view_predicate('subpath_segments', SubpathSegmentsPredicate)
config.add_view_predicate('additional_permission', AdditionalPermissionPredicate)
class SubpathSegmentsPredicate(object):
def __init__(self, val, config):
if isinstance(val, int):
val = (val,)
self.val = frozenset(val)
def text(self):
return 'subpath_segments in %r' % sorted(self.val)
phash = text
def __call__(self, context, request):
return len(request.subpath) in self.val
class AdditionalPermissionPredicate(object):
def __init__(self, val, config):
self.val = val
def text(self):
return 'additional_permission = %r' % self.val
phash = text
def __call__(self, context, request):
return has_permission(self.val, context, request)
|
from pyramid.security import has_permission
def includeme(config):
config.add_view_predicate('subpath_segments', SubpathSegmentsPredicate)
config.add_view_predicate('additional_permission', AdditionalPermissionPredicate)
class SubpathSegmentsPredicate(object):
def __init__(self, val, config):
self.val = val
def text(self):
return 'subpath_segments = %r' % self.val
phash = text
def __call__(self, context, request):
return len(request.subpath) == self.val
class AdditionalPermissionPredicate(object):
def __init__(self, val, config):
self.val = val
def text(self):
return 'additional_permission = %r' % self.val
phash = text
def __call__(self, context, request):
return has_permission(self.val, context, request)
Allow specification of multiple subpath_segmentsfrom pyramid.security import has_permission
def includeme(config):
config.add_view_predicate('subpath_segments', SubpathSegmentsPredicate)
config.add_view_predicate('additional_permission', AdditionalPermissionPredicate)
class SubpathSegmentsPredicate(object):
def __init__(self, val, config):
if isinstance(val, int):
val = (val,)
self.val = frozenset(val)
def text(self):
return 'subpath_segments in %r' % sorted(self.val)
phash = text
def __call__(self, context, request):
return len(request.subpath) in self.val
class AdditionalPermissionPredicate(object):
def __init__(self, val, config):
self.val = val
def text(self):
return 'additional_permission = %r' % self.val
phash = text
def __call__(self, context, request):
return has_permission(self.val, context, request)
|
<commit_before>from pyramid.security import has_permission
def includeme(config):
config.add_view_predicate('subpath_segments', SubpathSegmentsPredicate)
config.add_view_predicate('additional_permission', AdditionalPermissionPredicate)
class SubpathSegmentsPredicate(object):
def __init__(self, val, config):
self.val = val
def text(self):
return 'subpath_segments = %r' % self.val
phash = text
def __call__(self, context, request):
return len(request.subpath) == self.val
class AdditionalPermissionPredicate(object):
def __init__(self, val, config):
self.val = val
def text(self):
return 'additional_permission = %r' % self.val
phash = text
def __call__(self, context, request):
return has_permission(self.val, context, request)
<commit_msg>Allow specification of multiple subpath_segments<commit_after>from pyramid.security import has_permission
def includeme(config):
config.add_view_predicate('subpath_segments', SubpathSegmentsPredicate)
config.add_view_predicate('additional_permission', AdditionalPermissionPredicate)
class SubpathSegmentsPredicate(object):
def __init__(self, val, config):
if isinstance(val, int):
val = (val,)
self.val = frozenset(val)
def text(self):
return 'subpath_segments in %r' % sorted(self.val)
phash = text
def __call__(self, context, request):
return len(request.subpath) in self.val
class AdditionalPermissionPredicate(object):
def __init__(self, val, config):
self.val = val
def text(self):
return 'additional_permission = %r' % self.val
phash = text
def __call__(self, context, request):
return has_permission(self.val, context, request)
|
f014538a79facc32bdc726f0d7fe5d9a10d24189
|
project/settings.py
|
project/settings.py
|
# -*- coding: utf-8 -*-
TENHOU_HOST = '133.242.10.78'
TENHOU_PORT = 10080
USER_ID = 'NoName'
LOBBY = '0'
WAITING_GAME_TIMEOUT_MINUTES = 10
# in tournament mode bot is not trying to search the game
# it just sitting in the lobby and waiting for the game start
IS_TOURNAMENT = False
STAT_SERVER_URL = ''
STAT_TOKEN = ''
ENABLE_AI = True
# 1 - tonpu-sen, ari, ari
# 9 - hanchan, ari, ari
GAME_TYPE = '1'
try:
from settings_local import *
except ImportError:
pass
|
# -*- coding: utf-8 -*-
TENHOU_HOST = '133.242.10.78'
TENHOU_PORT = 10080
USER_ID = 'NoName'
LOBBY = '0'
WAITING_GAME_TIMEOUT_MINUTES = 10
# in tournament mode bot is not trying to search the game
# it just sitting in the lobby and waiting for the game start
IS_TOURNAMENT = False
STAT_SERVER_URL = ''
STAT_TOKEN = ''
ENABLE_AI = True
"""
0 - 1 - online, 0 - bots
1 - aka forbidden
2 - kuitan forbidden
3 - hanchan
4 - 3man
5 - dan flag
6 - fast game
7 - dan flag
Combine them as:
76543210
00001001 = 9 = hanchan ari-ari
00000001 = 1 = tonpu-sen ari-ari
"""
GAME_TYPE = '1'
try:
from settings_local import *
except ImportError:
pass
|
Update description for game types
|
Update description for game types
|
Python
|
mit
|
huangenyan/Lattish,MahjongRepository/tenhou-python-bot,huangenyan/Lattish,MahjongRepository/tenhou-python-bot
|
# -*- coding: utf-8 -*-
TENHOU_HOST = '133.242.10.78'
TENHOU_PORT = 10080
USER_ID = 'NoName'
LOBBY = '0'
WAITING_GAME_TIMEOUT_MINUTES = 10
# in tournament mode bot is not trying to search the game
# it just sitting in the lobby and waiting for the game start
IS_TOURNAMENT = False
STAT_SERVER_URL = ''
STAT_TOKEN = ''
ENABLE_AI = True
# 1 - tonpu-sen, ari, ari
# 9 - hanchan, ari, ari
GAME_TYPE = '1'
try:
from settings_local import *
except ImportError:
pass
Update description for game types
|
# -*- coding: utf-8 -*-
TENHOU_HOST = '133.242.10.78'
TENHOU_PORT = 10080
USER_ID = 'NoName'
LOBBY = '0'
WAITING_GAME_TIMEOUT_MINUTES = 10
# in tournament mode bot is not trying to search the game
# it just sitting in the lobby and waiting for the game start
IS_TOURNAMENT = False
STAT_SERVER_URL = ''
STAT_TOKEN = ''
ENABLE_AI = True
"""
0 - 1 - online, 0 - bots
1 - aka forbidden
2 - kuitan forbidden
3 - hanchan
4 - 3man
5 - dan flag
6 - fast game
7 - dan flag
Combine them as:
76543210
00001001 = 9 = hanchan ari-ari
00000001 = 1 = tonpu-sen ari-ari
"""
GAME_TYPE = '1'
try:
from settings_local import *
except ImportError:
pass
|
<commit_before># -*- coding: utf-8 -*-
TENHOU_HOST = '133.242.10.78'
TENHOU_PORT = 10080
USER_ID = 'NoName'
LOBBY = '0'
WAITING_GAME_TIMEOUT_MINUTES = 10
# in tournament mode bot is not trying to search the game
# it just sitting in the lobby and waiting for the game start
IS_TOURNAMENT = False
STAT_SERVER_URL = ''
STAT_TOKEN = ''
ENABLE_AI = True
# 1 - tonpu-sen, ari, ari
# 9 - hanchan, ari, ari
GAME_TYPE = '1'
try:
from settings_local import *
except ImportError:
pass
<commit_msg>Update description for game types<commit_after>
|
# -*- coding: utf-8 -*-
TENHOU_HOST = '133.242.10.78'
TENHOU_PORT = 10080
USER_ID = 'NoName'
LOBBY = '0'
WAITING_GAME_TIMEOUT_MINUTES = 10
# in tournament mode bot is not trying to search the game
# it just sitting in the lobby and waiting for the game start
IS_TOURNAMENT = False
STAT_SERVER_URL = ''
STAT_TOKEN = ''
ENABLE_AI = True
"""
0 - 1 - online, 0 - bots
1 - aka forbidden
2 - kuitan forbidden
3 - hanchan
4 - 3man
5 - dan flag
6 - fast game
7 - dan flag
Combine them as:
76543210
00001001 = 9 = hanchan ari-ari
00000001 = 1 = tonpu-sen ari-ari
"""
GAME_TYPE = '1'
try:
from settings_local import *
except ImportError:
pass
|
# -*- coding: utf-8 -*-
TENHOU_HOST = '133.242.10.78'
TENHOU_PORT = 10080
USER_ID = 'NoName'
LOBBY = '0'
WAITING_GAME_TIMEOUT_MINUTES = 10
# in tournament mode bot is not trying to search the game
# it just sitting in the lobby and waiting for the game start
IS_TOURNAMENT = False
STAT_SERVER_URL = ''
STAT_TOKEN = ''
ENABLE_AI = True
# 1 - tonpu-sen, ari, ari
# 9 - hanchan, ari, ari
GAME_TYPE = '1'
try:
from settings_local import *
except ImportError:
pass
Update description for game types# -*- coding: utf-8 -*-
TENHOU_HOST = '133.242.10.78'
TENHOU_PORT = 10080
USER_ID = 'NoName'
LOBBY = '0'
WAITING_GAME_TIMEOUT_MINUTES = 10
# in tournament mode bot is not trying to search the game
# it just sitting in the lobby and waiting for the game start
IS_TOURNAMENT = False
STAT_SERVER_URL = ''
STAT_TOKEN = ''
ENABLE_AI = True
"""
0 - 1 - online, 0 - bots
1 - aka forbidden
2 - kuitan forbidden
3 - hanchan
4 - 3man
5 - dan flag
6 - fast game
7 - dan flag
Combine them as:
76543210
00001001 = 9 = hanchan ari-ari
00000001 = 1 = tonpu-sen ari-ari
"""
GAME_TYPE = '1'
try:
from settings_local import *
except ImportError:
pass
|
<commit_before># -*- coding: utf-8 -*-
TENHOU_HOST = '133.242.10.78'
TENHOU_PORT = 10080
USER_ID = 'NoName'
LOBBY = '0'
WAITING_GAME_TIMEOUT_MINUTES = 10
# in tournament mode bot is not trying to search the game
# it just sitting in the lobby and waiting for the game start
IS_TOURNAMENT = False
STAT_SERVER_URL = ''
STAT_TOKEN = ''
ENABLE_AI = True
# 1 - tonpu-sen, ari, ari
# 9 - hanchan, ari, ari
GAME_TYPE = '1'
try:
from settings_local import *
except ImportError:
pass
<commit_msg>Update description for game types<commit_after># -*- coding: utf-8 -*-
TENHOU_HOST = '133.242.10.78'
TENHOU_PORT = 10080
USER_ID = 'NoName'
LOBBY = '0'
WAITING_GAME_TIMEOUT_MINUTES = 10
# in tournament mode bot is not trying to search the game
# it just sitting in the lobby and waiting for the game start
IS_TOURNAMENT = False
STAT_SERVER_URL = ''
STAT_TOKEN = ''
ENABLE_AI = True
"""
0 - 1 - online, 0 - bots
1 - aka forbidden
2 - kuitan forbidden
3 - hanchan
4 - 3man
5 - dan flag
6 - fast game
7 - dan flag
Combine them as:
76543210
00001001 = 9 = hanchan ari-ari
00000001 = 1 = tonpu-sen ari-ari
"""
GAME_TYPE = '1'
try:
from settings_local import *
except ImportError:
pass
|
f5234462c3bdacf91aad84df78bf750bf2035493
|
alfred_db/migrations/versions/4fdf1059c4ba_add_organizations_us.py
|
alfred_db/migrations/versions/4fdf1059c4ba_add_organizations_us.py
|
"""Add organizations-users association table
Revision ID: 4fdf1059c4ba
Revises: 393a48ab5fc7
Create Date: 2012-09-02 12:37:11.785052
"""
# revision identifiers, used by Alembic.
revision = '4fdf1059c4ba'
down_revision = '393a48ab5fc7'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.create_table('memberships',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('organization_id', sa.Integer(), nullable=True),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['organization_id'], ['organizations.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
def downgrade():
op.drop_table('memberships')
|
"""Add organizations-users association table
Revision ID: 4fdf1059c4ba
Revises: 393a48ab5fc7
Create Date: 2012-09-02 12:37:11.785052
"""
# revision identifiers, used by Alembic.
revision = '4fdf1059c4ba'
down_revision = '393a48ab5fc7'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.create_table('memberships',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('organization_id', sa.Integer(), nullable=True),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(
['organization_id'], ['organizations.id'], ondelete='CASCADE'
),
sa.ForeignKeyConstraint(
['user_id'], ['users.id'], ondelete='CASCADE'
),
sa.PrimaryKeyConstraint('id')
)
def downgrade():
op.drop_table('memberships')
|
Fix memebership table creation migration
|
Fix memebership table creation migration
|
Python
|
isc
|
alfredhq/alfred-db
|
"""Add organizations-users association table
Revision ID: 4fdf1059c4ba
Revises: 393a48ab5fc7
Create Date: 2012-09-02 12:37:11.785052
"""
# revision identifiers, used by Alembic.
revision = '4fdf1059c4ba'
down_revision = '393a48ab5fc7'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.create_table('memberships',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('organization_id', sa.Integer(), nullable=True),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['organization_id'], ['organizations.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
def downgrade():
op.drop_table('memberships')
Fix memebership table creation migration
|
"""Add organizations-users association table
Revision ID: 4fdf1059c4ba
Revises: 393a48ab5fc7
Create Date: 2012-09-02 12:37:11.785052
"""
# revision identifiers, used by Alembic.
revision = '4fdf1059c4ba'
down_revision = '393a48ab5fc7'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.create_table('memberships',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('organization_id', sa.Integer(), nullable=True),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(
['organization_id'], ['organizations.id'], ondelete='CASCADE'
),
sa.ForeignKeyConstraint(
['user_id'], ['users.id'], ondelete='CASCADE'
),
sa.PrimaryKeyConstraint('id')
)
def downgrade():
op.drop_table('memberships')
|
<commit_before>"""Add organizations-users association table
Revision ID: 4fdf1059c4ba
Revises: 393a48ab5fc7
Create Date: 2012-09-02 12:37:11.785052
"""
# revision identifiers, used by Alembic.
revision = '4fdf1059c4ba'
down_revision = '393a48ab5fc7'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.create_table('memberships',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('organization_id', sa.Integer(), nullable=True),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['organization_id'], ['organizations.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
def downgrade():
op.drop_table('memberships')
<commit_msg>Fix memebership table creation migration<commit_after>
|
"""Add organizations-users association table
Revision ID: 4fdf1059c4ba
Revises: 393a48ab5fc7
Create Date: 2012-09-02 12:37:11.785052
"""
# revision identifiers, used by Alembic.
revision = '4fdf1059c4ba'
down_revision = '393a48ab5fc7'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.create_table('memberships',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('organization_id', sa.Integer(), nullable=True),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(
['organization_id'], ['organizations.id'], ondelete='CASCADE'
),
sa.ForeignKeyConstraint(
['user_id'], ['users.id'], ondelete='CASCADE'
),
sa.PrimaryKeyConstraint('id')
)
def downgrade():
op.drop_table('memberships')
|
"""Add organizations-users association table
Revision ID: 4fdf1059c4ba
Revises: 393a48ab5fc7
Create Date: 2012-09-02 12:37:11.785052
"""
# revision identifiers, used by Alembic.
revision = '4fdf1059c4ba'
down_revision = '393a48ab5fc7'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.create_table('memberships',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('organization_id', sa.Integer(), nullable=True),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['organization_id'], ['organizations.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
def downgrade():
op.drop_table('memberships')
Fix memebership table creation migration"""Add organizations-users association table
Revision ID: 4fdf1059c4ba
Revises: 393a48ab5fc7
Create Date: 2012-09-02 12:37:11.785052
"""
# revision identifiers, used by Alembic.
revision = '4fdf1059c4ba'
down_revision = '393a48ab5fc7'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.create_table('memberships',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('organization_id', sa.Integer(), nullable=True),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(
['organization_id'], ['organizations.id'], ondelete='CASCADE'
),
sa.ForeignKeyConstraint(
['user_id'], ['users.id'], ondelete='CASCADE'
),
sa.PrimaryKeyConstraint('id')
)
def downgrade():
op.drop_table('memberships')
|
<commit_before>"""Add organizations-users association table
Revision ID: 4fdf1059c4ba
Revises: 393a48ab5fc7
Create Date: 2012-09-02 12:37:11.785052
"""
# revision identifiers, used by Alembic.
revision = '4fdf1059c4ba'
down_revision = '393a48ab5fc7'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.create_table('memberships',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('organization_id', sa.Integer(), nullable=True),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['organization_id'], ['organizations.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
def downgrade():
op.drop_table('memberships')
<commit_msg>Fix memebership table creation migration<commit_after>"""Add organizations-users association table
Revision ID: 4fdf1059c4ba
Revises: 393a48ab5fc7
Create Date: 2012-09-02 12:37:11.785052
"""
# revision identifiers, used by Alembic.
revision = '4fdf1059c4ba'
down_revision = '393a48ab5fc7'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.create_table('memberships',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('organization_id', sa.Integer(), nullable=True),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(
['organization_id'], ['organizations.id'], ondelete='CASCADE'
),
sa.ForeignKeyConstraint(
['user_id'], ['users.id'], ondelete='CASCADE'
),
sa.PrimaryKeyConstraint('id')
)
def downgrade():
op.drop_table('memberships')
|
d208407fb71ccb2d09eae7af41e486caae65a45e
|
openquake/__init__.py
|
openquake/__init__.py
|
__import__('pkg_resources').declare_namespace(__name__)
|
# -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright (C) 2010-2016 GEM Foundation
#
# OpenQuake is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# OpenQuake is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with OpenQuake. If not, see <http://www.gnu.org/licenses/>.
# Make the namespace compatible with old setuptools, like the one
# provided by QGIS 2.1x on Windows
try:
__import__('pkg_resources').declare_namespace(__name__)
except ImportError:
__path__ = __import__('pkgutil').extend_path(__path__, __name__)
|
Make the openquake namespace compatible with old setuptools
|
Make the openquake namespace compatible with old setuptools
|
Python
|
agpl-3.0
|
gem/oq-engine,gem/oq-engine,rcgee/oq-hazardlib,gem/oq-hazardlib,gem/oq-hazardlib,gem/oq-engine,gem/oq-engine,rcgee/oq-hazardlib,gem/oq-hazardlib,gem/oq-engine
|
__import__('pkg_resources').declare_namespace(__name__)
Make the openquake namespace compatible with old setuptools
|
# -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright (C) 2010-2016 GEM Foundation
#
# OpenQuake is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# OpenQuake is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with OpenQuake. If not, see <http://www.gnu.org/licenses/>.
# Make the namespace compatible with old setuptools, like the one
# provided by QGIS 2.1x on Windows
try:
__import__('pkg_resources').declare_namespace(__name__)
except ImportError:
__path__ = __import__('pkgutil').extend_path(__path__, __name__)
|
<commit_before>__import__('pkg_resources').declare_namespace(__name__)
<commit_msg>Make the openquake namespace compatible with old setuptools<commit_after>
|
# -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright (C) 2010-2016 GEM Foundation
#
# OpenQuake is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# OpenQuake is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with OpenQuake. If not, see <http://www.gnu.org/licenses/>.
# Make the namespace compatible with old setuptools, like the one
# provided by QGIS 2.1x on Windows
try:
__import__('pkg_resources').declare_namespace(__name__)
except ImportError:
__path__ = __import__('pkgutil').extend_path(__path__, __name__)
|
__import__('pkg_resources').declare_namespace(__name__)
Make the openquake namespace compatible with old setuptools# -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright (C) 2010-2016 GEM Foundation
#
# OpenQuake is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# OpenQuake is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with OpenQuake. If not, see <http://www.gnu.org/licenses/>.
# Make the namespace compatible with old setuptools, like the one
# provided by QGIS 2.1x on Windows
try:
__import__('pkg_resources').declare_namespace(__name__)
except ImportError:
__path__ = __import__('pkgutil').extend_path(__path__, __name__)
|
<commit_before>__import__('pkg_resources').declare_namespace(__name__)
<commit_msg>Make the openquake namespace compatible with old setuptools<commit_after># -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright (C) 2010-2016 GEM Foundation
#
# OpenQuake is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# OpenQuake is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with OpenQuake. If not, see <http://www.gnu.org/licenses/>.
# Make the namespace compatible with old setuptools, like the one
# provided by QGIS 2.1x on Windows
try:
__import__('pkg_resources').declare_namespace(__name__)
except ImportError:
__path__ = __import__('pkgutil').extend_path(__path__, __name__)
|
5ad869909e95fa8e5e0b6a489d361c42006023a5
|
openstack/__init__.py
|
openstack/__init__.py
|
# -*- coding: utf-8 -*-
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import pbr.version
__version__ = pbr.version.VersionInfo(
'openstack').version_string()
|
# -*- coding: utf-8 -*-
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import pbr.version
__version__ = pbr.version.VersionInfo(
'python-openstacksdk').version_string()
|
Use project name to retrieve version info
|
Use project name to retrieve version info
Change-Id: Iaef93bde5183263f900166b8ec90eefb7bfdc99b
|
Python
|
apache-2.0
|
openstack/python-openstacksdk,dudymas/python-openstacksdk,dudymas/python-openstacksdk,mtougeron/python-openstacksdk,mtougeron/python-openstacksdk,openstack/python-openstacksdk,briancurtin/python-openstacksdk,dtroyer/python-openstacksdk,stackforge/python-openstacksdk,briancurtin/python-openstacksdk,stackforge/python-openstacksdk,dtroyer/python-openstacksdk
|
# -*- coding: utf-8 -*-
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import pbr.version
__version__ = pbr.version.VersionInfo(
'openstack').version_string()
Use project name to retrieve version info
Change-Id: Iaef93bde5183263f900166b8ec90eefb7bfdc99b
|
# -*- coding: utf-8 -*-
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import pbr.version
__version__ = pbr.version.VersionInfo(
'python-openstacksdk').version_string()
|
<commit_before># -*- coding: utf-8 -*-
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import pbr.version
__version__ = pbr.version.VersionInfo(
'openstack').version_string()
<commit_msg>Use project name to retrieve version info
Change-Id: Iaef93bde5183263f900166b8ec90eefb7bfdc99b<commit_after>
|
# -*- coding: utf-8 -*-
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import pbr.version
__version__ = pbr.version.VersionInfo(
'python-openstacksdk').version_string()
|
# -*- coding: utf-8 -*-
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import pbr.version
__version__ = pbr.version.VersionInfo(
'openstack').version_string()
Use project name to retrieve version info
Change-Id: Iaef93bde5183263f900166b8ec90eefb7bfdc99b# -*- coding: utf-8 -*-
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import pbr.version
__version__ = pbr.version.VersionInfo(
'python-openstacksdk').version_string()
|
<commit_before># -*- coding: utf-8 -*-
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import pbr.version
__version__ = pbr.version.VersionInfo(
'openstack').version_string()
<commit_msg>Use project name to retrieve version info
Change-Id: Iaef93bde5183263f900166b8ec90eefb7bfdc99b<commit_after># -*- coding: utf-8 -*-
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import pbr.version
__version__ = pbr.version.VersionInfo(
'python-openstacksdk').version_string()
|
a6581409971a8670a5195924feb27fb890d297c5
|
plugins/PerObjectSettingsTool/PerObjectSettingsTool.py
|
plugins/PerObjectSettingsTool/PerObjectSettingsTool.py
|
# Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from UM.Tool import Tool
from UM.Scene.Selection import Selection
from UM.Application import Application
from . import PerObjectSettingsModel
class PerObjectSettingsTool(Tool):
def __init__(self):
super().__init__()
self.setExposedProperties("Model", "SelectedIndex", "PrintSequence")
def event(self, event):
return False
def getModel(self):
return PerObjectSettingsModel.PerObjectSettingsModel()
def getSelectedIndex(self):
selected_object_id = id(Selection.getSelectedObject(0))
index = self.getModel().find("id", selected_object_id)
return index
def getPrintSequence(self):
settings = Application.getInstance().getMachineManager().getActiveProfile()
return settings.getSettingValue("print_sequence")
|
# Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from UM.Tool import Tool
from UM.Scene.Selection import Selection
from UM.Application import Application
from . import PerObjectSettingsModel
class PerObjectSettingsTool(Tool):
def __init__(self):
super().__init__()
self.setExposedProperties("Model", "SelectedIndex")
def event(self, event):
return False
def getModel(self):
return PerObjectSettingsModel.PerObjectSettingsModel()
def getSelectedIndex(self):
selected_object_id = id(Selection.getSelectedObject(0))
index = self.getModel().find("id", selected_object_id)
return index
|
Remove more remnants of print sequence message
|
Remove more remnants of print sequence message
I found this other place that was helping to display the message that warns that print sequcence is set per-object. Since the latter is no longer possible, this message shouldn't be displayed any more.
Contributes to issue CURA-458.
|
Python
|
agpl-3.0
|
hmflash/Cura,Curahelper/Cura,senttech/Cura,Curahelper/Cura,hmflash/Cura,ynotstartups/Wanhao,totalretribution/Cura,fieldOfView/Cura,senttech/Cura,totalretribution/Cura,ynotstartups/Wanhao,fieldOfView/Cura
|
# Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from UM.Tool import Tool
from UM.Scene.Selection import Selection
from UM.Application import Application
from . import PerObjectSettingsModel
class PerObjectSettingsTool(Tool):
def __init__(self):
super().__init__()
self.setExposedProperties("Model", "SelectedIndex", "PrintSequence")
def event(self, event):
return False
def getModel(self):
return PerObjectSettingsModel.PerObjectSettingsModel()
def getSelectedIndex(self):
selected_object_id = id(Selection.getSelectedObject(0))
index = self.getModel().find("id", selected_object_id)
return index
def getPrintSequence(self):
settings = Application.getInstance().getMachineManager().getActiveProfile()
return settings.getSettingValue("print_sequence")Remove more remnants of print sequence message
I found this other place that was helping to display the message that warns that print sequcence is set per-object. Since the latter is no longer possible, this message shouldn't be displayed any more.
Contributes to issue CURA-458.
|
# Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from UM.Tool import Tool
from UM.Scene.Selection import Selection
from UM.Application import Application
from . import PerObjectSettingsModel
class PerObjectSettingsTool(Tool):
def __init__(self):
super().__init__()
self.setExposedProperties("Model", "SelectedIndex")
def event(self, event):
return False
def getModel(self):
return PerObjectSettingsModel.PerObjectSettingsModel()
def getSelectedIndex(self):
selected_object_id = id(Selection.getSelectedObject(0))
index = self.getModel().find("id", selected_object_id)
return index
|
<commit_before># Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from UM.Tool import Tool
from UM.Scene.Selection import Selection
from UM.Application import Application
from . import PerObjectSettingsModel
class PerObjectSettingsTool(Tool):
def __init__(self):
super().__init__()
self.setExposedProperties("Model", "SelectedIndex", "PrintSequence")
def event(self, event):
return False
def getModel(self):
return PerObjectSettingsModel.PerObjectSettingsModel()
def getSelectedIndex(self):
selected_object_id = id(Selection.getSelectedObject(0))
index = self.getModel().find("id", selected_object_id)
return index
def getPrintSequence(self):
settings = Application.getInstance().getMachineManager().getActiveProfile()
return settings.getSettingValue("print_sequence")<commit_msg>Remove more remnants of print sequence message
I found this other place that was helping to display the message that warns that print sequcence is set per-object. Since the latter is no longer possible, this message shouldn't be displayed any more.
Contributes to issue CURA-458.<commit_after>
|
# Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from UM.Tool import Tool
from UM.Scene.Selection import Selection
from UM.Application import Application
from . import PerObjectSettingsModel
class PerObjectSettingsTool(Tool):
def __init__(self):
super().__init__()
self.setExposedProperties("Model", "SelectedIndex")
def event(self, event):
return False
def getModel(self):
return PerObjectSettingsModel.PerObjectSettingsModel()
def getSelectedIndex(self):
selected_object_id = id(Selection.getSelectedObject(0))
index = self.getModel().find("id", selected_object_id)
return index
|
# Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from UM.Tool import Tool
from UM.Scene.Selection import Selection
from UM.Application import Application
from . import PerObjectSettingsModel
class PerObjectSettingsTool(Tool):
def __init__(self):
super().__init__()
self.setExposedProperties("Model", "SelectedIndex", "PrintSequence")
def event(self, event):
return False
def getModel(self):
return PerObjectSettingsModel.PerObjectSettingsModel()
def getSelectedIndex(self):
selected_object_id = id(Selection.getSelectedObject(0))
index = self.getModel().find("id", selected_object_id)
return index
def getPrintSequence(self):
settings = Application.getInstance().getMachineManager().getActiveProfile()
return settings.getSettingValue("print_sequence")Remove more remnants of print sequence message
I found this other place that was helping to display the message that warns that print sequcence is set per-object. Since the latter is no longer possible, this message shouldn't be displayed any more.
Contributes to issue CURA-458.# Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from UM.Tool import Tool
from UM.Scene.Selection import Selection
from UM.Application import Application
from . import PerObjectSettingsModel
class PerObjectSettingsTool(Tool):
def __init__(self):
super().__init__()
self.setExposedProperties("Model", "SelectedIndex")
def event(self, event):
return False
def getModel(self):
return PerObjectSettingsModel.PerObjectSettingsModel()
def getSelectedIndex(self):
selected_object_id = id(Selection.getSelectedObject(0))
index = self.getModel().find("id", selected_object_id)
return index
|
<commit_before># Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from UM.Tool import Tool
from UM.Scene.Selection import Selection
from UM.Application import Application
from . import PerObjectSettingsModel
class PerObjectSettingsTool(Tool):
def __init__(self):
super().__init__()
self.setExposedProperties("Model", "SelectedIndex", "PrintSequence")
def event(self, event):
return False
def getModel(self):
return PerObjectSettingsModel.PerObjectSettingsModel()
def getSelectedIndex(self):
selected_object_id = id(Selection.getSelectedObject(0))
index = self.getModel().find("id", selected_object_id)
return index
def getPrintSequence(self):
settings = Application.getInstance().getMachineManager().getActiveProfile()
return settings.getSettingValue("print_sequence")<commit_msg>Remove more remnants of print sequence message
I found this other place that was helping to display the message that warns that print sequcence is set per-object. Since the latter is no longer possible, this message shouldn't be displayed any more.
Contributes to issue CURA-458.<commit_after># Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from UM.Tool import Tool
from UM.Scene.Selection import Selection
from UM.Application import Application
from . import PerObjectSettingsModel
class PerObjectSettingsTool(Tool):
def __init__(self):
super().__init__()
self.setExposedProperties("Model", "SelectedIndex")
def event(self, event):
return False
def getModel(self):
return PerObjectSettingsModel.PerObjectSettingsModel()
def getSelectedIndex(self):
selected_object_id = id(Selection.getSelectedObject(0))
index = self.getModel().find("id", selected_object_id)
return index
|
e0164d906c791d0b00077ae5353a07a07f4cd30d
|
labs/04_conv_nets/solutions/strides_padding.py
|
labs/04_conv_nets/solutions/strides_padding.py
|
def my_init(shape, dtype=None):
array = np.zeros(shape=(5,5,3,3))
array[2,2] = np.eye(3)
return array
inp = Input((None, None, 3), dtype="float32")
x = Conv2D(kernel_size=(5,5), filters=3, strides=2,
padding="same", kernel_initializer=my_init)(inp)
conv_strides_same = Model(inputs=inp, outputs=x)
x2 = Conv2D(kernel_size=(5,5), filters=3, strides=2,
padding="valid", kernel_initializer=my_init)(inp)
conv_strides_valid = Model(inputs=inp, outputs=x2)
img_out = conv_strides_same.predict(np.expand_dims(sample_image, 0))
img_out2 = conv_strides_valid.predict(np.expand_dims(sample_image, 0))
show(img_out[0])
print("Shape of result with SAME padding:", img_out.shape)
print("Shape of result with VALID padding:", img_out2.shape)
# We observe that the stride divided the size of the image by 2
# In the case of 'VALID' padding mode, no padding is added, so
# the size of the ouput image is actually 1 less because of the
# kernel size
|
def my_init(shape=(5, 5, 3, 3), dtype=None):
array = np.zeros(shape=shape)
array[2, 2] = np.eye(3)
return array
conv_strides_same = Sequential([
Conv2D(filters=3, kernel_size=5, strides=2,
padding="same", kernel_initializer=my_init,
input_shape=(None, None, 3))
])
conv_strides_valid = Sequential([
Conv2D(filters=3, kernel_size=5, strides=2,
padding="valid", kernel_initializer=my_init,
input_shape=(None, None, 3))
])
img_in = np.expand_dims(sample_image, 0)
img_out_same = conv_strides_same.predict(img_in)
img_out_valid = conv_strides_valid.predict(img_in)
print("Shape of result with SAME padding:", img_out_same.shape)
print("Shape of result with VALID padding:", img_out_valid.shape)
fig, (ax0, ax1, ax2) = plt.subplots(ncols=3, figsize=(12, 4))
ax0.imshow(img_in[0].astype(np.uint8))
ax1.imshow(img_out_same[0].astype(np.uint8))
ax2.imshow(img_out_valid[0].astype(np.uint8))
# We observe that the stride divided the size of the image by 2
# In the case of 'VALID' padding mode, no padding is added, so
# the size of the ouput image is actually 1 less because of the
# kernel size
|
Update solution to be consistent
|
Update solution to be consistent
|
Python
|
mit
|
m2dsupsdlclass/lectures-labs,m2dsupsdlclass/lectures-labs
|
def my_init(shape, dtype=None):
array = np.zeros(shape=(5,5,3,3))
array[2,2] = np.eye(3)
return array
inp = Input((None, None, 3), dtype="float32")
x = Conv2D(kernel_size=(5,5), filters=3, strides=2,
padding="same", kernel_initializer=my_init)(inp)
conv_strides_same = Model(inputs=inp, outputs=x)
x2 = Conv2D(kernel_size=(5,5), filters=3, strides=2,
padding="valid", kernel_initializer=my_init)(inp)
conv_strides_valid = Model(inputs=inp, outputs=x2)
img_out = conv_strides_same.predict(np.expand_dims(sample_image, 0))
img_out2 = conv_strides_valid.predict(np.expand_dims(sample_image, 0))
show(img_out[0])
print("Shape of result with SAME padding:", img_out.shape)
print("Shape of result with VALID padding:", img_out2.shape)
# We observe that the stride divided the size of the image by 2
# In the case of 'VALID' padding mode, no padding is added, so
# the size of the ouput image is actually 1 less because of the
# kernel size
Update solution to be consistent
|
def my_init(shape=(5, 5, 3, 3), dtype=None):
array = np.zeros(shape=shape)
array[2, 2] = np.eye(3)
return array
conv_strides_same = Sequential([
Conv2D(filters=3, kernel_size=5, strides=2,
padding="same", kernel_initializer=my_init,
input_shape=(None, None, 3))
])
conv_strides_valid = Sequential([
Conv2D(filters=3, kernel_size=5, strides=2,
padding="valid", kernel_initializer=my_init,
input_shape=(None, None, 3))
])
img_in = np.expand_dims(sample_image, 0)
img_out_same = conv_strides_same.predict(img_in)
img_out_valid = conv_strides_valid.predict(img_in)
print("Shape of result with SAME padding:", img_out_same.shape)
print("Shape of result with VALID padding:", img_out_valid.shape)
fig, (ax0, ax1, ax2) = plt.subplots(ncols=3, figsize=(12, 4))
ax0.imshow(img_in[0].astype(np.uint8))
ax1.imshow(img_out_same[0].astype(np.uint8))
ax2.imshow(img_out_valid[0].astype(np.uint8))
# We observe that the stride divided the size of the image by 2
# In the case of 'VALID' padding mode, no padding is added, so
# the size of the ouput image is actually 1 less because of the
# kernel size
|
<commit_before>
def my_init(shape, dtype=None):
array = np.zeros(shape=(5,5,3,3))
array[2,2] = np.eye(3)
return array
inp = Input((None, None, 3), dtype="float32")
x = Conv2D(kernel_size=(5,5), filters=3, strides=2,
padding="same", kernel_initializer=my_init)(inp)
conv_strides_same = Model(inputs=inp, outputs=x)
x2 = Conv2D(kernel_size=(5,5), filters=3, strides=2,
padding="valid", kernel_initializer=my_init)(inp)
conv_strides_valid = Model(inputs=inp, outputs=x2)
img_out = conv_strides_same.predict(np.expand_dims(sample_image, 0))
img_out2 = conv_strides_valid.predict(np.expand_dims(sample_image, 0))
show(img_out[0])
print("Shape of result with SAME padding:", img_out.shape)
print("Shape of result with VALID padding:", img_out2.shape)
# We observe that the stride divided the size of the image by 2
# In the case of 'VALID' padding mode, no padding is added, so
# the size of the ouput image is actually 1 less because of the
# kernel size
<commit_msg>Update solution to be consistent<commit_after>
|
def my_init(shape=(5, 5, 3, 3), dtype=None):
array = np.zeros(shape=shape)
array[2, 2] = np.eye(3)
return array
conv_strides_same = Sequential([
Conv2D(filters=3, kernel_size=5, strides=2,
padding="same", kernel_initializer=my_init,
input_shape=(None, None, 3))
])
conv_strides_valid = Sequential([
Conv2D(filters=3, kernel_size=5, strides=2,
padding="valid", kernel_initializer=my_init,
input_shape=(None, None, 3))
])
img_in = np.expand_dims(sample_image, 0)
img_out_same = conv_strides_same.predict(img_in)
img_out_valid = conv_strides_valid.predict(img_in)
print("Shape of result with SAME padding:", img_out_same.shape)
print("Shape of result with VALID padding:", img_out_valid.shape)
fig, (ax0, ax1, ax2) = plt.subplots(ncols=3, figsize=(12, 4))
ax0.imshow(img_in[0].astype(np.uint8))
ax1.imshow(img_out_same[0].astype(np.uint8))
ax2.imshow(img_out_valid[0].astype(np.uint8))
# We observe that the stride divided the size of the image by 2
# In the case of 'VALID' padding mode, no padding is added, so
# the size of the ouput image is actually 1 less because of the
# kernel size
|
def my_init(shape, dtype=None):
array = np.zeros(shape=(5,5,3,3))
array[2,2] = np.eye(3)
return array
inp = Input((None, None, 3), dtype="float32")
x = Conv2D(kernel_size=(5,5), filters=3, strides=2,
padding="same", kernel_initializer=my_init)(inp)
conv_strides_same = Model(inputs=inp, outputs=x)
x2 = Conv2D(kernel_size=(5,5), filters=3, strides=2,
padding="valid", kernel_initializer=my_init)(inp)
conv_strides_valid = Model(inputs=inp, outputs=x2)
img_out = conv_strides_same.predict(np.expand_dims(sample_image, 0))
img_out2 = conv_strides_valid.predict(np.expand_dims(sample_image, 0))
show(img_out[0])
print("Shape of result with SAME padding:", img_out.shape)
print("Shape of result with VALID padding:", img_out2.shape)
# We observe that the stride divided the size of the image by 2
# In the case of 'VALID' padding mode, no padding is added, so
# the size of the ouput image is actually 1 less because of the
# kernel size
Update solution to be consistentdef my_init(shape=(5, 5, 3, 3), dtype=None):
array = np.zeros(shape=shape)
array[2, 2] = np.eye(3)
return array
conv_strides_same = Sequential([
Conv2D(filters=3, kernel_size=5, strides=2,
padding="same", kernel_initializer=my_init,
input_shape=(None, None, 3))
])
conv_strides_valid = Sequential([
Conv2D(filters=3, kernel_size=5, strides=2,
padding="valid", kernel_initializer=my_init,
input_shape=(None, None, 3))
])
img_in = np.expand_dims(sample_image, 0)
img_out_same = conv_strides_same.predict(img_in)
img_out_valid = conv_strides_valid.predict(img_in)
print("Shape of result with SAME padding:", img_out_same.shape)
print("Shape of result with VALID padding:", img_out_valid.shape)
fig, (ax0, ax1, ax2) = plt.subplots(ncols=3, figsize=(12, 4))
ax0.imshow(img_in[0].astype(np.uint8))
ax1.imshow(img_out_same[0].astype(np.uint8))
ax2.imshow(img_out_valid[0].astype(np.uint8))
# We observe that the stride divided the size of the image by 2
# In the case of 'VALID' padding mode, no padding is added, so
# the size of the ouput image is actually 1 less because of the
# kernel size
|
<commit_before>
def my_init(shape, dtype=None):
array = np.zeros(shape=(5,5,3,3))
array[2,2] = np.eye(3)
return array
inp = Input((None, None, 3), dtype="float32")
x = Conv2D(kernel_size=(5,5), filters=3, strides=2,
padding="same", kernel_initializer=my_init)(inp)
conv_strides_same = Model(inputs=inp, outputs=x)
x2 = Conv2D(kernel_size=(5,5), filters=3, strides=2,
padding="valid", kernel_initializer=my_init)(inp)
conv_strides_valid = Model(inputs=inp, outputs=x2)
img_out = conv_strides_same.predict(np.expand_dims(sample_image, 0))
img_out2 = conv_strides_valid.predict(np.expand_dims(sample_image, 0))
show(img_out[0])
print("Shape of result with SAME padding:", img_out.shape)
print("Shape of result with VALID padding:", img_out2.shape)
# We observe that the stride divided the size of the image by 2
# In the case of 'VALID' padding mode, no padding is added, so
# the size of the ouput image is actually 1 less because of the
# kernel size
<commit_msg>Update solution to be consistent<commit_after>def my_init(shape=(5, 5, 3, 3), dtype=None):
array = np.zeros(shape=shape)
array[2, 2] = np.eye(3)
return array
conv_strides_same = Sequential([
Conv2D(filters=3, kernel_size=5, strides=2,
padding="same", kernel_initializer=my_init,
input_shape=(None, None, 3))
])
conv_strides_valid = Sequential([
Conv2D(filters=3, kernel_size=5, strides=2,
padding="valid", kernel_initializer=my_init,
input_shape=(None, None, 3))
])
img_in = np.expand_dims(sample_image, 0)
img_out_same = conv_strides_same.predict(img_in)
img_out_valid = conv_strides_valid.predict(img_in)
print("Shape of result with SAME padding:", img_out_same.shape)
print("Shape of result with VALID padding:", img_out_valid.shape)
fig, (ax0, ax1, ax2) = plt.subplots(ncols=3, figsize=(12, 4))
ax0.imshow(img_in[0].astype(np.uint8))
ax1.imshow(img_out_same[0].astype(np.uint8))
ax2.imshow(img_out_valid[0].astype(np.uint8))
# We observe that the stride divided the size of the image by 2
# In the case of 'VALID' padding mode, no padding is added, so
# the size of the ouput image is actually 1 less because of the
# kernel size
|
72b9ff43daaf88f43ec4397cfed8fb860d4ad850
|
rest-api/test/client_test/base.py
|
rest-api/test/client_test/base.py
|
import copy
import json
import os
import unittest
from client.client import Client
# To run the tests against the test instance instead,
# set environment variable PMI_DRC_RDR_INSTANCE.
_DEFAULT_INSTANCE = 'http://localhost:8080'
_OFFLINE_BASE_PATH = 'offline'
class BaseClientTest(unittest.TestCase):
def setUp(self):
super(BaseClientTest, self).setUp()
self.maxDiff = None
instance = os.environ.get('PMI_DRC_RDR_INSTANCE') or _DEFAULT_INSTANCE
creds_file = os.environ.get('TESTING_CREDS_FILE')
self.client = Client(parse_cli=False, default_instance=instance, creds_file=creds_file)
self.offline_client = Client(
base_path=_OFFLINE_BASE_PATH,
parse_cli=False,
default_instance=instance,
creds_file=creds_file)
def assertJsonEquals(self, obj_a, obj_b):
obj_b = copy.deepcopy(obj_b)
for transient_key in ('etag', 'kind', 'meta'):
if transient_key in obj_b:
del obj_b[transient_key]
self.assertMultiLineEqual(_pretty(obj_a), _pretty(obj_b))
def _pretty(obj):
return json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': '))
|
import copy
import json
import os
import unittest
from client.client import Client
from tools.main_util import configure_logging
# To run the tests against the test instance instead,
# set environment variable PMI_DRC_RDR_INSTANCE.
_DEFAULT_INSTANCE = 'http://localhost:8080'
_OFFLINE_BASE_PATH = 'offline'
class BaseClientTest(unittest.TestCase):
def setUp(self):
super(BaseClientTest, self).setUp()
configure_logging()
self.maxDiff = None
instance = os.environ.get('PMI_DRC_RDR_INSTANCE') or _DEFAULT_INSTANCE
creds_file = os.environ.get('TESTING_CREDS_FILE')
self.client = Client(parse_cli=False, default_instance=instance, creds_file=creds_file)
self.offline_client = Client(
base_path=_OFFLINE_BASE_PATH,
parse_cli=False,
default_instance=instance,
creds_file=creds_file)
def assertJsonEquals(self, obj_a, obj_b):
obj_b = copy.deepcopy(obj_b)
for transient_key in ('etag', 'kind', 'meta'):
if transient_key in obj_b:
del obj_b[transient_key]
self.assertMultiLineEqual(_pretty(obj_a), _pretty(obj_b))
def _pretty(obj):
return json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': '))
|
Configure logging in client tests, so client logs show up.
|
Configure logging in client tests, so client logs show up.
|
Python
|
bsd-3-clause
|
all-of-us/raw-data-repository,all-of-us/raw-data-repository,all-of-us/raw-data-repository
|
import copy
import json
import os
import unittest
from client.client import Client
# To run the tests against the test instance instead,
# set environment variable PMI_DRC_RDR_INSTANCE.
_DEFAULT_INSTANCE = 'http://localhost:8080'
_OFFLINE_BASE_PATH = 'offline'
class BaseClientTest(unittest.TestCase):
def setUp(self):
super(BaseClientTest, self).setUp()
self.maxDiff = None
instance = os.environ.get('PMI_DRC_RDR_INSTANCE') or _DEFAULT_INSTANCE
creds_file = os.environ.get('TESTING_CREDS_FILE')
self.client = Client(parse_cli=False, default_instance=instance, creds_file=creds_file)
self.offline_client = Client(
base_path=_OFFLINE_BASE_PATH,
parse_cli=False,
default_instance=instance,
creds_file=creds_file)
def assertJsonEquals(self, obj_a, obj_b):
obj_b = copy.deepcopy(obj_b)
for transient_key in ('etag', 'kind', 'meta'):
if transient_key in obj_b:
del obj_b[transient_key]
self.assertMultiLineEqual(_pretty(obj_a), _pretty(obj_b))
def _pretty(obj):
return json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': '))
Configure logging in client tests, so client logs show up.
|
import copy
import json
import os
import unittest
from client.client import Client
from tools.main_util import configure_logging
# To run the tests against the test instance instead,
# set environment variable PMI_DRC_RDR_INSTANCE.
_DEFAULT_INSTANCE = 'http://localhost:8080'
_OFFLINE_BASE_PATH = 'offline'
class BaseClientTest(unittest.TestCase):
def setUp(self):
super(BaseClientTest, self).setUp()
configure_logging()
self.maxDiff = None
instance = os.environ.get('PMI_DRC_RDR_INSTANCE') or _DEFAULT_INSTANCE
creds_file = os.environ.get('TESTING_CREDS_FILE')
self.client = Client(parse_cli=False, default_instance=instance, creds_file=creds_file)
self.offline_client = Client(
base_path=_OFFLINE_BASE_PATH,
parse_cli=False,
default_instance=instance,
creds_file=creds_file)
def assertJsonEquals(self, obj_a, obj_b):
obj_b = copy.deepcopy(obj_b)
for transient_key in ('etag', 'kind', 'meta'):
if transient_key in obj_b:
del obj_b[transient_key]
self.assertMultiLineEqual(_pretty(obj_a), _pretty(obj_b))
def _pretty(obj):
return json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': '))
|
<commit_before>import copy
import json
import os
import unittest
from client.client import Client
# To run the tests against the test instance instead,
# set environment variable PMI_DRC_RDR_INSTANCE.
_DEFAULT_INSTANCE = 'http://localhost:8080'
_OFFLINE_BASE_PATH = 'offline'
class BaseClientTest(unittest.TestCase):
def setUp(self):
super(BaseClientTest, self).setUp()
self.maxDiff = None
instance = os.environ.get('PMI_DRC_RDR_INSTANCE') or _DEFAULT_INSTANCE
creds_file = os.environ.get('TESTING_CREDS_FILE')
self.client = Client(parse_cli=False, default_instance=instance, creds_file=creds_file)
self.offline_client = Client(
base_path=_OFFLINE_BASE_PATH,
parse_cli=False,
default_instance=instance,
creds_file=creds_file)
def assertJsonEquals(self, obj_a, obj_b):
obj_b = copy.deepcopy(obj_b)
for transient_key in ('etag', 'kind', 'meta'):
if transient_key in obj_b:
del obj_b[transient_key]
self.assertMultiLineEqual(_pretty(obj_a), _pretty(obj_b))
def _pretty(obj):
return json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': '))
<commit_msg>Configure logging in client tests, so client logs show up.<commit_after>
|
import copy
import json
import os
import unittest
from client.client import Client
from tools.main_util import configure_logging
# To run the tests against the test instance instead,
# set environment variable PMI_DRC_RDR_INSTANCE.
_DEFAULT_INSTANCE = 'http://localhost:8080'
_OFFLINE_BASE_PATH = 'offline'
class BaseClientTest(unittest.TestCase):
def setUp(self):
super(BaseClientTest, self).setUp()
configure_logging()
self.maxDiff = None
instance = os.environ.get('PMI_DRC_RDR_INSTANCE') or _DEFAULT_INSTANCE
creds_file = os.environ.get('TESTING_CREDS_FILE')
self.client = Client(parse_cli=False, default_instance=instance, creds_file=creds_file)
self.offline_client = Client(
base_path=_OFFLINE_BASE_PATH,
parse_cli=False,
default_instance=instance,
creds_file=creds_file)
def assertJsonEquals(self, obj_a, obj_b):
obj_b = copy.deepcopy(obj_b)
for transient_key in ('etag', 'kind', 'meta'):
if transient_key in obj_b:
del obj_b[transient_key]
self.assertMultiLineEqual(_pretty(obj_a), _pretty(obj_b))
def _pretty(obj):
return json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': '))
|
import copy
import json
import os
import unittest
from client.client import Client
# To run the tests against the test instance instead,
# set environment variable PMI_DRC_RDR_INSTANCE.
_DEFAULT_INSTANCE = 'http://localhost:8080'
_OFFLINE_BASE_PATH = 'offline'
class BaseClientTest(unittest.TestCase):
def setUp(self):
super(BaseClientTest, self).setUp()
self.maxDiff = None
instance = os.environ.get('PMI_DRC_RDR_INSTANCE') or _DEFAULT_INSTANCE
creds_file = os.environ.get('TESTING_CREDS_FILE')
self.client = Client(parse_cli=False, default_instance=instance, creds_file=creds_file)
self.offline_client = Client(
base_path=_OFFLINE_BASE_PATH,
parse_cli=False,
default_instance=instance,
creds_file=creds_file)
def assertJsonEquals(self, obj_a, obj_b):
obj_b = copy.deepcopy(obj_b)
for transient_key in ('etag', 'kind', 'meta'):
if transient_key in obj_b:
del obj_b[transient_key]
self.assertMultiLineEqual(_pretty(obj_a), _pretty(obj_b))
def _pretty(obj):
return json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': '))
Configure logging in client tests, so client logs show up.import copy
import json
import os
import unittest
from client.client import Client
from tools.main_util import configure_logging
# To run the tests against the test instance instead,
# set environment variable PMI_DRC_RDR_INSTANCE.
_DEFAULT_INSTANCE = 'http://localhost:8080'
_OFFLINE_BASE_PATH = 'offline'
class BaseClientTest(unittest.TestCase):
def setUp(self):
super(BaseClientTest, self).setUp()
configure_logging()
self.maxDiff = None
instance = os.environ.get('PMI_DRC_RDR_INSTANCE') or _DEFAULT_INSTANCE
creds_file = os.environ.get('TESTING_CREDS_FILE')
self.client = Client(parse_cli=False, default_instance=instance, creds_file=creds_file)
self.offline_client = Client(
base_path=_OFFLINE_BASE_PATH,
parse_cli=False,
default_instance=instance,
creds_file=creds_file)
def assertJsonEquals(self, obj_a, obj_b):
obj_b = copy.deepcopy(obj_b)
for transient_key in ('etag', 'kind', 'meta'):
if transient_key in obj_b:
del obj_b[transient_key]
self.assertMultiLineEqual(_pretty(obj_a), _pretty(obj_b))
def _pretty(obj):
return json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': '))
|
<commit_before>import copy
import json
import os
import unittest
from client.client import Client
# To run the tests against the test instance instead,
# set environment variable PMI_DRC_RDR_INSTANCE.
_DEFAULT_INSTANCE = 'http://localhost:8080'
_OFFLINE_BASE_PATH = 'offline'
class BaseClientTest(unittest.TestCase):
def setUp(self):
super(BaseClientTest, self).setUp()
self.maxDiff = None
instance = os.environ.get('PMI_DRC_RDR_INSTANCE') or _DEFAULT_INSTANCE
creds_file = os.environ.get('TESTING_CREDS_FILE')
self.client = Client(parse_cli=False, default_instance=instance, creds_file=creds_file)
self.offline_client = Client(
base_path=_OFFLINE_BASE_PATH,
parse_cli=False,
default_instance=instance,
creds_file=creds_file)
def assertJsonEquals(self, obj_a, obj_b):
obj_b = copy.deepcopy(obj_b)
for transient_key in ('etag', 'kind', 'meta'):
if transient_key in obj_b:
del obj_b[transient_key]
self.assertMultiLineEqual(_pretty(obj_a), _pretty(obj_b))
def _pretty(obj):
return json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': '))
<commit_msg>Configure logging in client tests, so client logs show up.<commit_after>import copy
import json
import os
import unittest
from client.client import Client
from tools.main_util import configure_logging
# To run the tests against the test instance instead,
# set environment variable PMI_DRC_RDR_INSTANCE.
_DEFAULT_INSTANCE = 'http://localhost:8080'
_OFFLINE_BASE_PATH = 'offline'
class BaseClientTest(unittest.TestCase):
def setUp(self):
super(BaseClientTest, self).setUp()
configure_logging()
self.maxDiff = None
instance = os.environ.get('PMI_DRC_RDR_INSTANCE') or _DEFAULT_INSTANCE
creds_file = os.environ.get('TESTING_CREDS_FILE')
self.client = Client(parse_cli=False, default_instance=instance, creds_file=creds_file)
self.offline_client = Client(
base_path=_OFFLINE_BASE_PATH,
parse_cli=False,
default_instance=instance,
creds_file=creds_file)
def assertJsonEquals(self, obj_a, obj_b):
obj_b = copy.deepcopy(obj_b)
for transient_key in ('etag', 'kind', 'meta'):
if transient_key in obj_b:
del obj_b[transient_key]
self.assertMultiLineEqual(_pretty(obj_a), _pretty(obj_b))
def _pretty(obj):
return json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': '))
|
b5d3425ae0a4a42e85748e494c3ddfaa7511f7b7
|
ocradmin/lib/nodetree/cache.py
|
ocradmin/lib/nodetree/cache.py
|
"""
Classes for customising node caching.
"""
class BasicCacher(object):
"""
Basic in-memory caching.
"""
def __init__(self, logger=None):
self._cache = {}
self.logger = logger
def set_cache(self, node, data):
"""
Store some data on the object.
"""
self._cache[node.label] = data
def get_cache(self, node):
"""
Return cached data.
"""
return self._cache.get(node.label)
def has_cache(self, node):
return self._cache.get(node.label) is not None
def clear_cache(self, node):
del self._cache[node.label]
def clear(self):
self._cache = {}
def __repr__(self):
return "<%s>" % self.__class__.__name__
|
"""
Classes for customising node caching.
"""
class BasicCacher(object):
"""
Basic in-memory caching.
"""
def __init__(self, logger=None):
self._cache = {}
self.logger = logger
def set_cache(self, node, data):
"""
Store some data on the object.
"""
self._cache[node.label] = data
def get_cache(self, node):
"""
Return cached data.
"""
return self._cache.get(node.label)
def has_cache(self, node):
return self._cache.get(node.label) is not None
def clear_cache(self, node):
if self._cache.get(node.label):
del self._cache[node.label]
def clear(self):
self._cache = {}
def __repr__(self):
return "<%s>" % self.__class__.__name__
|
Test for existence of node before clearing it
|
Test for existence of node before clearing it
|
Python
|
apache-2.0
|
vitorio/ocropodium,vitorio/ocropodium,vitorio/ocropodium,vitorio/ocropodium
|
"""
Classes for customising node caching.
"""
class BasicCacher(object):
"""
Basic in-memory caching.
"""
def __init__(self, logger=None):
self._cache = {}
self.logger = logger
def set_cache(self, node, data):
"""
Store some data on the object.
"""
self._cache[node.label] = data
def get_cache(self, node):
"""
Return cached data.
"""
return self._cache.get(node.label)
def has_cache(self, node):
return self._cache.get(node.label) is not None
def clear_cache(self, node):
del self._cache[node.label]
def clear(self):
self._cache = {}
def __repr__(self):
return "<%s>" % self.__class__.__name__
Test for existence of node before clearing it
|
"""
Classes for customising node caching.
"""
class BasicCacher(object):
"""
Basic in-memory caching.
"""
def __init__(self, logger=None):
self._cache = {}
self.logger = logger
def set_cache(self, node, data):
"""
Store some data on the object.
"""
self._cache[node.label] = data
def get_cache(self, node):
"""
Return cached data.
"""
return self._cache.get(node.label)
def has_cache(self, node):
return self._cache.get(node.label) is not None
def clear_cache(self, node):
if self._cache.get(node.label):
del self._cache[node.label]
def clear(self):
self._cache = {}
def __repr__(self):
return "<%s>" % self.__class__.__name__
|
<commit_before>"""
Classes for customising node caching.
"""
class BasicCacher(object):
"""
Basic in-memory caching.
"""
def __init__(self, logger=None):
self._cache = {}
self.logger = logger
def set_cache(self, node, data):
"""
Store some data on the object.
"""
self._cache[node.label] = data
def get_cache(self, node):
"""
Return cached data.
"""
return self._cache.get(node.label)
def has_cache(self, node):
return self._cache.get(node.label) is not None
def clear_cache(self, node):
del self._cache[node.label]
def clear(self):
self._cache = {}
def __repr__(self):
return "<%s>" % self.__class__.__name__
<commit_msg>Test for existence of node before clearing it<commit_after>
|
"""
Classes for customising node caching.
"""
class BasicCacher(object):
"""
Basic in-memory caching.
"""
def __init__(self, logger=None):
self._cache = {}
self.logger = logger
def set_cache(self, node, data):
"""
Store some data on the object.
"""
self._cache[node.label] = data
def get_cache(self, node):
"""
Return cached data.
"""
return self._cache.get(node.label)
def has_cache(self, node):
return self._cache.get(node.label) is not None
def clear_cache(self, node):
if self._cache.get(node.label):
del self._cache[node.label]
def clear(self):
self._cache = {}
def __repr__(self):
return "<%s>" % self.__class__.__name__
|
"""
Classes for customising node caching.
"""
class BasicCacher(object):
"""
Basic in-memory caching.
"""
def __init__(self, logger=None):
self._cache = {}
self.logger = logger
def set_cache(self, node, data):
"""
Store some data on the object.
"""
self._cache[node.label] = data
def get_cache(self, node):
"""
Return cached data.
"""
return self._cache.get(node.label)
def has_cache(self, node):
return self._cache.get(node.label) is not None
def clear_cache(self, node):
del self._cache[node.label]
def clear(self):
self._cache = {}
def __repr__(self):
return "<%s>" % self.__class__.__name__
Test for existence of node before clearing it"""
Classes for customising node caching.
"""
class BasicCacher(object):
"""
Basic in-memory caching.
"""
def __init__(self, logger=None):
self._cache = {}
self.logger = logger
def set_cache(self, node, data):
"""
Store some data on the object.
"""
self._cache[node.label] = data
def get_cache(self, node):
"""
Return cached data.
"""
return self._cache.get(node.label)
def has_cache(self, node):
return self._cache.get(node.label) is not None
def clear_cache(self, node):
if self._cache.get(node.label):
del self._cache[node.label]
def clear(self):
self._cache = {}
def __repr__(self):
return "<%s>" % self.__class__.__name__
|
<commit_before>"""
Classes for customising node caching.
"""
class BasicCacher(object):
"""
Basic in-memory caching.
"""
def __init__(self, logger=None):
self._cache = {}
self.logger = logger
def set_cache(self, node, data):
"""
Store some data on the object.
"""
self._cache[node.label] = data
def get_cache(self, node):
"""
Return cached data.
"""
return self._cache.get(node.label)
def has_cache(self, node):
return self._cache.get(node.label) is not None
def clear_cache(self, node):
del self._cache[node.label]
def clear(self):
self._cache = {}
def __repr__(self):
return "<%s>" % self.__class__.__name__
<commit_msg>Test for existence of node before clearing it<commit_after>"""
Classes for customising node caching.
"""
class BasicCacher(object):
"""
Basic in-memory caching.
"""
def __init__(self, logger=None):
self._cache = {}
self.logger = logger
def set_cache(self, node, data):
"""
Store some data on the object.
"""
self._cache[node.label] = data
def get_cache(self, node):
"""
Return cached data.
"""
return self._cache.get(node.label)
def has_cache(self, node):
return self._cache.get(node.label) is not None
def clear_cache(self, node):
if self._cache.get(node.label):
del self._cache[node.label]
def clear(self):
self._cache = {}
def __repr__(self):
return "<%s>" % self.__class__.__name__
|
1934229ace3bd35b98e3eaa9b8ec75a1000dea78
|
djkombu/transport.py
|
djkombu/transport.py
|
from Queue import Empty
from anyjson import serialize, deserialize
from kombu.transport import virtual
from django.conf import settings
from django.core import exceptions as errors
from djkombu.models import Queue
POLLING_INTERVAL = getattr(settings, "DJKOMBU_POLLING_INTERVAL", 5.0)
class Channel(virtual.Channel):
def _new_queue(self, queue, **kwargs):
Queue.objects.get_or_create(name=queue)
def _put(self, queue, message, **kwargs):
Queue.objects.publish(queue, serialize(message))
def basic_consume(self, queue, *args, **kwargs):
exchange, _ , _ = self.state.bindings[queue]
if self.typeof(exchange).type == "fanout":
return
super(Channel, self).basic_consume(queue, *args, **kwargs)
def _get(self, queue):
#self.refresh_connection()
m = Queue.objects.fetch(queue)
if m:
return deserialize(m)
raise Empty()
def _size(self, queue):
return Queue.objects.size(queue)
def _purge(self, queue):
return Queue.objects.purge(queue)
def refresh_connection(self):
from django import db
db.close_connection()
class DatabaseTransport(virtual.Transport):
Channel = Channel
default_port = 0
polling_interval = POLLING_INTERVAL
connection_errors = ()
channel_errors = (errors.ObjectDoesNotExist,
errors.MultipleObjectsReturned)
|
from Queue import Empty
from anyjson import serialize, deserialize
from kombu.transport import virtual
from django.conf import settings
from django.core import exceptions as errors
from djkombu.models import Queue
POLLING_INTERVAL = getattr(settings, "DJKOMBU_POLLING_INTERVAL", 5.0)
class Channel(virtual.Channel):
def _new_queue(self, queue, **kwargs):
Queue.objects.get_or_create(name=queue)
def _put(self, queue, message, **kwargs):
Queue.objects.publish(queue, serialize(message))
def basic_consume(self, queue, *args, **kwargs):
qinfo = self.state.bindings[queue]
exchange = qinfo[0]
if self.typeof(exchange).type == "fanout":
return
super(Channel, self).basic_consume(queue, *args, **kwargs)
def _get(self, queue):
#self.refresh_connection()
m = Queue.objects.fetch(queue)
if m:
return deserialize(m)
raise Empty()
def _size(self, queue):
return Queue.objects.size(queue)
def _purge(self, queue):
return Queue.objects.purge(queue)
def refresh_connection(self):
from django import db
db.close_connection()
class DatabaseTransport(virtual.Transport):
Channel = Channel
default_port = 0
polling_interval = POLLING_INTERVAL
connection_errors = ()
channel_errors = (errors.ObjectDoesNotExist,
errors.MultipleObjectsReturned)
|
Work with new and *older* kombu versions
|
Work with new and *older* kombu versions
|
Python
|
bsd-3-clause
|
ask/django-kombu
|
from Queue import Empty
from anyjson import serialize, deserialize
from kombu.transport import virtual
from django.conf import settings
from django.core import exceptions as errors
from djkombu.models import Queue
POLLING_INTERVAL = getattr(settings, "DJKOMBU_POLLING_INTERVAL", 5.0)
class Channel(virtual.Channel):
def _new_queue(self, queue, **kwargs):
Queue.objects.get_or_create(name=queue)
def _put(self, queue, message, **kwargs):
Queue.objects.publish(queue, serialize(message))
def basic_consume(self, queue, *args, **kwargs):
exchange, _ , _ = self.state.bindings[queue]
if self.typeof(exchange).type == "fanout":
return
super(Channel, self).basic_consume(queue, *args, **kwargs)
def _get(self, queue):
#self.refresh_connection()
m = Queue.objects.fetch(queue)
if m:
return deserialize(m)
raise Empty()
def _size(self, queue):
return Queue.objects.size(queue)
def _purge(self, queue):
return Queue.objects.purge(queue)
def refresh_connection(self):
from django import db
db.close_connection()
class DatabaseTransport(virtual.Transport):
Channel = Channel
default_port = 0
polling_interval = POLLING_INTERVAL
connection_errors = ()
channel_errors = (errors.ObjectDoesNotExist,
errors.MultipleObjectsReturned)
Work with new and *older* kombu versions
|
from Queue import Empty
from anyjson import serialize, deserialize
from kombu.transport import virtual
from django.conf import settings
from django.core import exceptions as errors
from djkombu.models import Queue
POLLING_INTERVAL = getattr(settings, "DJKOMBU_POLLING_INTERVAL", 5.0)
class Channel(virtual.Channel):
def _new_queue(self, queue, **kwargs):
Queue.objects.get_or_create(name=queue)
def _put(self, queue, message, **kwargs):
Queue.objects.publish(queue, serialize(message))
def basic_consume(self, queue, *args, **kwargs):
qinfo = self.state.bindings[queue]
exchange = qinfo[0]
if self.typeof(exchange).type == "fanout":
return
super(Channel, self).basic_consume(queue, *args, **kwargs)
def _get(self, queue):
#self.refresh_connection()
m = Queue.objects.fetch(queue)
if m:
return deserialize(m)
raise Empty()
def _size(self, queue):
return Queue.objects.size(queue)
def _purge(self, queue):
return Queue.objects.purge(queue)
def refresh_connection(self):
from django import db
db.close_connection()
class DatabaseTransport(virtual.Transport):
Channel = Channel
default_port = 0
polling_interval = POLLING_INTERVAL
connection_errors = ()
channel_errors = (errors.ObjectDoesNotExist,
errors.MultipleObjectsReturned)
|
<commit_before>from Queue import Empty
from anyjson import serialize, deserialize
from kombu.transport import virtual
from django.conf import settings
from django.core import exceptions as errors
from djkombu.models import Queue
POLLING_INTERVAL = getattr(settings, "DJKOMBU_POLLING_INTERVAL", 5.0)
class Channel(virtual.Channel):
def _new_queue(self, queue, **kwargs):
Queue.objects.get_or_create(name=queue)
def _put(self, queue, message, **kwargs):
Queue.objects.publish(queue, serialize(message))
def basic_consume(self, queue, *args, **kwargs):
exchange, _ , _ = self.state.bindings[queue]
if self.typeof(exchange).type == "fanout":
return
super(Channel, self).basic_consume(queue, *args, **kwargs)
def _get(self, queue):
#self.refresh_connection()
m = Queue.objects.fetch(queue)
if m:
return deserialize(m)
raise Empty()
def _size(self, queue):
return Queue.objects.size(queue)
def _purge(self, queue):
return Queue.objects.purge(queue)
def refresh_connection(self):
from django import db
db.close_connection()
class DatabaseTransport(virtual.Transport):
Channel = Channel
default_port = 0
polling_interval = POLLING_INTERVAL
connection_errors = ()
channel_errors = (errors.ObjectDoesNotExist,
errors.MultipleObjectsReturned)
<commit_msg>Work with new and *older* kombu versions<commit_after>
|
from Queue import Empty
from anyjson import serialize, deserialize
from kombu.transport import virtual
from django.conf import settings
from django.core import exceptions as errors
from djkombu.models import Queue
POLLING_INTERVAL = getattr(settings, "DJKOMBU_POLLING_INTERVAL", 5.0)
class Channel(virtual.Channel):
def _new_queue(self, queue, **kwargs):
Queue.objects.get_or_create(name=queue)
def _put(self, queue, message, **kwargs):
Queue.objects.publish(queue, serialize(message))
def basic_consume(self, queue, *args, **kwargs):
qinfo = self.state.bindings[queue]
exchange = qinfo[0]
if self.typeof(exchange).type == "fanout":
return
super(Channel, self).basic_consume(queue, *args, **kwargs)
def _get(self, queue):
#self.refresh_connection()
m = Queue.objects.fetch(queue)
if m:
return deserialize(m)
raise Empty()
def _size(self, queue):
return Queue.objects.size(queue)
def _purge(self, queue):
return Queue.objects.purge(queue)
def refresh_connection(self):
from django import db
db.close_connection()
class DatabaseTransport(virtual.Transport):
Channel = Channel
default_port = 0
polling_interval = POLLING_INTERVAL
connection_errors = ()
channel_errors = (errors.ObjectDoesNotExist,
errors.MultipleObjectsReturned)
|
from Queue import Empty
from anyjson import serialize, deserialize
from kombu.transport import virtual
from django.conf import settings
from django.core import exceptions as errors
from djkombu.models import Queue
POLLING_INTERVAL = getattr(settings, "DJKOMBU_POLLING_INTERVAL", 5.0)
class Channel(virtual.Channel):
def _new_queue(self, queue, **kwargs):
Queue.objects.get_or_create(name=queue)
def _put(self, queue, message, **kwargs):
Queue.objects.publish(queue, serialize(message))
def basic_consume(self, queue, *args, **kwargs):
exchange, _ , _ = self.state.bindings[queue]
if self.typeof(exchange).type == "fanout":
return
super(Channel, self).basic_consume(queue, *args, **kwargs)
def _get(self, queue):
#self.refresh_connection()
m = Queue.objects.fetch(queue)
if m:
return deserialize(m)
raise Empty()
def _size(self, queue):
return Queue.objects.size(queue)
def _purge(self, queue):
return Queue.objects.purge(queue)
def refresh_connection(self):
from django import db
db.close_connection()
class DatabaseTransport(virtual.Transport):
Channel = Channel
default_port = 0
polling_interval = POLLING_INTERVAL
connection_errors = ()
channel_errors = (errors.ObjectDoesNotExist,
errors.MultipleObjectsReturned)
Work with new and *older* kombu versionsfrom Queue import Empty
from anyjson import serialize, deserialize
from kombu.transport import virtual
from django.conf import settings
from django.core import exceptions as errors
from djkombu.models import Queue
POLLING_INTERVAL = getattr(settings, "DJKOMBU_POLLING_INTERVAL", 5.0)
class Channel(virtual.Channel):
def _new_queue(self, queue, **kwargs):
Queue.objects.get_or_create(name=queue)
def _put(self, queue, message, **kwargs):
Queue.objects.publish(queue, serialize(message))
def basic_consume(self, queue, *args, **kwargs):
qinfo = self.state.bindings[queue]
exchange = qinfo[0]
if self.typeof(exchange).type == "fanout":
return
super(Channel, self).basic_consume(queue, *args, **kwargs)
def _get(self, queue):
#self.refresh_connection()
m = Queue.objects.fetch(queue)
if m:
return deserialize(m)
raise Empty()
def _size(self, queue):
return Queue.objects.size(queue)
def _purge(self, queue):
return Queue.objects.purge(queue)
def refresh_connection(self):
from django import db
db.close_connection()
class DatabaseTransport(virtual.Transport):
Channel = Channel
default_port = 0
polling_interval = POLLING_INTERVAL
connection_errors = ()
channel_errors = (errors.ObjectDoesNotExist,
errors.MultipleObjectsReturned)
|
<commit_before>from Queue import Empty
from anyjson import serialize, deserialize
from kombu.transport import virtual
from django.conf import settings
from django.core import exceptions as errors
from djkombu.models import Queue
POLLING_INTERVAL = getattr(settings, "DJKOMBU_POLLING_INTERVAL", 5.0)
class Channel(virtual.Channel):
def _new_queue(self, queue, **kwargs):
Queue.objects.get_or_create(name=queue)
def _put(self, queue, message, **kwargs):
Queue.objects.publish(queue, serialize(message))
def basic_consume(self, queue, *args, **kwargs):
exchange, _ , _ = self.state.bindings[queue]
if self.typeof(exchange).type == "fanout":
return
super(Channel, self).basic_consume(queue, *args, **kwargs)
def _get(self, queue):
#self.refresh_connection()
m = Queue.objects.fetch(queue)
if m:
return deserialize(m)
raise Empty()
def _size(self, queue):
return Queue.objects.size(queue)
def _purge(self, queue):
return Queue.objects.purge(queue)
def refresh_connection(self):
from django import db
db.close_connection()
class DatabaseTransport(virtual.Transport):
Channel = Channel
default_port = 0
polling_interval = POLLING_INTERVAL
connection_errors = ()
channel_errors = (errors.ObjectDoesNotExist,
errors.MultipleObjectsReturned)
<commit_msg>Work with new and *older* kombu versions<commit_after>from Queue import Empty
from anyjson import serialize, deserialize
from kombu.transport import virtual
from django.conf import settings
from django.core import exceptions as errors
from djkombu.models import Queue
POLLING_INTERVAL = getattr(settings, "DJKOMBU_POLLING_INTERVAL", 5.0)
class Channel(virtual.Channel):
def _new_queue(self, queue, **kwargs):
Queue.objects.get_or_create(name=queue)
def _put(self, queue, message, **kwargs):
Queue.objects.publish(queue, serialize(message))
def basic_consume(self, queue, *args, **kwargs):
qinfo = self.state.bindings[queue]
exchange = qinfo[0]
if self.typeof(exchange).type == "fanout":
return
super(Channel, self).basic_consume(queue, *args, **kwargs)
def _get(self, queue):
#self.refresh_connection()
m = Queue.objects.fetch(queue)
if m:
return deserialize(m)
raise Empty()
def _size(self, queue):
return Queue.objects.size(queue)
def _purge(self, queue):
return Queue.objects.purge(queue)
def refresh_connection(self):
from django import db
db.close_connection()
class DatabaseTransport(virtual.Transport):
Channel = Channel
default_port = 0
polling_interval = POLLING_INTERVAL
connection_errors = ()
channel_errors = (errors.ObjectDoesNotExist,
errors.MultipleObjectsReturned)
|
54dbc3638ba376f29aa619e897c9b87238559ac3
|
billjobs/tests/tests_export_account_email.py
|
billjobs/tests/tests_export_account_email.py
|
from django.test import TestCase
from django.http import HttpResponse
from django.contrib.admin.sites import AdminSite
from django.contrib.auth.models import User
from billjobs.admin import UserAdmin
class EmailExportTestCase(TestCase):
""" Tests for email account export """
def test_method_is_avaible(self):
""" Test admin can select the action in dropdown list """
self.assertTrue(hasattr(UserAdmin, 'export_email'))
def test_method_is_model_admin_action(self):
""" Test method is an custom action for user admin """
self.assertTrue('export_email' in UserAdmin.actions)
def test_action_has_a_short_description(self):
""" Test method has a short description """
self.assertEqual(UserAdmin.export_email.short_description,
'Export email of selected users')
def test_action_return_http_response(self):
class MockRequest(object):
pass
site = AdminSite()
user_admin = UserAdmin(User, site)
query_set = User.objects.all()
response = user_admin.export_email(request=MockRequest(), queryset=query_set)
self.assertIsInstance(response, HttpResponse)
|
from django.test import TestCase
from django.http import HttpResponse
from django.contrib.admin.sites import AdminSite
from django.contrib.auth.models import User
from billjobs.admin import UserAdmin
class MockRequest(object):
pass
class EmailExportTestCase(TestCase):
""" Tests for email account export """
def setUp(self):
self.site = AdminSite()
self.query_set = User.objects.all()
def test_method_is_avaible(self):
""" Test admin can select the action in dropdown list """
self.assertTrue(hasattr(UserAdmin, 'export_email'))
def test_method_is_model_admin_action(self):
""" Test method is an custom action for user admin """
self.assertTrue('export_email' in UserAdmin.actions)
def test_action_has_a_short_description(self):
""" Test method has a short description """
self.assertEqual(UserAdmin.export_email.short_description,
'Export email of selected users')
def test_action_return_http_response(self):
user_admin = UserAdmin(User, self.site)
response = user_admin.export_email(request=MockRequest(), queryset=self.query_set)
self.assertIsInstance(response, HttpResponse)
def test_action_return_csv(self):
user_admin = UserAdmin(User, self.site)
response = user_admin.export_email(request=MockRequest(), queryset=self.query_set)
self.assertEqual(response.get('Content-Type'), 'text/csv')
|
Refactor test, test export email return text/csv content type
|
Refactor test, test export email return text/csv content type
|
Python
|
mit
|
ioO/billjobs
|
from django.test import TestCase
from django.http import HttpResponse
from django.contrib.admin.sites import AdminSite
from django.contrib.auth.models import User
from billjobs.admin import UserAdmin
class EmailExportTestCase(TestCase):
""" Tests for email account export """
def test_method_is_avaible(self):
""" Test admin can select the action in dropdown list """
self.assertTrue(hasattr(UserAdmin, 'export_email'))
def test_method_is_model_admin_action(self):
""" Test method is an custom action for user admin """
self.assertTrue('export_email' in UserAdmin.actions)
def test_action_has_a_short_description(self):
""" Test method has a short description """
self.assertEqual(UserAdmin.export_email.short_description,
'Export email of selected users')
def test_action_return_http_response(self):
class MockRequest(object):
pass
site = AdminSite()
user_admin = UserAdmin(User, site)
query_set = User.objects.all()
response = user_admin.export_email(request=MockRequest(), queryset=query_set)
self.assertIsInstance(response, HttpResponse)
Refactor test, test export email return text/csv content type
|
from django.test import TestCase
from django.http import HttpResponse
from django.contrib.admin.sites import AdminSite
from django.contrib.auth.models import User
from billjobs.admin import UserAdmin
class MockRequest(object):
pass
class EmailExportTestCase(TestCase):
""" Tests for email account export """
def setUp(self):
self.site = AdminSite()
self.query_set = User.objects.all()
def test_method_is_avaible(self):
""" Test admin can select the action in dropdown list """
self.assertTrue(hasattr(UserAdmin, 'export_email'))
def test_method_is_model_admin_action(self):
""" Test method is an custom action for user admin """
self.assertTrue('export_email' in UserAdmin.actions)
def test_action_has_a_short_description(self):
""" Test method has a short description """
self.assertEqual(UserAdmin.export_email.short_description,
'Export email of selected users')
def test_action_return_http_response(self):
user_admin = UserAdmin(User, self.site)
response = user_admin.export_email(request=MockRequest(), queryset=self.query_set)
self.assertIsInstance(response, HttpResponse)
def test_action_return_csv(self):
user_admin = UserAdmin(User, self.site)
response = user_admin.export_email(request=MockRequest(), queryset=self.query_set)
self.assertEqual(response.get('Content-Type'), 'text/csv')
|
<commit_before>from django.test import TestCase
from django.http import HttpResponse
from django.contrib.admin.sites import AdminSite
from django.contrib.auth.models import User
from billjobs.admin import UserAdmin
class EmailExportTestCase(TestCase):
""" Tests for email account export """
def test_method_is_avaible(self):
""" Test admin can select the action in dropdown list """
self.assertTrue(hasattr(UserAdmin, 'export_email'))
def test_method_is_model_admin_action(self):
""" Test method is an custom action for user admin """
self.assertTrue('export_email' in UserAdmin.actions)
def test_action_has_a_short_description(self):
""" Test method has a short description """
self.assertEqual(UserAdmin.export_email.short_description,
'Export email of selected users')
def test_action_return_http_response(self):
class MockRequest(object):
pass
site = AdminSite()
user_admin = UserAdmin(User, site)
query_set = User.objects.all()
response = user_admin.export_email(request=MockRequest(), queryset=query_set)
self.assertIsInstance(response, HttpResponse)
<commit_msg>Refactor test, test export email return text/csv content type<commit_after>
|
from django.test import TestCase
from django.http import HttpResponse
from django.contrib.admin.sites import AdminSite
from django.contrib.auth.models import User
from billjobs.admin import UserAdmin
class MockRequest(object):
pass
class EmailExportTestCase(TestCase):
""" Tests for email account export """
def setUp(self):
self.site = AdminSite()
self.query_set = User.objects.all()
def test_method_is_avaible(self):
""" Test admin can select the action in dropdown list """
self.assertTrue(hasattr(UserAdmin, 'export_email'))
def test_method_is_model_admin_action(self):
""" Test method is an custom action for user admin """
self.assertTrue('export_email' in UserAdmin.actions)
def test_action_has_a_short_description(self):
""" Test method has a short description """
self.assertEqual(UserAdmin.export_email.short_description,
'Export email of selected users')
def test_action_return_http_response(self):
user_admin = UserAdmin(User, self.site)
response = user_admin.export_email(request=MockRequest(), queryset=self.query_set)
self.assertIsInstance(response, HttpResponse)
def test_action_return_csv(self):
user_admin = UserAdmin(User, self.site)
response = user_admin.export_email(request=MockRequest(), queryset=self.query_set)
self.assertEqual(response.get('Content-Type'), 'text/csv')
|
from django.test import TestCase
from django.http import HttpResponse
from django.contrib.admin.sites import AdminSite
from django.contrib.auth.models import User
from billjobs.admin import UserAdmin
class EmailExportTestCase(TestCase):
""" Tests for email account export """
def test_method_is_avaible(self):
""" Test admin can select the action in dropdown list """
self.assertTrue(hasattr(UserAdmin, 'export_email'))
def test_method_is_model_admin_action(self):
""" Test method is an custom action for user admin """
self.assertTrue('export_email' in UserAdmin.actions)
def test_action_has_a_short_description(self):
""" Test method has a short description """
self.assertEqual(UserAdmin.export_email.short_description,
'Export email of selected users')
def test_action_return_http_response(self):
class MockRequest(object):
pass
site = AdminSite()
user_admin = UserAdmin(User, site)
query_set = User.objects.all()
response = user_admin.export_email(request=MockRequest(), queryset=query_set)
self.assertIsInstance(response, HttpResponse)
Refactor test, test export email return text/csv content typefrom django.test import TestCase
from django.http import HttpResponse
from django.contrib.admin.sites import AdminSite
from django.contrib.auth.models import User
from billjobs.admin import UserAdmin
class MockRequest(object):
pass
class EmailExportTestCase(TestCase):
""" Tests for email account export """
def setUp(self):
self.site = AdminSite()
self.query_set = User.objects.all()
def test_method_is_avaible(self):
""" Test admin can select the action in dropdown list """
self.assertTrue(hasattr(UserAdmin, 'export_email'))
def test_method_is_model_admin_action(self):
""" Test method is an custom action for user admin """
self.assertTrue('export_email' in UserAdmin.actions)
def test_action_has_a_short_description(self):
""" Test method has a short description """
self.assertEqual(UserAdmin.export_email.short_description,
'Export email of selected users')
def test_action_return_http_response(self):
user_admin = UserAdmin(User, self.site)
response = user_admin.export_email(request=MockRequest(), queryset=self.query_set)
self.assertIsInstance(response, HttpResponse)
def test_action_return_csv(self):
user_admin = UserAdmin(User, self.site)
response = user_admin.export_email(request=MockRequest(), queryset=self.query_set)
self.assertEqual(response.get('Content-Type'), 'text/csv')
|
<commit_before>from django.test import TestCase
from django.http import HttpResponse
from django.contrib.admin.sites import AdminSite
from django.contrib.auth.models import User
from billjobs.admin import UserAdmin
class EmailExportTestCase(TestCase):
""" Tests for email account export """
def test_method_is_avaible(self):
""" Test admin can select the action in dropdown list """
self.assertTrue(hasattr(UserAdmin, 'export_email'))
def test_method_is_model_admin_action(self):
""" Test method is an custom action for user admin """
self.assertTrue('export_email' in UserAdmin.actions)
def test_action_has_a_short_description(self):
""" Test method has a short description """
self.assertEqual(UserAdmin.export_email.short_description,
'Export email of selected users')
def test_action_return_http_response(self):
class MockRequest(object):
pass
site = AdminSite()
user_admin = UserAdmin(User, site)
query_set = User.objects.all()
response = user_admin.export_email(request=MockRequest(), queryset=query_set)
self.assertIsInstance(response, HttpResponse)
<commit_msg>Refactor test, test export email return text/csv content type<commit_after>from django.test import TestCase
from django.http import HttpResponse
from django.contrib.admin.sites import AdminSite
from django.contrib.auth.models import User
from billjobs.admin import UserAdmin
class MockRequest(object):
pass
class EmailExportTestCase(TestCase):
""" Tests for email account export """
def setUp(self):
self.site = AdminSite()
self.query_set = User.objects.all()
def test_method_is_avaible(self):
""" Test admin can select the action in dropdown list """
self.assertTrue(hasattr(UserAdmin, 'export_email'))
def test_method_is_model_admin_action(self):
""" Test method is an custom action for user admin """
self.assertTrue('export_email' in UserAdmin.actions)
def test_action_has_a_short_description(self):
""" Test method has a short description """
self.assertEqual(UserAdmin.export_email.short_description,
'Export email of selected users')
def test_action_return_http_response(self):
user_admin = UserAdmin(User, self.site)
response = user_admin.export_email(request=MockRequest(), queryset=self.query_set)
self.assertIsInstance(response, HttpResponse)
def test_action_return_csv(self):
user_admin = UserAdmin(User, self.site)
response = user_admin.export_email(request=MockRequest(), queryset=self.query_set)
self.assertEqual(response.get('Content-Type'), 'text/csv')
|
2c449a27be2e9e9ec57cc6f8e31825064195290d
|
modules/weather_module/weather_module.py
|
modules/weather_module/weather_module.py
|
import juliet_module
from pygame import Rect
from time import time
from os import getcwd
class weather_module(juliet_module.module):
mod_name = "weather_module"
__last_update = time()
__api = None
def __init__(self, _id, _keyfile):
print("Initializing Weather Module")
self.mod_id = _id
with open(_keyfile, 'r') as f:
self.__api = f.read()
def draw(self, surf):
"Takes a surface object and blits its data onto it"
print("Draw call of Weather Module")
def update(self):
"Update this module's internal state (do things like time updates, get weather, etc."
# print("Update call of Weather Module")
def new_module(_id = -1, _keyfile = 'modules/weather_module/api.key'):
return weather_module(_id, _keyfile)
|
import juliet_module
from pygame import Rect
from time import time
import forecastio
class weather_module(juliet_module.module):
mod_name = "weather_module"
__last_update = time()
__api = None
__forecast = None
def __init__(self, _id, _keyfile):
print("Initializing Weather Module")
self.mod_id = _id
with open(_keyfile, 'r') as f:
self.__api = f.read()[:-1]
lat = 40.7127
lng = 74.0059
forecastio.load_forecast(self.__api, lat, lng, units = "us", callback=self.request_callback)
def draw(self, surf):
"Takes a surface object and blits its data onto it"
print("Draw call of Weather Module")
def update(self):
"Update this module's internal state (do things like time updates, get weather, etc."
# print("Update call of Weather Module")
def request_callback(self, forecast):
self.__forecast = forecast
print(self.__forecast.daily().summary)
def new_module(_id = -1, _keyfile = 'modules/weather_module/api.key'):
return weather_module(_id, _keyfile)
|
Add test forecast.io API call
|
Add test forecast.io API call
|
Python
|
bsd-2-clause
|
halfbro/juliet
|
import juliet_module
from pygame import Rect
from time import time
from os import getcwd
class weather_module(juliet_module.module):
mod_name = "weather_module"
__last_update = time()
__api = None
def __init__(self, _id, _keyfile):
print("Initializing Weather Module")
self.mod_id = _id
with open(_keyfile, 'r') as f:
self.__api = f.read()
def draw(self, surf):
"Takes a surface object and blits its data onto it"
print("Draw call of Weather Module")
def update(self):
"Update this module's internal state (do things like time updates, get weather, etc."
# print("Update call of Weather Module")
def new_module(_id = -1, _keyfile = 'modules/weather_module/api.key'):
return weather_module(_id, _keyfile)
Add test forecast.io API call
|
import juliet_module
from pygame import Rect
from time import time
import forecastio
class weather_module(juliet_module.module):
mod_name = "weather_module"
__last_update = time()
__api = None
__forecast = None
def __init__(self, _id, _keyfile):
print("Initializing Weather Module")
self.mod_id = _id
with open(_keyfile, 'r') as f:
self.__api = f.read()[:-1]
lat = 40.7127
lng = 74.0059
forecastio.load_forecast(self.__api, lat, lng, units = "us", callback=self.request_callback)
def draw(self, surf):
"Takes a surface object and blits its data onto it"
print("Draw call of Weather Module")
def update(self):
"Update this module's internal state (do things like time updates, get weather, etc."
# print("Update call of Weather Module")
def request_callback(self, forecast):
self.__forecast = forecast
print(self.__forecast.daily().summary)
def new_module(_id = -1, _keyfile = 'modules/weather_module/api.key'):
return weather_module(_id, _keyfile)
|
<commit_before>import juliet_module
from pygame import Rect
from time import time
from os import getcwd
class weather_module(juliet_module.module):
mod_name = "weather_module"
__last_update = time()
__api = None
def __init__(self, _id, _keyfile):
print("Initializing Weather Module")
self.mod_id = _id
with open(_keyfile, 'r') as f:
self.__api = f.read()
def draw(self, surf):
"Takes a surface object and blits its data onto it"
print("Draw call of Weather Module")
def update(self):
"Update this module's internal state (do things like time updates, get weather, etc."
# print("Update call of Weather Module")
def new_module(_id = -1, _keyfile = 'modules/weather_module/api.key'):
return weather_module(_id, _keyfile)
<commit_msg>Add test forecast.io API call<commit_after>
|
import juliet_module
from pygame import Rect
from time import time
import forecastio
class weather_module(juliet_module.module):
mod_name = "weather_module"
__last_update = time()
__api = None
__forecast = None
def __init__(self, _id, _keyfile):
print("Initializing Weather Module")
self.mod_id = _id
with open(_keyfile, 'r') as f:
self.__api = f.read()[:-1]
lat = 40.7127
lng = 74.0059
forecastio.load_forecast(self.__api, lat, lng, units = "us", callback=self.request_callback)
def draw(self, surf):
"Takes a surface object and blits its data onto it"
print("Draw call of Weather Module")
def update(self):
"Update this module's internal state (do things like time updates, get weather, etc."
# print("Update call of Weather Module")
def request_callback(self, forecast):
self.__forecast = forecast
print(self.__forecast.daily().summary)
def new_module(_id = -1, _keyfile = 'modules/weather_module/api.key'):
return weather_module(_id, _keyfile)
|
import juliet_module
from pygame import Rect
from time import time
from os import getcwd
class weather_module(juliet_module.module):
mod_name = "weather_module"
__last_update = time()
__api = None
def __init__(self, _id, _keyfile):
print("Initializing Weather Module")
self.mod_id = _id
with open(_keyfile, 'r') as f:
self.__api = f.read()
def draw(self, surf):
"Takes a surface object and blits its data onto it"
print("Draw call of Weather Module")
def update(self):
"Update this module's internal state (do things like time updates, get weather, etc."
# print("Update call of Weather Module")
def new_module(_id = -1, _keyfile = 'modules/weather_module/api.key'):
return weather_module(_id, _keyfile)
Add test forecast.io API callimport juliet_module
from pygame import Rect
from time import time
import forecastio
class weather_module(juliet_module.module):
mod_name = "weather_module"
__last_update = time()
__api = None
__forecast = None
def __init__(self, _id, _keyfile):
print("Initializing Weather Module")
self.mod_id = _id
with open(_keyfile, 'r') as f:
self.__api = f.read()[:-1]
lat = 40.7127
lng = 74.0059
forecastio.load_forecast(self.__api, lat, lng, units = "us", callback=self.request_callback)
def draw(self, surf):
"Takes a surface object and blits its data onto it"
print("Draw call of Weather Module")
def update(self):
"Update this module's internal state (do things like time updates, get weather, etc."
# print("Update call of Weather Module")
def request_callback(self, forecast):
self.__forecast = forecast
print(self.__forecast.daily().summary)
def new_module(_id = -1, _keyfile = 'modules/weather_module/api.key'):
return weather_module(_id, _keyfile)
|
<commit_before>import juliet_module
from pygame import Rect
from time import time
from os import getcwd
class weather_module(juliet_module.module):
mod_name = "weather_module"
__last_update = time()
__api = None
def __init__(self, _id, _keyfile):
print("Initializing Weather Module")
self.mod_id = _id
with open(_keyfile, 'r') as f:
self.__api = f.read()
def draw(self, surf):
"Takes a surface object and blits its data onto it"
print("Draw call of Weather Module")
def update(self):
"Update this module's internal state (do things like time updates, get weather, etc."
# print("Update call of Weather Module")
def new_module(_id = -1, _keyfile = 'modules/weather_module/api.key'):
return weather_module(_id, _keyfile)
<commit_msg>Add test forecast.io API call<commit_after>import juliet_module
from pygame import Rect
from time import time
import forecastio
class weather_module(juliet_module.module):
mod_name = "weather_module"
__last_update = time()
__api = None
__forecast = None
def __init__(self, _id, _keyfile):
print("Initializing Weather Module")
self.mod_id = _id
with open(_keyfile, 'r') as f:
self.__api = f.read()[:-1]
lat = 40.7127
lng = 74.0059
forecastio.load_forecast(self.__api, lat, lng, units = "us", callback=self.request_callback)
def draw(self, surf):
"Takes a surface object and blits its data onto it"
print("Draw call of Weather Module")
def update(self):
"Update this module's internal state (do things like time updates, get weather, etc."
# print("Update call of Weather Module")
def request_callback(self, forecast):
self.__forecast = forecast
print(self.__forecast.daily().summary)
def new_module(_id = -1, _keyfile = 'modules/weather_module/api.key'):
return weather_module(_id, _keyfile)
|
4c18d98b456d8a9f231a7009079f9b00f732c92e
|
comics/crawler/crawlers/ctrlaltdelsillies.py
|
comics/crawler/crawlers/ctrlaltdelsillies.py
|
from comics.crawler.base import BaseComicCrawler
from comics.crawler.meta import BaseComicMeta
class ComicMeta(BaseComicMeta):
name = 'Ctrl+Alt+Del Sillies'
language = 'en'
url = 'http://www.ctrlaltdel-online.com/'
start_date = '2008-06-27'
history_capable_date = '2008-06-27'
schedule = 'Mo,Tu,We,Th,Fr,Sa,Su'
time_zone = -5
rights = 'Tim Buckley'
class ComicCrawler(BaseComicCrawler):
def _get_url(self):
self.url = 'http://www.cad-comic.com/comics/Lite%(date)s.jpg' % {
'date': self.pub_date.strftime('%Y%m%d'),
}
|
from comics.crawler.base import BaseComicCrawler
from comics.crawler.meta import BaseComicMeta
class ComicMeta(BaseComicMeta):
name = 'Ctrl+Alt+Del Sillies'
language = 'en'
url = 'http://www.ctrlaltdel-online.com/'
start_date = '2008-06-27'
history_capable_date = '2008-06-27'
schedule = 'Mo,Tu,We,Th,Fr,Sa,Su'
time_zone = -5
rights = 'Tim Buckley'
class ComicCrawler(BaseComicCrawler):
def _get_url(self):
self.url = 'http://www.ctrlaltdel-online.com/comics/Lite%(date)s.gif' % {
'date': self.pub_date.strftime('%Y%m%d'),
}
|
Update Ctrl+Alt+Del Sillies crawler with new URL
|
Update Ctrl+Alt+Del Sillies crawler with new URL
|
Python
|
agpl-3.0
|
klette/comics,datagutten/comics,klette/comics,datagutten/comics,jodal/comics,jodal/comics,jodal/comics,datagutten/comics,jodal/comics,klette/comics,datagutten/comics
|
from comics.crawler.base import BaseComicCrawler
from comics.crawler.meta import BaseComicMeta
class ComicMeta(BaseComicMeta):
name = 'Ctrl+Alt+Del Sillies'
language = 'en'
url = 'http://www.ctrlaltdel-online.com/'
start_date = '2008-06-27'
history_capable_date = '2008-06-27'
schedule = 'Mo,Tu,We,Th,Fr,Sa,Su'
time_zone = -5
rights = 'Tim Buckley'
class ComicCrawler(BaseComicCrawler):
def _get_url(self):
self.url = 'http://www.cad-comic.com/comics/Lite%(date)s.jpg' % {
'date': self.pub_date.strftime('%Y%m%d'),
}
Update Ctrl+Alt+Del Sillies crawler with new URL
|
from comics.crawler.base import BaseComicCrawler
from comics.crawler.meta import BaseComicMeta
class ComicMeta(BaseComicMeta):
name = 'Ctrl+Alt+Del Sillies'
language = 'en'
url = 'http://www.ctrlaltdel-online.com/'
start_date = '2008-06-27'
history_capable_date = '2008-06-27'
schedule = 'Mo,Tu,We,Th,Fr,Sa,Su'
time_zone = -5
rights = 'Tim Buckley'
class ComicCrawler(BaseComicCrawler):
def _get_url(self):
self.url = 'http://www.ctrlaltdel-online.com/comics/Lite%(date)s.gif' % {
'date': self.pub_date.strftime('%Y%m%d'),
}
|
<commit_before>from comics.crawler.base import BaseComicCrawler
from comics.crawler.meta import BaseComicMeta
class ComicMeta(BaseComicMeta):
name = 'Ctrl+Alt+Del Sillies'
language = 'en'
url = 'http://www.ctrlaltdel-online.com/'
start_date = '2008-06-27'
history_capable_date = '2008-06-27'
schedule = 'Mo,Tu,We,Th,Fr,Sa,Su'
time_zone = -5
rights = 'Tim Buckley'
class ComicCrawler(BaseComicCrawler):
def _get_url(self):
self.url = 'http://www.cad-comic.com/comics/Lite%(date)s.jpg' % {
'date': self.pub_date.strftime('%Y%m%d'),
}
<commit_msg>Update Ctrl+Alt+Del Sillies crawler with new URL<commit_after>
|
from comics.crawler.base import BaseComicCrawler
from comics.crawler.meta import BaseComicMeta
class ComicMeta(BaseComicMeta):
name = 'Ctrl+Alt+Del Sillies'
language = 'en'
url = 'http://www.ctrlaltdel-online.com/'
start_date = '2008-06-27'
history_capable_date = '2008-06-27'
schedule = 'Mo,Tu,We,Th,Fr,Sa,Su'
time_zone = -5
rights = 'Tim Buckley'
class ComicCrawler(BaseComicCrawler):
def _get_url(self):
self.url = 'http://www.ctrlaltdel-online.com/comics/Lite%(date)s.gif' % {
'date': self.pub_date.strftime('%Y%m%d'),
}
|
from comics.crawler.base import BaseComicCrawler
from comics.crawler.meta import BaseComicMeta
class ComicMeta(BaseComicMeta):
name = 'Ctrl+Alt+Del Sillies'
language = 'en'
url = 'http://www.ctrlaltdel-online.com/'
start_date = '2008-06-27'
history_capable_date = '2008-06-27'
schedule = 'Mo,Tu,We,Th,Fr,Sa,Su'
time_zone = -5
rights = 'Tim Buckley'
class ComicCrawler(BaseComicCrawler):
def _get_url(self):
self.url = 'http://www.cad-comic.com/comics/Lite%(date)s.jpg' % {
'date': self.pub_date.strftime('%Y%m%d'),
}
Update Ctrl+Alt+Del Sillies crawler with new URLfrom comics.crawler.base import BaseComicCrawler
from comics.crawler.meta import BaseComicMeta
class ComicMeta(BaseComicMeta):
name = 'Ctrl+Alt+Del Sillies'
language = 'en'
url = 'http://www.ctrlaltdel-online.com/'
start_date = '2008-06-27'
history_capable_date = '2008-06-27'
schedule = 'Mo,Tu,We,Th,Fr,Sa,Su'
time_zone = -5
rights = 'Tim Buckley'
class ComicCrawler(BaseComicCrawler):
def _get_url(self):
self.url = 'http://www.ctrlaltdel-online.com/comics/Lite%(date)s.gif' % {
'date': self.pub_date.strftime('%Y%m%d'),
}
|
<commit_before>from comics.crawler.base import BaseComicCrawler
from comics.crawler.meta import BaseComicMeta
class ComicMeta(BaseComicMeta):
name = 'Ctrl+Alt+Del Sillies'
language = 'en'
url = 'http://www.ctrlaltdel-online.com/'
start_date = '2008-06-27'
history_capable_date = '2008-06-27'
schedule = 'Mo,Tu,We,Th,Fr,Sa,Su'
time_zone = -5
rights = 'Tim Buckley'
class ComicCrawler(BaseComicCrawler):
def _get_url(self):
self.url = 'http://www.cad-comic.com/comics/Lite%(date)s.jpg' % {
'date': self.pub_date.strftime('%Y%m%d'),
}
<commit_msg>Update Ctrl+Alt+Del Sillies crawler with new URL<commit_after>from comics.crawler.base import BaseComicCrawler
from comics.crawler.meta import BaseComicMeta
class ComicMeta(BaseComicMeta):
name = 'Ctrl+Alt+Del Sillies'
language = 'en'
url = 'http://www.ctrlaltdel-online.com/'
start_date = '2008-06-27'
history_capable_date = '2008-06-27'
schedule = 'Mo,Tu,We,Th,Fr,Sa,Su'
time_zone = -5
rights = 'Tim Buckley'
class ComicCrawler(BaseComicCrawler):
def _get_url(self):
self.url = 'http://www.ctrlaltdel-online.com/comics/Lite%(date)s.gif' % {
'date': self.pub_date.strftime('%Y%m%d'),
}
|
8ce6a6144fee1c9ec6a5f1a083eabbb653d8514b
|
virtool/postgres.py
|
virtool/postgres.py
|
import logging
import sys
from sqlalchemy import text
from sqlalchemy.ext.asyncio import AsyncConnection, create_async_engine
logger = logging.getLogger(__name__)
async def connect(postgres_connection_string: str) -> AsyncConnection:
"""
Create a connection of Postgres.
:param postgres_connection_string: the postgres connection string
:return: an AsyncConnection object
"""
if not postgres_connection_string.startswith("postgresql+asyncpg://"):
logger.fatal("Invalid PostgreSQL connection string")
sys.exit(1)
try:
postgres = create_async_engine(postgres_connection_string)
async with postgres.connect() as connection:
await check_version(connection)
return connection
except ConnectionRefusedError:
logger.fatal("Could not connect to PostgreSQL: Connection refused")
sys.exit(1)
async def check_version(connection: AsyncConnection):
"""
Check and log the Postgres sever version.
:param connection:an AsyncConnection object
"""
info = await connection.execute(text('SHOW server_version'))
version = info.first()[0].split()[0]
logger.info(f"Found PostgreSQL {version}")
|
import logging
import sys
from sqlalchemy import text
from sqlalchemy.ext.asyncio import AsyncConnection, create_async_engine
import virtool.models
logger = logging.getLogger(__name__)
async def connect(postgres_connection_string: str) -> AsyncConnection:
"""
Create a connection of Postgres.
:param postgres_connection_string: the postgres connection string
:return: an AsyncConnection object
"""
if not postgres_connection_string.startswith("postgresql+asyncpg://"):
logger.fatal("Invalid PostgreSQL connection string")
sys.exit(1)
try:
postgres = create_async_engine(postgres_connection_string)
await virtool.models.create_tables(postgres)
async with postgres.connect() as connection:
await check_version(connection)
return connection
except ConnectionRefusedError:
logger.fatal("Could not connect to PostgreSQL: Connection refused")
sys.exit(1)
async def check_version(connection: AsyncConnection):
"""
Check and log the Postgres sever version.
:param connection:an AsyncConnection object
"""
info = await connection.execute(text('SHOW server_version'))
version = info.first()[0].split()[0]
logger.info(f"Found PostgreSQL {version}")
|
Create tables on application start
|
Create tables on application start
|
Python
|
mit
|
virtool/virtool,virtool/virtool,igboyes/virtool,igboyes/virtool
|
import logging
import sys
from sqlalchemy import text
from sqlalchemy.ext.asyncio import AsyncConnection, create_async_engine
logger = logging.getLogger(__name__)
async def connect(postgres_connection_string: str) -> AsyncConnection:
"""
Create a connection of Postgres.
:param postgres_connection_string: the postgres connection string
:return: an AsyncConnection object
"""
if not postgres_connection_string.startswith("postgresql+asyncpg://"):
logger.fatal("Invalid PostgreSQL connection string")
sys.exit(1)
try:
postgres = create_async_engine(postgres_connection_string)
async with postgres.connect() as connection:
await check_version(connection)
return connection
except ConnectionRefusedError:
logger.fatal("Could not connect to PostgreSQL: Connection refused")
sys.exit(1)
async def check_version(connection: AsyncConnection):
"""
Check and log the Postgres sever version.
:param connection:an AsyncConnection object
"""
info = await connection.execute(text('SHOW server_version'))
version = info.first()[0].split()[0]
logger.info(f"Found PostgreSQL {version}")
Create tables on application start
|
import logging
import sys
from sqlalchemy import text
from sqlalchemy.ext.asyncio import AsyncConnection, create_async_engine
import virtool.models
logger = logging.getLogger(__name__)
async def connect(postgres_connection_string: str) -> AsyncConnection:
"""
Create a connection of Postgres.
:param postgres_connection_string: the postgres connection string
:return: an AsyncConnection object
"""
if not postgres_connection_string.startswith("postgresql+asyncpg://"):
logger.fatal("Invalid PostgreSQL connection string")
sys.exit(1)
try:
postgres = create_async_engine(postgres_connection_string)
await virtool.models.create_tables(postgres)
async with postgres.connect() as connection:
await check_version(connection)
return connection
except ConnectionRefusedError:
logger.fatal("Could not connect to PostgreSQL: Connection refused")
sys.exit(1)
async def check_version(connection: AsyncConnection):
"""
Check and log the Postgres sever version.
:param connection:an AsyncConnection object
"""
info = await connection.execute(text('SHOW server_version'))
version = info.first()[0].split()[0]
logger.info(f"Found PostgreSQL {version}")
|
<commit_before>import logging
import sys
from sqlalchemy import text
from sqlalchemy.ext.asyncio import AsyncConnection, create_async_engine
logger = logging.getLogger(__name__)
async def connect(postgres_connection_string: str) -> AsyncConnection:
"""
Create a connection of Postgres.
:param postgres_connection_string: the postgres connection string
:return: an AsyncConnection object
"""
if not postgres_connection_string.startswith("postgresql+asyncpg://"):
logger.fatal("Invalid PostgreSQL connection string")
sys.exit(1)
try:
postgres = create_async_engine(postgres_connection_string)
async with postgres.connect() as connection:
await check_version(connection)
return connection
except ConnectionRefusedError:
logger.fatal("Could not connect to PostgreSQL: Connection refused")
sys.exit(1)
async def check_version(connection: AsyncConnection):
"""
Check and log the Postgres sever version.
:param connection:an AsyncConnection object
"""
info = await connection.execute(text('SHOW server_version'))
version = info.first()[0].split()[0]
logger.info(f"Found PostgreSQL {version}")
<commit_msg>Create tables on application start<commit_after>
|
import logging
import sys
from sqlalchemy import text
from sqlalchemy.ext.asyncio import AsyncConnection, create_async_engine
import virtool.models
logger = logging.getLogger(__name__)
async def connect(postgres_connection_string: str) -> AsyncConnection:
"""
Create a connection of Postgres.
:param postgres_connection_string: the postgres connection string
:return: an AsyncConnection object
"""
if not postgres_connection_string.startswith("postgresql+asyncpg://"):
logger.fatal("Invalid PostgreSQL connection string")
sys.exit(1)
try:
postgres = create_async_engine(postgres_connection_string)
await virtool.models.create_tables(postgres)
async with postgres.connect() as connection:
await check_version(connection)
return connection
except ConnectionRefusedError:
logger.fatal("Could not connect to PostgreSQL: Connection refused")
sys.exit(1)
async def check_version(connection: AsyncConnection):
"""
Check and log the Postgres sever version.
:param connection:an AsyncConnection object
"""
info = await connection.execute(text('SHOW server_version'))
version = info.first()[0].split()[0]
logger.info(f"Found PostgreSQL {version}")
|
import logging
import sys
from sqlalchemy import text
from sqlalchemy.ext.asyncio import AsyncConnection, create_async_engine
logger = logging.getLogger(__name__)
async def connect(postgres_connection_string: str) -> AsyncConnection:
"""
Create a connection of Postgres.
:param postgres_connection_string: the postgres connection string
:return: an AsyncConnection object
"""
if not postgres_connection_string.startswith("postgresql+asyncpg://"):
logger.fatal("Invalid PostgreSQL connection string")
sys.exit(1)
try:
postgres = create_async_engine(postgres_connection_string)
async with postgres.connect() as connection:
await check_version(connection)
return connection
except ConnectionRefusedError:
logger.fatal("Could not connect to PostgreSQL: Connection refused")
sys.exit(1)
async def check_version(connection: AsyncConnection):
"""
Check and log the Postgres sever version.
:param connection:an AsyncConnection object
"""
info = await connection.execute(text('SHOW server_version'))
version = info.first()[0].split()[0]
logger.info(f"Found PostgreSQL {version}")
Create tables on application startimport logging
import sys
from sqlalchemy import text
from sqlalchemy.ext.asyncio import AsyncConnection, create_async_engine
import virtool.models
logger = logging.getLogger(__name__)
async def connect(postgres_connection_string: str) -> AsyncConnection:
"""
Create a connection of Postgres.
:param postgres_connection_string: the postgres connection string
:return: an AsyncConnection object
"""
if not postgres_connection_string.startswith("postgresql+asyncpg://"):
logger.fatal("Invalid PostgreSQL connection string")
sys.exit(1)
try:
postgres = create_async_engine(postgres_connection_string)
await virtool.models.create_tables(postgres)
async with postgres.connect() as connection:
await check_version(connection)
return connection
except ConnectionRefusedError:
logger.fatal("Could not connect to PostgreSQL: Connection refused")
sys.exit(1)
async def check_version(connection: AsyncConnection):
"""
Check and log the Postgres sever version.
:param connection:an AsyncConnection object
"""
info = await connection.execute(text('SHOW server_version'))
version = info.first()[0].split()[0]
logger.info(f"Found PostgreSQL {version}")
|
<commit_before>import logging
import sys
from sqlalchemy import text
from sqlalchemy.ext.asyncio import AsyncConnection, create_async_engine
logger = logging.getLogger(__name__)
async def connect(postgres_connection_string: str) -> AsyncConnection:
"""
Create a connection of Postgres.
:param postgres_connection_string: the postgres connection string
:return: an AsyncConnection object
"""
if not postgres_connection_string.startswith("postgresql+asyncpg://"):
logger.fatal("Invalid PostgreSQL connection string")
sys.exit(1)
try:
postgres = create_async_engine(postgres_connection_string)
async with postgres.connect() as connection:
await check_version(connection)
return connection
except ConnectionRefusedError:
logger.fatal("Could not connect to PostgreSQL: Connection refused")
sys.exit(1)
async def check_version(connection: AsyncConnection):
"""
Check and log the Postgres sever version.
:param connection:an AsyncConnection object
"""
info = await connection.execute(text('SHOW server_version'))
version = info.first()[0].split()[0]
logger.info(f"Found PostgreSQL {version}")
<commit_msg>Create tables on application start<commit_after>import logging
import sys
from sqlalchemy import text
from sqlalchemy.ext.asyncio import AsyncConnection, create_async_engine
import virtool.models
logger = logging.getLogger(__name__)
async def connect(postgres_connection_string: str) -> AsyncConnection:
"""
Create a connection of Postgres.
:param postgres_connection_string: the postgres connection string
:return: an AsyncConnection object
"""
if not postgres_connection_string.startswith("postgresql+asyncpg://"):
logger.fatal("Invalid PostgreSQL connection string")
sys.exit(1)
try:
postgres = create_async_engine(postgres_connection_string)
await virtool.models.create_tables(postgres)
async with postgres.connect() as connection:
await check_version(connection)
return connection
except ConnectionRefusedError:
logger.fatal("Could not connect to PostgreSQL: Connection refused")
sys.exit(1)
async def check_version(connection: AsyncConnection):
"""
Check and log the Postgres sever version.
:param connection:an AsyncConnection object
"""
info = await connection.execute(text('SHOW server_version'))
version = info.first()[0].split()[0]
logger.info(f"Found PostgreSQL {version}")
|
e381d5c780e0d688766a415323d5586ead60532c
|
mangacork/__init__.py
|
mangacork/__init__.py
|
import os
import logging
from flask import Flask
from flask.ext.bcrypt import Bcrypt
import flask.ext.login as flask_login
from flask.ext.sqlalchemy import SQLAlchemy
log = logging.getLogger(__name__)
app = Flask(__name__)
app.config.from_object(os.getenv('APP_SETTINGS'))
bcrypt = Bcrypt(app)
db = SQLAlchemy(app)
# Loads user from an ID and directs actions for redirects etc
login_manager = flask_login.LoginManager()
login_manager.init_app(app)
# Determine which view to direct user if logged out
login_manager.login_view = 'login'
import mangacork.views
from .models import User
# Define how to get user object with app object
@login_manager.user_loader
def load_user(userid):
return User.query.filter(User.id == userid).first()
|
import os
import logging
from flask import Flask
from flask.ext.bcrypt import Bcrypt
import flask.ext.login as flask_login
from flask.ext.sqlalchemy import SQLAlchemy
log = logging.getLogger(__name__)
app = Flask(__name__)
# TODO: It doesn't look like getenv is returning anything on prod
# Find an alternative or fix path to retrieve environment var from
# virtualenvwrapper
app.config.from_object(os.getenv('APP_SETTINGS'))
bcrypt = Bcrypt(app)
db = SQLAlchemy(app)
# Loads user from an ID and directs actions for redirects etc
login_manager = flask_login.LoginManager()
login_manager.init_app(app)
# Determine which view to direct user if logged out
login_manager.login_view = 'login'
import mangacork.views
from .models import User
# Define how to get user object with app object
@login_manager.user_loader
def load_user(userid):
return User.query.filter(User.id == userid).first()
|
Add important todo for fixing prod
|
Add important todo for fixing prod
|
Python
|
mit
|
ma3lstrom/manga-cork,ma3lstrom/manga-cork,ma3lstrom/manga-cork
|
import os
import logging
from flask import Flask
from flask.ext.bcrypt import Bcrypt
import flask.ext.login as flask_login
from flask.ext.sqlalchemy import SQLAlchemy
log = logging.getLogger(__name__)
app = Flask(__name__)
app.config.from_object(os.getenv('APP_SETTINGS'))
bcrypt = Bcrypt(app)
db = SQLAlchemy(app)
# Loads user from an ID and directs actions for redirects etc
login_manager = flask_login.LoginManager()
login_manager.init_app(app)
# Determine which view to direct user if logged out
login_manager.login_view = 'login'
import mangacork.views
from .models import User
# Define how to get user object with app object
@login_manager.user_loader
def load_user(userid):
return User.query.filter(User.id == userid).first()
Add important todo for fixing prod
|
import os
import logging
from flask import Flask
from flask.ext.bcrypt import Bcrypt
import flask.ext.login as flask_login
from flask.ext.sqlalchemy import SQLAlchemy
log = logging.getLogger(__name__)
app = Flask(__name__)
# TODO: It doesn't look like getenv is returning anything on prod
# Find an alternative or fix path to retrieve environment var from
# virtualenvwrapper
app.config.from_object(os.getenv('APP_SETTINGS'))
bcrypt = Bcrypt(app)
db = SQLAlchemy(app)
# Loads user from an ID and directs actions for redirects etc
login_manager = flask_login.LoginManager()
login_manager.init_app(app)
# Determine which view to direct user if logged out
login_manager.login_view = 'login'
import mangacork.views
from .models import User
# Define how to get user object with app object
@login_manager.user_loader
def load_user(userid):
return User.query.filter(User.id == userid).first()
|
<commit_before>import os
import logging
from flask import Flask
from flask.ext.bcrypt import Bcrypt
import flask.ext.login as flask_login
from flask.ext.sqlalchemy import SQLAlchemy
log = logging.getLogger(__name__)
app = Flask(__name__)
app.config.from_object(os.getenv('APP_SETTINGS'))
bcrypt = Bcrypt(app)
db = SQLAlchemy(app)
# Loads user from an ID and directs actions for redirects etc
login_manager = flask_login.LoginManager()
login_manager.init_app(app)
# Determine which view to direct user if logged out
login_manager.login_view = 'login'
import mangacork.views
from .models import User
# Define how to get user object with app object
@login_manager.user_loader
def load_user(userid):
return User.query.filter(User.id == userid).first()
<commit_msg>Add important todo for fixing prod<commit_after>
|
import os
import logging
from flask import Flask
from flask.ext.bcrypt import Bcrypt
import flask.ext.login as flask_login
from flask.ext.sqlalchemy import SQLAlchemy
log = logging.getLogger(__name__)
app = Flask(__name__)
# TODO: It doesn't look like getenv is returning anything on prod
# Find an alternative or fix path to retrieve environment var from
# virtualenvwrapper
app.config.from_object(os.getenv('APP_SETTINGS'))
bcrypt = Bcrypt(app)
db = SQLAlchemy(app)
# Loads user from an ID and directs actions for redirects etc
login_manager = flask_login.LoginManager()
login_manager.init_app(app)
# Determine which view to direct user if logged out
login_manager.login_view = 'login'
import mangacork.views
from .models import User
# Define how to get user object with app object
@login_manager.user_loader
def load_user(userid):
return User.query.filter(User.id == userid).first()
|
import os
import logging
from flask import Flask
from flask.ext.bcrypt import Bcrypt
import flask.ext.login as flask_login
from flask.ext.sqlalchemy import SQLAlchemy
log = logging.getLogger(__name__)
app = Flask(__name__)
app.config.from_object(os.getenv('APP_SETTINGS'))
bcrypt = Bcrypt(app)
db = SQLAlchemy(app)
# Loads user from an ID and directs actions for redirects etc
login_manager = flask_login.LoginManager()
login_manager.init_app(app)
# Determine which view to direct user if logged out
login_manager.login_view = 'login'
import mangacork.views
from .models import User
# Define how to get user object with app object
@login_manager.user_loader
def load_user(userid):
return User.query.filter(User.id == userid).first()
Add important todo for fixing prodimport os
import logging
from flask import Flask
from flask.ext.bcrypt import Bcrypt
import flask.ext.login as flask_login
from flask.ext.sqlalchemy import SQLAlchemy
log = logging.getLogger(__name__)
app = Flask(__name__)
# TODO: It doesn't look like getenv is returning anything on prod
# Find an alternative or fix path to retrieve environment var from
# virtualenvwrapper
app.config.from_object(os.getenv('APP_SETTINGS'))
bcrypt = Bcrypt(app)
db = SQLAlchemy(app)
# Loads user from an ID and directs actions for redirects etc
login_manager = flask_login.LoginManager()
login_manager.init_app(app)
# Determine which view to direct user if logged out
login_manager.login_view = 'login'
import mangacork.views
from .models import User
# Define how to get user object with app object
@login_manager.user_loader
def load_user(userid):
return User.query.filter(User.id == userid).first()
|
<commit_before>import os
import logging
from flask import Flask
from flask.ext.bcrypt import Bcrypt
import flask.ext.login as flask_login
from flask.ext.sqlalchemy import SQLAlchemy
log = logging.getLogger(__name__)
app = Flask(__name__)
app.config.from_object(os.getenv('APP_SETTINGS'))
bcrypt = Bcrypt(app)
db = SQLAlchemy(app)
# Loads user from an ID and directs actions for redirects etc
login_manager = flask_login.LoginManager()
login_manager.init_app(app)
# Determine which view to direct user if logged out
login_manager.login_view = 'login'
import mangacork.views
from .models import User
# Define how to get user object with app object
@login_manager.user_loader
def load_user(userid):
return User.query.filter(User.id == userid).first()
<commit_msg>Add important todo for fixing prod<commit_after>import os
import logging
from flask import Flask
from flask.ext.bcrypt import Bcrypt
import flask.ext.login as flask_login
from flask.ext.sqlalchemy import SQLAlchemy
log = logging.getLogger(__name__)
app = Flask(__name__)
# TODO: It doesn't look like getenv is returning anything on prod
# Find an alternative or fix path to retrieve environment var from
# virtualenvwrapper
app.config.from_object(os.getenv('APP_SETTINGS'))
bcrypt = Bcrypt(app)
db = SQLAlchemy(app)
# Loads user from an ID and directs actions for redirects etc
login_manager = flask_login.LoginManager()
login_manager.init_app(app)
# Determine which view to direct user if logged out
login_manager.login_view = 'login'
import mangacork.views
from .models import User
# Define how to get user object with app object
@login_manager.user_loader
def load_user(userid):
return User.query.filter(User.id == userid).first()
|
5bde0ffa9374a1b4363faedc389ed3b49009aabd
|
candidates/tests/test_api_help_view.py
|
candidates/tests/test_api_help_view.py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django_webtest import WebTest
from . import factories
class TestApiHelpView(WebTest):
def setUp(self):
factories.ElectionFactory.create(
slug='2015',
name='2015 General Election',
)
def test_api_help(self):
response = self.app.get('/help/api')
self.assertEqual(response.status_code, 200)
self.assertIn(
'Download of the 2015 General Election candidates',
response)
self.assertIn(
"The browsable base URL of the site's read-only API is: <a href=\"http://localhost:80/api/v0.9/\">http://localhost:80/api/v0.9/</a>",
response
)
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django_webtest import WebTest
from . import factories
class TestApiHelpView(WebTest):
def setUp(self):
factories.ElectionFactory.create(
slug='2015',
name='2015 General Election',
)
def test_api_help(self):
response = self.app.get('/help/api')
self.assertEqual(response.status_code, 200)
self.assertIn(
'Download the 2015 General Election candidates',
response)
self.assertIn(
"The browsable base URL of the site's read-only API is: <a href=\"http://localhost:80/api/v0.9/\">http://localhost:80/api/v0.9/</a>",
response
)
|
Fix test for updated text
|
Fix test for updated text
|
Python
|
agpl-3.0
|
DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django_webtest import WebTest
from . import factories
class TestApiHelpView(WebTest):
def setUp(self):
factories.ElectionFactory.create(
slug='2015',
name='2015 General Election',
)
def test_api_help(self):
response = self.app.get('/help/api')
self.assertEqual(response.status_code, 200)
self.assertIn(
'Download of the 2015 General Election candidates',
response)
self.assertIn(
"The browsable base URL of the site's read-only API is: <a href=\"http://localhost:80/api/v0.9/\">http://localhost:80/api/v0.9/</a>",
response
)
Fix test for updated text
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django_webtest import WebTest
from . import factories
class TestApiHelpView(WebTest):
def setUp(self):
factories.ElectionFactory.create(
slug='2015',
name='2015 General Election',
)
def test_api_help(self):
response = self.app.get('/help/api')
self.assertEqual(response.status_code, 200)
self.assertIn(
'Download the 2015 General Election candidates',
response)
self.assertIn(
"The browsable base URL of the site's read-only API is: <a href=\"http://localhost:80/api/v0.9/\">http://localhost:80/api/v0.9/</a>",
response
)
|
<commit_before># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django_webtest import WebTest
from . import factories
class TestApiHelpView(WebTest):
def setUp(self):
factories.ElectionFactory.create(
slug='2015',
name='2015 General Election',
)
def test_api_help(self):
response = self.app.get('/help/api')
self.assertEqual(response.status_code, 200)
self.assertIn(
'Download of the 2015 General Election candidates',
response)
self.assertIn(
"The browsable base URL of the site's read-only API is: <a href=\"http://localhost:80/api/v0.9/\">http://localhost:80/api/v0.9/</a>",
response
)
<commit_msg>Fix test for updated text<commit_after>
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django_webtest import WebTest
from . import factories
class TestApiHelpView(WebTest):
def setUp(self):
factories.ElectionFactory.create(
slug='2015',
name='2015 General Election',
)
def test_api_help(self):
response = self.app.get('/help/api')
self.assertEqual(response.status_code, 200)
self.assertIn(
'Download the 2015 General Election candidates',
response)
self.assertIn(
"The browsable base URL of the site's read-only API is: <a href=\"http://localhost:80/api/v0.9/\">http://localhost:80/api/v0.9/</a>",
response
)
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django_webtest import WebTest
from . import factories
class TestApiHelpView(WebTest):
def setUp(self):
factories.ElectionFactory.create(
slug='2015',
name='2015 General Election',
)
def test_api_help(self):
response = self.app.get('/help/api')
self.assertEqual(response.status_code, 200)
self.assertIn(
'Download of the 2015 General Election candidates',
response)
self.assertIn(
"The browsable base URL of the site's read-only API is: <a href=\"http://localhost:80/api/v0.9/\">http://localhost:80/api/v0.9/</a>",
response
)
Fix test for updated text# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django_webtest import WebTest
from . import factories
class TestApiHelpView(WebTest):
def setUp(self):
factories.ElectionFactory.create(
slug='2015',
name='2015 General Election',
)
def test_api_help(self):
response = self.app.get('/help/api')
self.assertEqual(response.status_code, 200)
self.assertIn(
'Download the 2015 General Election candidates',
response)
self.assertIn(
"The browsable base URL of the site's read-only API is: <a href=\"http://localhost:80/api/v0.9/\">http://localhost:80/api/v0.9/</a>",
response
)
|
<commit_before># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django_webtest import WebTest
from . import factories
class TestApiHelpView(WebTest):
def setUp(self):
factories.ElectionFactory.create(
slug='2015',
name='2015 General Election',
)
def test_api_help(self):
response = self.app.get('/help/api')
self.assertEqual(response.status_code, 200)
self.assertIn(
'Download of the 2015 General Election candidates',
response)
self.assertIn(
"The browsable base URL of the site's read-only API is: <a href=\"http://localhost:80/api/v0.9/\">http://localhost:80/api/v0.9/</a>",
response
)
<commit_msg>Fix test for updated text<commit_after># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django_webtest import WebTest
from . import factories
class TestApiHelpView(WebTest):
def setUp(self):
factories.ElectionFactory.create(
slug='2015',
name='2015 General Election',
)
def test_api_help(self):
response = self.app.get('/help/api')
self.assertEqual(response.status_code, 200)
self.assertIn(
'Download the 2015 General Election candidates',
response)
self.assertIn(
"The browsable base URL of the site's read-only API is: <a href=\"http://localhost:80/api/v0.9/\">http://localhost:80/api/v0.9/</a>",
response
)
|
4bf959b75c195c86418ff65c9147c3345712a188
|
funsize/utils/fetch.py
|
funsize/utils/fetch.py
|
"""
funsize.fetch
~~~~~~~~~~~~~~~~~~
This module contains fetch functions
"""
import logging
import requests
from .csum import verify
from .oddity import DownloadError
def downloadmar(url, checksum, cipher='sha512', output_file=None):
""" Downloads the file specified by url, verifies the checksum.
The file is written to the location specified by output file,
if not specified, the downloaded file is returned.
List of Ciphers supported is the same as those supported by
`csum.py`
"""
logging.debug('Starting download for %s with checksum: %s', url, checksum)
response = requests.get(url)
if response.status_code != requests.codes.ok:
logging.debug('HTTP Request to %s failed with error code %d',
url, response.status_code)
raise DownloadError('HTTP Request response error')
mar = response.content
if not verify(mar, checksum, cipher):
logging.warning('Verification of %s with checksum %s failed',
url, checksum)
raise DownloadError('Checksums do not match')
else:
logging.info('Verified download of %s', url)
if output_file:
try:
logging.info('Writing download %s to file %s', url, output_file)
# TODO ROUGHEDGE write in blocks of 1MB anc check afterwards?
with open(output_file, 'wb') as fobj:
fobj.write(mar)
except:
logging.error('Error while downloading %s to file %s on disk',
url, output_file)
raise DownloadError('Failed to write file to disk')
else:
return None
else:
return mar
|
"""
funsize.fetch
~~~~~~~~~~~~~~~~~~
This module contains fetch functions
"""
import logging
import requests
from .csum import verify
from .oddity import DownloadError
def downloadmar(url, checksum, cipher='sha512', output_file=None):
""" Downloads the file specified by url, verifies the checksum.
The file is written to the location specified by output file,
if not specified, the downloaded file is returned.
List of Ciphers supported is the same as those supported by
`csum.py`
"""
logging.debug('Starting download for %s with checksum: %s', url, checksum)
response = requests.get(url)
if response.status_code != requests.codes.ok:
logging.debug('HTTP Request to %s failed with error code %d',
url, response.status_code)
raise DownloadError('HTTP Request response error')
mar = response.content
if not verify(mar, checksum, cipher):
logging.warning('Verification of %s with checksum %s failed',
url, checksum)
raise DownloadError('Checksums do not match')
else:
logging.info('Verified download of %s', url)
if output_file:
try:
logging.info('Writing download %s to file %s', url, output_file)
with open(output_file, 'wb') as fobj:
fobj.write(mar)
except:
logging.error('Error while downloading %s to file %s on disk',
url, output_file)
raise DownloadError('Failed to write file to disk')
else:
return None
else:
return mar
|
Remove useless TODO from codebase.
|
Remove useless TODO from codebase.
|
Python
|
mpl-2.0
|
petemoore/build-funsize,petemoore/build-funsize
|
"""
funsize.fetch
~~~~~~~~~~~~~~~~~~
This module contains fetch functions
"""
import logging
import requests
from .csum import verify
from .oddity import DownloadError
def downloadmar(url, checksum, cipher='sha512', output_file=None):
""" Downloads the file specified by url, verifies the checksum.
The file is written to the location specified by output file,
if not specified, the downloaded file is returned.
List of Ciphers supported is the same as those supported by
`csum.py`
"""
logging.debug('Starting download for %s with checksum: %s', url, checksum)
response = requests.get(url)
if response.status_code != requests.codes.ok:
logging.debug('HTTP Request to %s failed with error code %d',
url, response.status_code)
raise DownloadError('HTTP Request response error')
mar = response.content
if not verify(mar, checksum, cipher):
logging.warning('Verification of %s with checksum %s failed',
url, checksum)
raise DownloadError('Checksums do not match')
else:
logging.info('Verified download of %s', url)
if output_file:
try:
logging.info('Writing download %s to file %s', url, output_file)
# TODO ROUGHEDGE write in blocks of 1MB anc check afterwards?
with open(output_file, 'wb') as fobj:
fobj.write(mar)
except:
logging.error('Error while downloading %s to file %s on disk',
url, output_file)
raise DownloadError('Failed to write file to disk')
else:
return None
else:
return mar
Remove useless TODO from codebase.
|
"""
funsize.fetch
~~~~~~~~~~~~~~~~~~
This module contains fetch functions
"""
import logging
import requests
from .csum import verify
from .oddity import DownloadError
def downloadmar(url, checksum, cipher='sha512', output_file=None):
""" Downloads the file specified by url, verifies the checksum.
The file is written to the location specified by output file,
if not specified, the downloaded file is returned.
List of Ciphers supported is the same as those supported by
`csum.py`
"""
logging.debug('Starting download for %s with checksum: %s', url, checksum)
response = requests.get(url)
if response.status_code != requests.codes.ok:
logging.debug('HTTP Request to %s failed with error code %d',
url, response.status_code)
raise DownloadError('HTTP Request response error')
mar = response.content
if not verify(mar, checksum, cipher):
logging.warning('Verification of %s with checksum %s failed',
url, checksum)
raise DownloadError('Checksums do not match')
else:
logging.info('Verified download of %s', url)
if output_file:
try:
logging.info('Writing download %s to file %s', url, output_file)
with open(output_file, 'wb') as fobj:
fobj.write(mar)
except:
logging.error('Error while downloading %s to file %s on disk',
url, output_file)
raise DownloadError('Failed to write file to disk')
else:
return None
else:
return mar
|
<commit_before>"""
funsize.fetch
~~~~~~~~~~~~~~~~~~
This module contains fetch functions
"""
import logging
import requests
from .csum import verify
from .oddity import DownloadError
def downloadmar(url, checksum, cipher='sha512', output_file=None):
""" Downloads the file specified by url, verifies the checksum.
The file is written to the location specified by output file,
if not specified, the downloaded file is returned.
List of Ciphers supported is the same as those supported by
`csum.py`
"""
logging.debug('Starting download for %s with checksum: %s', url, checksum)
response = requests.get(url)
if response.status_code != requests.codes.ok:
logging.debug('HTTP Request to %s failed with error code %d',
url, response.status_code)
raise DownloadError('HTTP Request response error')
mar = response.content
if not verify(mar, checksum, cipher):
logging.warning('Verification of %s with checksum %s failed',
url, checksum)
raise DownloadError('Checksums do not match')
else:
logging.info('Verified download of %s', url)
if output_file:
try:
logging.info('Writing download %s to file %s', url, output_file)
# TODO ROUGHEDGE write in blocks of 1MB anc check afterwards?
with open(output_file, 'wb') as fobj:
fobj.write(mar)
except:
logging.error('Error while downloading %s to file %s on disk',
url, output_file)
raise DownloadError('Failed to write file to disk')
else:
return None
else:
return mar
<commit_msg>Remove useless TODO from codebase.<commit_after>
|
"""
funsize.fetch
~~~~~~~~~~~~~~~~~~
This module contains fetch functions
"""
import logging
import requests
from .csum import verify
from .oddity import DownloadError
def downloadmar(url, checksum, cipher='sha512', output_file=None):
""" Downloads the file specified by url, verifies the checksum.
The file is written to the location specified by output file,
if not specified, the downloaded file is returned.
List of Ciphers supported is the same as those supported by
`csum.py`
"""
logging.debug('Starting download for %s with checksum: %s', url, checksum)
response = requests.get(url)
if response.status_code != requests.codes.ok:
logging.debug('HTTP Request to %s failed with error code %d',
url, response.status_code)
raise DownloadError('HTTP Request response error')
mar = response.content
if not verify(mar, checksum, cipher):
logging.warning('Verification of %s with checksum %s failed',
url, checksum)
raise DownloadError('Checksums do not match')
else:
logging.info('Verified download of %s', url)
if output_file:
try:
logging.info('Writing download %s to file %s', url, output_file)
with open(output_file, 'wb') as fobj:
fobj.write(mar)
except:
logging.error('Error while downloading %s to file %s on disk',
url, output_file)
raise DownloadError('Failed to write file to disk')
else:
return None
else:
return mar
|
"""
funsize.fetch
~~~~~~~~~~~~~~~~~~
This module contains fetch functions
"""
import logging
import requests
from .csum import verify
from .oddity import DownloadError
def downloadmar(url, checksum, cipher='sha512', output_file=None):
""" Downloads the file specified by url, verifies the checksum.
The file is written to the location specified by output file,
if not specified, the downloaded file is returned.
List of Ciphers supported is the same as those supported by
`csum.py`
"""
logging.debug('Starting download for %s with checksum: %s', url, checksum)
response = requests.get(url)
if response.status_code != requests.codes.ok:
logging.debug('HTTP Request to %s failed with error code %d',
url, response.status_code)
raise DownloadError('HTTP Request response error')
mar = response.content
if not verify(mar, checksum, cipher):
logging.warning('Verification of %s with checksum %s failed',
url, checksum)
raise DownloadError('Checksums do not match')
else:
logging.info('Verified download of %s', url)
if output_file:
try:
logging.info('Writing download %s to file %s', url, output_file)
# TODO ROUGHEDGE write in blocks of 1MB anc check afterwards?
with open(output_file, 'wb') as fobj:
fobj.write(mar)
except:
logging.error('Error while downloading %s to file %s on disk',
url, output_file)
raise DownloadError('Failed to write file to disk')
else:
return None
else:
return mar
Remove useless TODO from codebase."""
funsize.fetch
~~~~~~~~~~~~~~~~~~
This module contains fetch functions
"""
import logging
import requests
from .csum import verify
from .oddity import DownloadError
def downloadmar(url, checksum, cipher='sha512', output_file=None):
""" Downloads the file specified by url, verifies the checksum.
The file is written to the location specified by output file,
if not specified, the downloaded file is returned.
List of Ciphers supported is the same as those supported by
`csum.py`
"""
logging.debug('Starting download for %s with checksum: %s', url, checksum)
response = requests.get(url)
if response.status_code != requests.codes.ok:
logging.debug('HTTP Request to %s failed with error code %d',
url, response.status_code)
raise DownloadError('HTTP Request response error')
mar = response.content
if not verify(mar, checksum, cipher):
logging.warning('Verification of %s with checksum %s failed',
url, checksum)
raise DownloadError('Checksums do not match')
else:
logging.info('Verified download of %s', url)
if output_file:
try:
logging.info('Writing download %s to file %s', url, output_file)
with open(output_file, 'wb') as fobj:
fobj.write(mar)
except:
logging.error('Error while downloading %s to file %s on disk',
url, output_file)
raise DownloadError('Failed to write file to disk')
else:
return None
else:
return mar
|
<commit_before>"""
funsize.fetch
~~~~~~~~~~~~~~~~~~
This module contains fetch functions
"""
import logging
import requests
from .csum import verify
from .oddity import DownloadError
def downloadmar(url, checksum, cipher='sha512', output_file=None):
""" Downloads the file specified by url, verifies the checksum.
The file is written to the location specified by output file,
if not specified, the downloaded file is returned.
List of Ciphers supported is the same as those supported by
`csum.py`
"""
logging.debug('Starting download for %s with checksum: %s', url, checksum)
response = requests.get(url)
if response.status_code != requests.codes.ok:
logging.debug('HTTP Request to %s failed with error code %d',
url, response.status_code)
raise DownloadError('HTTP Request response error')
mar = response.content
if not verify(mar, checksum, cipher):
logging.warning('Verification of %s with checksum %s failed',
url, checksum)
raise DownloadError('Checksums do not match')
else:
logging.info('Verified download of %s', url)
if output_file:
try:
logging.info('Writing download %s to file %s', url, output_file)
# TODO ROUGHEDGE write in blocks of 1MB anc check afterwards?
with open(output_file, 'wb') as fobj:
fobj.write(mar)
except:
logging.error('Error while downloading %s to file %s on disk',
url, output_file)
raise DownloadError('Failed to write file to disk')
else:
return None
else:
return mar
<commit_msg>Remove useless TODO from codebase.<commit_after>"""
funsize.fetch
~~~~~~~~~~~~~~~~~~
This module contains fetch functions
"""
import logging
import requests
from .csum import verify
from .oddity import DownloadError
def downloadmar(url, checksum, cipher='sha512', output_file=None):
""" Downloads the file specified by url, verifies the checksum.
The file is written to the location specified by output file,
if not specified, the downloaded file is returned.
List of Ciphers supported is the same as those supported by
`csum.py`
"""
logging.debug('Starting download for %s with checksum: %s', url, checksum)
response = requests.get(url)
if response.status_code != requests.codes.ok:
logging.debug('HTTP Request to %s failed with error code %d',
url, response.status_code)
raise DownloadError('HTTP Request response error')
mar = response.content
if not verify(mar, checksum, cipher):
logging.warning('Verification of %s with checksum %s failed',
url, checksum)
raise DownloadError('Checksums do not match')
else:
logging.info('Verified download of %s', url)
if output_file:
try:
logging.info('Writing download %s to file %s', url, output_file)
with open(output_file, 'wb') as fobj:
fobj.write(mar)
except:
logging.error('Error while downloading %s to file %s on disk',
url, output_file)
raise DownloadError('Failed to write file to disk')
else:
return None
else:
return mar
|
49990a967471f615936025c17ac1411e2976f159
|
neuroimaging/utils/tests/test_odict.py
|
neuroimaging/utils/tests/test_odict.py
|
"""Test file for the ordered dictionary module, odict.py."""
from neuroimaging.externals.scipy.testing import *
from neuroimaging.utils.odict import odict
class TestOdict(TestCase):
def setUp(self):
print 'setUp'
self.thedict = odict((('one', 1.0), ('two', 2.0), ('three', 3.0)))
def test_copy(self):
"""Test odict.copy method."""
print self.thedict
cpydict = self.thedict.copy()
assert cpydict == self.thedict
# test that it's a copy and not a reference
assert cpydict is not self.thedict
if __name__ == "__main__":
nose.run(argv=['', __file__])
|
"""Test file for the ordered dictionary module, odict.py."""
from neuroimaging.externals.scipy.testing import *
from neuroimaging.utils.odict import odict
class TestOdict(TestCase):
def setUp(self):
print 'setUp'
self.thedict = odict((('one', 1.0), ('two', 2.0), ('three', 3.0)))
def test_copy(self):
"""Test odict.copy method."""
print self.thedict
cpydict = self.thedict.copy()
assert cpydict == self.thedict
# test that it's a copy and not a reference
assert cpydict is not self.thedict
if __name__ == "__main__":
nose.runmodule()
|
Fix nose call so tests run in __main__.
|
BUG: Fix nose call so tests run in __main__.
|
Python
|
bsd-3-clause
|
yarikoptic/NiPy-OLD,yarikoptic/NiPy-OLD
|
"""Test file for the ordered dictionary module, odict.py."""
from neuroimaging.externals.scipy.testing import *
from neuroimaging.utils.odict import odict
class TestOdict(TestCase):
def setUp(self):
print 'setUp'
self.thedict = odict((('one', 1.0), ('two', 2.0), ('three', 3.0)))
def test_copy(self):
"""Test odict.copy method."""
print self.thedict
cpydict = self.thedict.copy()
assert cpydict == self.thedict
# test that it's a copy and not a reference
assert cpydict is not self.thedict
if __name__ == "__main__":
nose.run(argv=['', __file__])
BUG: Fix nose call so tests run in __main__.
|
"""Test file for the ordered dictionary module, odict.py."""
from neuroimaging.externals.scipy.testing import *
from neuroimaging.utils.odict import odict
class TestOdict(TestCase):
def setUp(self):
print 'setUp'
self.thedict = odict((('one', 1.0), ('two', 2.0), ('three', 3.0)))
def test_copy(self):
"""Test odict.copy method."""
print self.thedict
cpydict = self.thedict.copy()
assert cpydict == self.thedict
# test that it's a copy and not a reference
assert cpydict is not self.thedict
if __name__ == "__main__":
nose.runmodule()
|
<commit_before>"""Test file for the ordered dictionary module, odict.py."""
from neuroimaging.externals.scipy.testing import *
from neuroimaging.utils.odict import odict
class TestOdict(TestCase):
def setUp(self):
print 'setUp'
self.thedict = odict((('one', 1.0), ('two', 2.0), ('three', 3.0)))
def test_copy(self):
"""Test odict.copy method."""
print self.thedict
cpydict = self.thedict.copy()
assert cpydict == self.thedict
# test that it's a copy and not a reference
assert cpydict is not self.thedict
if __name__ == "__main__":
nose.run(argv=['', __file__])
<commit_msg>BUG: Fix nose call so tests run in __main__.<commit_after>
|
"""Test file for the ordered dictionary module, odict.py."""
from neuroimaging.externals.scipy.testing import *
from neuroimaging.utils.odict import odict
class TestOdict(TestCase):
def setUp(self):
print 'setUp'
self.thedict = odict((('one', 1.0), ('two', 2.0), ('three', 3.0)))
def test_copy(self):
"""Test odict.copy method."""
print self.thedict
cpydict = self.thedict.copy()
assert cpydict == self.thedict
# test that it's a copy and not a reference
assert cpydict is not self.thedict
if __name__ == "__main__":
nose.runmodule()
|
"""Test file for the ordered dictionary module, odict.py."""
from neuroimaging.externals.scipy.testing import *
from neuroimaging.utils.odict import odict
class TestOdict(TestCase):
def setUp(self):
print 'setUp'
self.thedict = odict((('one', 1.0), ('two', 2.0), ('three', 3.0)))
def test_copy(self):
"""Test odict.copy method."""
print self.thedict
cpydict = self.thedict.copy()
assert cpydict == self.thedict
# test that it's a copy and not a reference
assert cpydict is not self.thedict
if __name__ == "__main__":
nose.run(argv=['', __file__])
BUG: Fix nose call so tests run in __main__."""Test file for the ordered dictionary module, odict.py."""
from neuroimaging.externals.scipy.testing import *
from neuroimaging.utils.odict import odict
class TestOdict(TestCase):
def setUp(self):
print 'setUp'
self.thedict = odict((('one', 1.0), ('two', 2.0), ('three', 3.0)))
def test_copy(self):
"""Test odict.copy method."""
print self.thedict
cpydict = self.thedict.copy()
assert cpydict == self.thedict
# test that it's a copy and not a reference
assert cpydict is not self.thedict
if __name__ == "__main__":
nose.runmodule()
|
<commit_before>"""Test file for the ordered dictionary module, odict.py."""
from neuroimaging.externals.scipy.testing import *
from neuroimaging.utils.odict import odict
class TestOdict(TestCase):
def setUp(self):
print 'setUp'
self.thedict = odict((('one', 1.0), ('two', 2.0), ('three', 3.0)))
def test_copy(self):
"""Test odict.copy method."""
print self.thedict
cpydict = self.thedict.copy()
assert cpydict == self.thedict
# test that it's a copy and not a reference
assert cpydict is not self.thedict
if __name__ == "__main__":
nose.run(argv=['', __file__])
<commit_msg>BUG: Fix nose call so tests run in __main__.<commit_after>"""Test file for the ordered dictionary module, odict.py."""
from neuroimaging.externals.scipy.testing import *
from neuroimaging.utils.odict import odict
class TestOdict(TestCase):
def setUp(self):
print 'setUp'
self.thedict = odict((('one', 1.0), ('two', 2.0), ('three', 3.0)))
def test_copy(self):
"""Test odict.copy method."""
print self.thedict
cpydict = self.thedict.copy()
assert cpydict == self.thedict
# test that it's a copy and not a reference
assert cpydict is not self.thedict
if __name__ == "__main__":
nose.runmodule()
|
dac71e1741eed7c5412661e852ee435ee7f30c21
|
lingcod/layers/urls.py
|
lingcod/layers/urls.py
|
from django.conf.urls.defaults import *
urlpatterns = patterns('lingcod.layers.views',
url(r'^public/',
'get_public_layers',
name='public-data-layers'),
url(r'^kml_file/(?P<session_key>\w+)/(?P<uid>[\w_]+).kml',
'get_kml_file',
name='kml-file'),
url(r'^privatekml/(?P<session_key>\w+)/$',
'get_privatekml_list',
name='layers-privatekml-list'),
url(r'^privatekml/(?P<session_key>\w+)/(?P<pk>\d+)/$',
'get_privatekml',
name='layers-privatekml'),
url(r'^privatekml/(?P<session_key>\w+)/(?P<pk>\d+)/(?P<path>[^\z]+)$',
'get_relative_to_privatekml',
name='layers-privatekml-relative'),
)
|
from django.conf.urls.defaults import *
import time
urlpatterns = patterns('lingcod.layers.views',
url(r'^public/$',
'get_public_layers',
name='public-data-layers'),
# Useful for debugging, avoids GE caching interference
url(r'^public/cachebuster/%s' % str(time.time()),
'get_public_layers',
name='public-data-layers-cachebuster'),
url(r'^kml_file/(?P<session_key>\w+)/(?P<uid>[\w_]+).kml',
'get_kml_file',
name='kml-file'),
url(r'^privatekml/(?P<session_key>\w+)/$',
'get_privatekml_list',
name='layers-privatekml-list'),
url(r'^privatekml/(?P<session_key>\w+)/(?P<pk>\d+)/$',
'get_privatekml',
name='layers-privatekml'),
url(r'^privatekml/(?P<session_key>\w+)/(?P<pk>\d+)/(?P<path>[^\z]+)$',
'get_relative_to_privatekml',
name='layers-privatekml-relative'),
)
|
Add another url pattern for debugging public layers
|
Add another url pattern for debugging public layers
--HG--
branch : bookmarks
|
Python
|
bsd-3-clause
|
underbluewaters/marinemap,underbluewaters/marinemap,underbluewaters/marinemap
|
from django.conf.urls.defaults import *
urlpatterns = patterns('lingcod.layers.views',
url(r'^public/',
'get_public_layers',
name='public-data-layers'),
url(r'^kml_file/(?P<session_key>\w+)/(?P<uid>[\w_]+).kml',
'get_kml_file',
name='kml-file'),
url(r'^privatekml/(?P<session_key>\w+)/$',
'get_privatekml_list',
name='layers-privatekml-list'),
url(r'^privatekml/(?P<session_key>\w+)/(?P<pk>\d+)/$',
'get_privatekml',
name='layers-privatekml'),
url(r'^privatekml/(?P<session_key>\w+)/(?P<pk>\d+)/(?P<path>[^\z]+)$',
'get_relative_to_privatekml',
name='layers-privatekml-relative'),
)
Add another url pattern for debugging public layers
--HG--
branch : bookmarks
|
from django.conf.urls.defaults import *
import time
urlpatterns = patterns('lingcod.layers.views',
url(r'^public/$',
'get_public_layers',
name='public-data-layers'),
# Useful for debugging, avoids GE caching interference
url(r'^public/cachebuster/%s' % str(time.time()),
'get_public_layers',
name='public-data-layers-cachebuster'),
url(r'^kml_file/(?P<session_key>\w+)/(?P<uid>[\w_]+).kml',
'get_kml_file',
name='kml-file'),
url(r'^privatekml/(?P<session_key>\w+)/$',
'get_privatekml_list',
name='layers-privatekml-list'),
url(r'^privatekml/(?P<session_key>\w+)/(?P<pk>\d+)/$',
'get_privatekml',
name='layers-privatekml'),
url(r'^privatekml/(?P<session_key>\w+)/(?P<pk>\d+)/(?P<path>[^\z]+)$',
'get_relative_to_privatekml',
name='layers-privatekml-relative'),
)
|
<commit_before>from django.conf.urls.defaults import *
urlpatterns = patterns('lingcod.layers.views',
url(r'^public/',
'get_public_layers',
name='public-data-layers'),
url(r'^kml_file/(?P<session_key>\w+)/(?P<uid>[\w_]+).kml',
'get_kml_file',
name='kml-file'),
url(r'^privatekml/(?P<session_key>\w+)/$',
'get_privatekml_list',
name='layers-privatekml-list'),
url(r'^privatekml/(?P<session_key>\w+)/(?P<pk>\d+)/$',
'get_privatekml',
name='layers-privatekml'),
url(r'^privatekml/(?P<session_key>\w+)/(?P<pk>\d+)/(?P<path>[^\z]+)$',
'get_relative_to_privatekml',
name='layers-privatekml-relative'),
)
<commit_msg>Add another url pattern for debugging public layers
--HG--
branch : bookmarks<commit_after>
|
from django.conf.urls.defaults import *
import time
urlpatterns = patterns('lingcod.layers.views',
url(r'^public/$',
'get_public_layers',
name='public-data-layers'),
# Useful for debugging, avoids GE caching interference
url(r'^public/cachebuster/%s' % str(time.time()),
'get_public_layers',
name='public-data-layers-cachebuster'),
url(r'^kml_file/(?P<session_key>\w+)/(?P<uid>[\w_]+).kml',
'get_kml_file',
name='kml-file'),
url(r'^privatekml/(?P<session_key>\w+)/$',
'get_privatekml_list',
name='layers-privatekml-list'),
url(r'^privatekml/(?P<session_key>\w+)/(?P<pk>\d+)/$',
'get_privatekml',
name='layers-privatekml'),
url(r'^privatekml/(?P<session_key>\w+)/(?P<pk>\d+)/(?P<path>[^\z]+)$',
'get_relative_to_privatekml',
name='layers-privatekml-relative'),
)
|
from django.conf.urls.defaults import *
urlpatterns = patterns('lingcod.layers.views',
url(r'^public/',
'get_public_layers',
name='public-data-layers'),
url(r'^kml_file/(?P<session_key>\w+)/(?P<uid>[\w_]+).kml',
'get_kml_file',
name='kml-file'),
url(r'^privatekml/(?P<session_key>\w+)/$',
'get_privatekml_list',
name='layers-privatekml-list'),
url(r'^privatekml/(?P<session_key>\w+)/(?P<pk>\d+)/$',
'get_privatekml',
name='layers-privatekml'),
url(r'^privatekml/(?P<session_key>\w+)/(?P<pk>\d+)/(?P<path>[^\z]+)$',
'get_relative_to_privatekml',
name='layers-privatekml-relative'),
)
Add another url pattern for debugging public layers
--HG--
branch : bookmarksfrom django.conf.urls.defaults import *
import time
urlpatterns = patterns('lingcod.layers.views',
url(r'^public/$',
'get_public_layers',
name='public-data-layers'),
# Useful for debugging, avoids GE caching interference
url(r'^public/cachebuster/%s' % str(time.time()),
'get_public_layers',
name='public-data-layers-cachebuster'),
url(r'^kml_file/(?P<session_key>\w+)/(?P<uid>[\w_]+).kml',
'get_kml_file',
name='kml-file'),
url(r'^privatekml/(?P<session_key>\w+)/$',
'get_privatekml_list',
name='layers-privatekml-list'),
url(r'^privatekml/(?P<session_key>\w+)/(?P<pk>\d+)/$',
'get_privatekml',
name='layers-privatekml'),
url(r'^privatekml/(?P<session_key>\w+)/(?P<pk>\d+)/(?P<path>[^\z]+)$',
'get_relative_to_privatekml',
name='layers-privatekml-relative'),
)
|
<commit_before>from django.conf.urls.defaults import *
urlpatterns = patterns('lingcod.layers.views',
url(r'^public/',
'get_public_layers',
name='public-data-layers'),
url(r'^kml_file/(?P<session_key>\w+)/(?P<uid>[\w_]+).kml',
'get_kml_file',
name='kml-file'),
url(r'^privatekml/(?P<session_key>\w+)/$',
'get_privatekml_list',
name='layers-privatekml-list'),
url(r'^privatekml/(?P<session_key>\w+)/(?P<pk>\d+)/$',
'get_privatekml',
name='layers-privatekml'),
url(r'^privatekml/(?P<session_key>\w+)/(?P<pk>\d+)/(?P<path>[^\z]+)$',
'get_relative_to_privatekml',
name='layers-privatekml-relative'),
)
<commit_msg>Add another url pattern for debugging public layers
--HG--
branch : bookmarks<commit_after>from django.conf.urls.defaults import *
import time
urlpatterns = patterns('lingcod.layers.views',
url(r'^public/$',
'get_public_layers',
name='public-data-layers'),
# Useful for debugging, avoids GE caching interference
url(r'^public/cachebuster/%s' % str(time.time()),
'get_public_layers',
name='public-data-layers-cachebuster'),
url(r'^kml_file/(?P<session_key>\w+)/(?P<uid>[\w_]+).kml',
'get_kml_file',
name='kml-file'),
url(r'^privatekml/(?P<session_key>\w+)/$',
'get_privatekml_list',
name='layers-privatekml-list'),
url(r'^privatekml/(?P<session_key>\w+)/(?P<pk>\d+)/$',
'get_privatekml',
name='layers-privatekml'),
url(r'^privatekml/(?P<session_key>\w+)/(?P<pk>\d+)/(?P<path>[^\z]+)$',
'get_relative_to_privatekml',
name='layers-privatekml-relative'),
)
|
1dd06e1be96beb0088e58e06e9e775063e14b6ec
|
moksha/hub/reactor.py
|
moksha/hub/reactor.py
|
# This file is part of Moksha.
#
# Moksha is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Moksha is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Moksha. If not, see <http://www.gnu.org/licenses/>.
#
# Copyright 2008, Red Hat, Inc.
# Authors: Luke Macken <lmacken@redhat.com>
"""
Choses the best platform-specific Twisted reactor
"""
import sys
try:
if 'linux' in sys.platform:
from twisted.internet import epollreactor
epollreactor.install()
elif 'win' in sys.platform:
from twisted.internet import iocpreactor
iocpreactor.install()
elif 'freebsd' in sys.platform or 'darwin' in sys.platform:
from twisted.internet import kqreactor
kqreactor.install()
except AssertionError: # reactor already installed
pass
from twisted.internet import reactor
|
# This file is part of Moksha.
#
# Moksha is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Moksha is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Moksha. If not, see <http://www.gnu.org/licenses/>.
#
# Copyright 2008, Red Hat, Inc.
# Authors: Luke Macken <lmacken@redhat.com>
"""
Choses the best platform-specific Twisted reactor
"""
import sys
try:
if 'linux' in sys.platform:
from twisted.internet import epollreactor
epollreactor.install()
elif 'freebsd' in sys.platform or 'darwin' in sys.platform:
from twisted.internet import kqreactor
kqreactor.install()
elif 'win' in sys.platform:
from twisted.internet import iocpreactor
iocpreactor.install()
except AssertionError: # reactor already installed
pass
from twisted.internet import reactor
|
Fix a bug on platform detection on Mac OSX
|
Fix a bug on platform detection on Mac OSX
|
Python
|
apache-2.0
|
pombredanne/moksha,lmacken/moksha,ralphbean/moksha,pombredanne/moksha,mokshaproject/moksha,mokshaproject/moksha,ralphbean/moksha,pombredanne/moksha,lmacken/moksha,lmacken/moksha,mokshaproject/moksha,pombredanne/moksha,ralphbean/moksha,mokshaproject/moksha
|
# This file is part of Moksha.
#
# Moksha is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Moksha is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Moksha. If not, see <http://www.gnu.org/licenses/>.
#
# Copyright 2008, Red Hat, Inc.
# Authors: Luke Macken <lmacken@redhat.com>
"""
Choses the best platform-specific Twisted reactor
"""
import sys
try:
if 'linux' in sys.platform:
from twisted.internet import epollreactor
epollreactor.install()
elif 'win' in sys.platform:
from twisted.internet import iocpreactor
iocpreactor.install()
elif 'freebsd' in sys.platform or 'darwin' in sys.platform:
from twisted.internet import kqreactor
kqreactor.install()
except AssertionError: # reactor already installed
pass
from twisted.internet import reactor
Fix a bug on platform detection on Mac OSX
|
# This file is part of Moksha.
#
# Moksha is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Moksha is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Moksha. If not, see <http://www.gnu.org/licenses/>.
#
# Copyright 2008, Red Hat, Inc.
# Authors: Luke Macken <lmacken@redhat.com>
"""
Choses the best platform-specific Twisted reactor
"""
import sys
try:
if 'linux' in sys.platform:
from twisted.internet import epollreactor
epollreactor.install()
elif 'freebsd' in sys.platform or 'darwin' in sys.platform:
from twisted.internet import kqreactor
kqreactor.install()
elif 'win' in sys.platform:
from twisted.internet import iocpreactor
iocpreactor.install()
except AssertionError: # reactor already installed
pass
from twisted.internet import reactor
|
<commit_before># This file is part of Moksha.
#
# Moksha is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Moksha is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Moksha. If not, see <http://www.gnu.org/licenses/>.
#
# Copyright 2008, Red Hat, Inc.
# Authors: Luke Macken <lmacken@redhat.com>
"""
Choses the best platform-specific Twisted reactor
"""
import sys
try:
if 'linux' in sys.platform:
from twisted.internet import epollreactor
epollreactor.install()
elif 'win' in sys.platform:
from twisted.internet import iocpreactor
iocpreactor.install()
elif 'freebsd' in sys.platform or 'darwin' in sys.platform:
from twisted.internet import kqreactor
kqreactor.install()
except AssertionError: # reactor already installed
pass
from twisted.internet import reactor
<commit_msg>Fix a bug on platform detection on Mac OSX<commit_after>
|
# This file is part of Moksha.
#
# Moksha is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Moksha is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Moksha. If not, see <http://www.gnu.org/licenses/>.
#
# Copyright 2008, Red Hat, Inc.
# Authors: Luke Macken <lmacken@redhat.com>
"""
Choses the best platform-specific Twisted reactor
"""
import sys
try:
if 'linux' in sys.platform:
from twisted.internet import epollreactor
epollreactor.install()
elif 'freebsd' in sys.platform or 'darwin' in sys.platform:
from twisted.internet import kqreactor
kqreactor.install()
elif 'win' in sys.platform:
from twisted.internet import iocpreactor
iocpreactor.install()
except AssertionError: # reactor already installed
pass
from twisted.internet import reactor
|
# This file is part of Moksha.
#
# Moksha is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Moksha is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Moksha. If not, see <http://www.gnu.org/licenses/>.
#
# Copyright 2008, Red Hat, Inc.
# Authors: Luke Macken <lmacken@redhat.com>
"""
Choses the best platform-specific Twisted reactor
"""
import sys
try:
if 'linux' in sys.platform:
from twisted.internet import epollreactor
epollreactor.install()
elif 'win' in sys.platform:
from twisted.internet import iocpreactor
iocpreactor.install()
elif 'freebsd' in sys.platform or 'darwin' in sys.platform:
from twisted.internet import kqreactor
kqreactor.install()
except AssertionError: # reactor already installed
pass
from twisted.internet import reactor
Fix a bug on platform detection on Mac OSX# This file is part of Moksha.
#
# Moksha is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Moksha is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Moksha. If not, see <http://www.gnu.org/licenses/>.
#
# Copyright 2008, Red Hat, Inc.
# Authors: Luke Macken <lmacken@redhat.com>
"""
Choses the best platform-specific Twisted reactor
"""
import sys
try:
if 'linux' in sys.platform:
from twisted.internet import epollreactor
epollreactor.install()
elif 'freebsd' in sys.platform or 'darwin' in sys.platform:
from twisted.internet import kqreactor
kqreactor.install()
elif 'win' in sys.platform:
from twisted.internet import iocpreactor
iocpreactor.install()
except AssertionError: # reactor already installed
pass
from twisted.internet import reactor
|
<commit_before># This file is part of Moksha.
#
# Moksha is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Moksha is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Moksha. If not, see <http://www.gnu.org/licenses/>.
#
# Copyright 2008, Red Hat, Inc.
# Authors: Luke Macken <lmacken@redhat.com>
"""
Choses the best platform-specific Twisted reactor
"""
import sys
try:
if 'linux' in sys.platform:
from twisted.internet import epollreactor
epollreactor.install()
elif 'win' in sys.platform:
from twisted.internet import iocpreactor
iocpreactor.install()
elif 'freebsd' in sys.platform or 'darwin' in sys.platform:
from twisted.internet import kqreactor
kqreactor.install()
except AssertionError: # reactor already installed
pass
from twisted.internet import reactor
<commit_msg>Fix a bug on platform detection on Mac OSX<commit_after># This file is part of Moksha.
#
# Moksha is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Moksha is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Moksha. If not, see <http://www.gnu.org/licenses/>.
#
# Copyright 2008, Red Hat, Inc.
# Authors: Luke Macken <lmacken@redhat.com>
"""
Choses the best platform-specific Twisted reactor
"""
import sys
try:
if 'linux' in sys.platform:
from twisted.internet import epollreactor
epollreactor.install()
elif 'freebsd' in sys.platform or 'darwin' in sys.platform:
from twisted.internet import kqreactor
kqreactor.install()
elif 'win' in sys.platform:
from twisted.internet import iocpreactor
iocpreactor.install()
except AssertionError: # reactor already installed
pass
from twisted.internet import reactor
|
5c70751806c69bded77821b87d728821e37152c8
|
web/server.py
|
web/server.py
|
from flask import Flask, request, session, g, redirect, url_for, abort, \
render_template, jsonify, make_response
import json
from decorators import Monitor
app = Flask(__name__)
#app.wsgi_app = WSGIApplication(app.config['APPINSIGHTS_INSTRUMENTATION_KEY'], app.wsgi_app)
@app.route('/')
@Monitor.api()
def index():
return 'Newsalyzer'
@app.route('/get-sentiment', endpoint='get_sentiment')
@Monitor.api()
def get_sentiment():
from google.cloud import language
language_client = language.Client()
text = request.args['text']
document = language_client.document_from_text(text)
# Detects the sentiment of the text
sentiment = document.analyze_sentiment().sentiment
entity_response = document.analyze_entities()
response = {
'score' : sentiment.score,
'magnitude' : sentiment.magnitude,
'entities' : [ { 'name': e.name, 'type': e.entity_type, 'sentiment' : e.sentiment } for e in entity_response.entities]
}
return json.dumps(response), 200, {'ContentType':'application/json'}
if __name__=='__main__':
app.run()
|
import os
from flask import Flask, request, session, g, redirect, url_for, abort, \
render_template, jsonify, make_response
import json
from google.cloud import language
from decorators import Monitor
from blob_storage import BlobStorage
app = Flask(__name__)
#app.wsgi_app = WSGIApplication(app.config['APPINSIGHTS_INSTRUMENTATION_KEY'], app.wsgi_app)
if os.environ.has_key('STORAGE_ACCOUNT_NAME'):
local_key_file = 'private/google-nlp-key.json'
blob_storage = BlobStorage(os.environ['STORAGE_ACCOUNT_NAME'], os.environ['STORAGE_ACCOUNT_KEY'])
blob_storage.download_file('private', 'google-nlp-key.json', local_key_file)
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = local_key_file
@app.route('/')
@Monitor.api()
def index():
return 'Newsalyzer'
@app.route('/get-sentiment', endpoint='get_sentiment')
@Monitor.api()
def get_sentiment():
language_client = language.Client(api_version='v1beta2')
document = language_client.document_from_text(request.args['text'])
# Detects the sentiment of the text
sentiment = document.analyze_sentiment().sentiment
entity_response = document.analyze_entity_sentiment()
response = {
'score' : sentiment.score,
'magnitude' : sentiment.magnitude,
'entities' : [ { 'name': e.name, 'type': e.entity_type, 'sentiment' : e.sentiment.score, 'magnitude': e.sentiment.magnitude } for e in entity_response.entities]
}
return json.dumps(response), 200, {'ContentType':'application/json'}
if __name__=='__main__':
app.run()
|
Fix bugs in sentiment analysis code so entity sentiment is returned
|
Fix bugs in sentiment analysis code so entity sentiment is returned
|
Python
|
mit
|
harigov/newsalyzer,harigov/newsalyzer,harigov/newsalyzer
|
from flask import Flask, request, session, g, redirect, url_for, abort, \
render_template, jsonify, make_response
import json
from decorators import Monitor
app = Flask(__name__)
#app.wsgi_app = WSGIApplication(app.config['APPINSIGHTS_INSTRUMENTATION_KEY'], app.wsgi_app)
@app.route('/')
@Monitor.api()
def index():
return 'Newsalyzer'
@app.route('/get-sentiment', endpoint='get_sentiment')
@Monitor.api()
def get_sentiment():
from google.cloud import language
language_client = language.Client()
text = request.args['text']
document = language_client.document_from_text(text)
# Detects the sentiment of the text
sentiment = document.analyze_sentiment().sentiment
entity_response = document.analyze_entities()
response = {
'score' : sentiment.score,
'magnitude' : sentiment.magnitude,
'entities' : [ { 'name': e.name, 'type': e.entity_type, 'sentiment' : e.sentiment } for e in entity_response.entities]
}
return json.dumps(response), 200, {'ContentType':'application/json'}
if __name__=='__main__':
app.run()
Fix bugs in sentiment analysis code so entity sentiment is returned
|
import os
from flask import Flask, request, session, g, redirect, url_for, abort, \
render_template, jsonify, make_response
import json
from google.cloud import language
from decorators import Monitor
from blob_storage import BlobStorage
app = Flask(__name__)
#app.wsgi_app = WSGIApplication(app.config['APPINSIGHTS_INSTRUMENTATION_KEY'], app.wsgi_app)
if os.environ.has_key('STORAGE_ACCOUNT_NAME'):
local_key_file = 'private/google-nlp-key.json'
blob_storage = BlobStorage(os.environ['STORAGE_ACCOUNT_NAME'], os.environ['STORAGE_ACCOUNT_KEY'])
blob_storage.download_file('private', 'google-nlp-key.json', local_key_file)
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = local_key_file
@app.route('/')
@Monitor.api()
def index():
return 'Newsalyzer'
@app.route('/get-sentiment', endpoint='get_sentiment')
@Monitor.api()
def get_sentiment():
language_client = language.Client(api_version='v1beta2')
document = language_client.document_from_text(request.args['text'])
# Detects the sentiment of the text
sentiment = document.analyze_sentiment().sentiment
entity_response = document.analyze_entity_sentiment()
response = {
'score' : sentiment.score,
'magnitude' : sentiment.magnitude,
'entities' : [ { 'name': e.name, 'type': e.entity_type, 'sentiment' : e.sentiment.score, 'magnitude': e.sentiment.magnitude } for e in entity_response.entities]
}
return json.dumps(response), 200, {'ContentType':'application/json'}
if __name__=='__main__':
app.run()
|
<commit_before>from flask import Flask, request, session, g, redirect, url_for, abort, \
render_template, jsonify, make_response
import json
from decorators import Monitor
app = Flask(__name__)
#app.wsgi_app = WSGIApplication(app.config['APPINSIGHTS_INSTRUMENTATION_KEY'], app.wsgi_app)
@app.route('/')
@Monitor.api()
def index():
return 'Newsalyzer'
@app.route('/get-sentiment', endpoint='get_sentiment')
@Monitor.api()
def get_sentiment():
from google.cloud import language
language_client = language.Client()
text = request.args['text']
document = language_client.document_from_text(text)
# Detects the sentiment of the text
sentiment = document.analyze_sentiment().sentiment
entity_response = document.analyze_entities()
response = {
'score' : sentiment.score,
'magnitude' : sentiment.magnitude,
'entities' : [ { 'name': e.name, 'type': e.entity_type, 'sentiment' : e.sentiment } for e in entity_response.entities]
}
return json.dumps(response), 200, {'ContentType':'application/json'}
if __name__=='__main__':
app.run()
<commit_msg>Fix bugs in sentiment analysis code so entity sentiment is returned<commit_after>
|
import os
from flask import Flask, request, session, g, redirect, url_for, abort, \
render_template, jsonify, make_response
import json
from google.cloud import language
from decorators import Monitor
from blob_storage import BlobStorage
app = Flask(__name__)
#app.wsgi_app = WSGIApplication(app.config['APPINSIGHTS_INSTRUMENTATION_KEY'], app.wsgi_app)
if os.environ.has_key('STORAGE_ACCOUNT_NAME'):
local_key_file = 'private/google-nlp-key.json'
blob_storage = BlobStorage(os.environ['STORAGE_ACCOUNT_NAME'], os.environ['STORAGE_ACCOUNT_KEY'])
blob_storage.download_file('private', 'google-nlp-key.json', local_key_file)
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = local_key_file
@app.route('/')
@Monitor.api()
def index():
return 'Newsalyzer'
@app.route('/get-sentiment', endpoint='get_sentiment')
@Monitor.api()
def get_sentiment():
language_client = language.Client(api_version='v1beta2')
document = language_client.document_from_text(request.args['text'])
# Detects the sentiment of the text
sentiment = document.analyze_sentiment().sentiment
entity_response = document.analyze_entity_sentiment()
response = {
'score' : sentiment.score,
'magnitude' : sentiment.magnitude,
'entities' : [ { 'name': e.name, 'type': e.entity_type, 'sentiment' : e.sentiment.score, 'magnitude': e.sentiment.magnitude } for e in entity_response.entities]
}
return json.dumps(response), 200, {'ContentType':'application/json'}
if __name__=='__main__':
app.run()
|
from flask import Flask, request, session, g, redirect, url_for, abort, \
render_template, jsonify, make_response
import json
from decorators import Monitor
app = Flask(__name__)
#app.wsgi_app = WSGIApplication(app.config['APPINSIGHTS_INSTRUMENTATION_KEY'], app.wsgi_app)
@app.route('/')
@Monitor.api()
def index():
return 'Newsalyzer'
@app.route('/get-sentiment', endpoint='get_sentiment')
@Monitor.api()
def get_sentiment():
from google.cloud import language
language_client = language.Client()
text = request.args['text']
document = language_client.document_from_text(text)
# Detects the sentiment of the text
sentiment = document.analyze_sentiment().sentiment
entity_response = document.analyze_entities()
response = {
'score' : sentiment.score,
'magnitude' : sentiment.magnitude,
'entities' : [ { 'name': e.name, 'type': e.entity_type, 'sentiment' : e.sentiment } for e in entity_response.entities]
}
return json.dumps(response), 200, {'ContentType':'application/json'}
if __name__=='__main__':
app.run()
Fix bugs in sentiment analysis code so entity sentiment is returnedimport os
from flask import Flask, request, session, g, redirect, url_for, abort, \
render_template, jsonify, make_response
import json
from google.cloud import language
from decorators import Monitor
from blob_storage import BlobStorage
app = Flask(__name__)
#app.wsgi_app = WSGIApplication(app.config['APPINSIGHTS_INSTRUMENTATION_KEY'], app.wsgi_app)
if os.environ.has_key('STORAGE_ACCOUNT_NAME'):
local_key_file = 'private/google-nlp-key.json'
blob_storage = BlobStorage(os.environ['STORAGE_ACCOUNT_NAME'], os.environ['STORAGE_ACCOUNT_KEY'])
blob_storage.download_file('private', 'google-nlp-key.json', local_key_file)
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = local_key_file
@app.route('/')
@Monitor.api()
def index():
return 'Newsalyzer'
@app.route('/get-sentiment', endpoint='get_sentiment')
@Monitor.api()
def get_sentiment():
language_client = language.Client(api_version='v1beta2')
document = language_client.document_from_text(request.args['text'])
# Detects the sentiment of the text
sentiment = document.analyze_sentiment().sentiment
entity_response = document.analyze_entity_sentiment()
response = {
'score' : sentiment.score,
'magnitude' : sentiment.magnitude,
'entities' : [ { 'name': e.name, 'type': e.entity_type, 'sentiment' : e.sentiment.score, 'magnitude': e.sentiment.magnitude } for e in entity_response.entities]
}
return json.dumps(response), 200, {'ContentType':'application/json'}
if __name__=='__main__':
app.run()
|
<commit_before>from flask import Flask, request, session, g, redirect, url_for, abort, \
render_template, jsonify, make_response
import json
from decorators import Monitor
app = Flask(__name__)
#app.wsgi_app = WSGIApplication(app.config['APPINSIGHTS_INSTRUMENTATION_KEY'], app.wsgi_app)
@app.route('/')
@Monitor.api()
def index():
return 'Newsalyzer'
@app.route('/get-sentiment', endpoint='get_sentiment')
@Monitor.api()
def get_sentiment():
from google.cloud import language
language_client = language.Client()
text = request.args['text']
document = language_client.document_from_text(text)
# Detects the sentiment of the text
sentiment = document.analyze_sentiment().sentiment
entity_response = document.analyze_entities()
response = {
'score' : sentiment.score,
'magnitude' : sentiment.magnitude,
'entities' : [ { 'name': e.name, 'type': e.entity_type, 'sentiment' : e.sentiment } for e in entity_response.entities]
}
return json.dumps(response), 200, {'ContentType':'application/json'}
if __name__=='__main__':
app.run()
<commit_msg>Fix bugs in sentiment analysis code so entity sentiment is returned<commit_after>import os
from flask import Flask, request, session, g, redirect, url_for, abort, \
render_template, jsonify, make_response
import json
from google.cloud import language
from decorators import Monitor
from blob_storage import BlobStorage
app = Flask(__name__)
#app.wsgi_app = WSGIApplication(app.config['APPINSIGHTS_INSTRUMENTATION_KEY'], app.wsgi_app)
if os.environ.has_key('STORAGE_ACCOUNT_NAME'):
local_key_file = 'private/google-nlp-key.json'
blob_storage = BlobStorage(os.environ['STORAGE_ACCOUNT_NAME'], os.environ['STORAGE_ACCOUNT_KEY'])
blob_storage.download_file('private', 'google-nlp-key.json', local_key_file)
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = local_key_file
@app.route('/')
@Monitor.api()
def index():
return 'Newsalyzer'
@app.route('/get-sentiment', endpoint='get_sentiment')
@Monitor.api()
def get_sentiment():
language_client = language.Client(api_version='v1beta2')
document = language_client.document_from_text(request.args['text'])
# Detects the sentiment of the text
sentiment = document.analyze_sentiment().sentiment
entity_response = document.analyze_entity_sentiment()
response = {
'score' : sentiment.score,
'magnitude' : sentiment.magnitude,
'entities' : [ { 'name': e.name, 'type': e.entity_type, 'sentiment' : e.sentiment.score, 'magnitude': e.sentiment.magnitude } for e in entity_response.entities]
}
return json.dumps(response), 200, {'ContentType':'application/json'}
if __name__=='__main__':
app.run()
|
707fb2cabcfa9886c968e81964b59995c0b0f2b6
|
python/convert_line_endings.py
|
python/convert_line_endings.py
|
#!/usr/bin/python
import os
import sys
def convert_line_endings(file):
if '\r\n' in open(file, 'rb').read():
print '%s contains DOS line endings. Converting' % file
with open(file, 'rb') as infile:
text = infile.read()
text = text.replace('\r\n', '\n')
with open(file, 'wb') as outfile:
outfile.write(text)
def main():
if len(sys.argv) > 1:
convert_line_endings(sys.argv[1])
return
for dirpath, dirnames, filenames in os.walk('.'):
for file in filenames:
if os.path.splitext(file)[1] == '.cs':
csPath = os.path.join(dirpath, file)
convert_line_endings(csPath)
if __name__ == "__main__":
main()
|
#!/usr/bin/python
import os
import sys
def convert_line_endings(file):
if '\r\n' in open(file, 'rb').read():
print '%s contains DOS line endings. Converting' % file
with open(file, 'rb') as infile:
text = infile.read()
text = text.replace('\r\n', '\n')
with open(file, 'wb') as outfile:
outfile.write(text)
def processPath(dirPath, ext):
for dirpath, dirnames, filenames in os.walk(dirPath):
for file in filenames:
if os.path.splitext(file)[1] == ext:
csPath = os.path.join(dirpath, file)
convert_line_endings(csPath)
if __name__ == "__main__":
if len(sys.argv) > 1:
convert_line_endings(sys.argv[1])
return
processPath('.', '.cs')
processPath('testpackages', '.h')
processPath('testpackages', '.c')
processPath('testpackages', '.cpp')
|
Convert line endings for .h, .c and .cpp files as well as .cs
|
[trunk] Convert line endings for .h, .c and .cpp files as well as .cs
|
Python
|
bsd-3-clause
|
markfinal/BuildAMation,markfinal/BuildAMation,markfinal/BuildAMation,markfinal/BuildAMation,markfinal/BuildAMation
|
#!/usr/bin/python
import os
import sys
def convert_line_endings(file):
if '\r\n' in open(file, 'rb').read():
print '%s contains DOS line endings. Converting' % file
with open(file, 'rb') as infile:
text = infile.read()
text = text.replace('\r\n', '\n')
with open(file, 'wb') as outfile:
outfile.write(text)
def main():
if len(sys.argv) > 1:
convert_line_endings(sys.argv[1])
return
for dirpath, dirnames, filenames in os.walk('.'):
for file in filenames:
if os.path.splitext(file)[1] == '.cs':
csPath = os.path.join(dirpath, file)
convert_line_endings(csPath)
if __name__ == "__main__":
main()
[trunk] Convert line endings for .h, .c and .cpp files as well as .cs
|
#!/usr/bin/python
import os
import sys
def convert_line_endings(file):
if '\r\n' in open(file, 'rb').read():
print '%s contains DOS line endings. Converting' % file
with open(file, 'rb') as infile:
text = infile.read()
text = text.replace('\r\n', '\n')
with open(file, 'wb') as outfile:
outfile.write(text)
def processPath(dirPath, ext):
for dirpath, dirnames, filenames in os.walk(dirPath):
for file in filenames:
if os.path.splitext(file)[1] == ext:
csPath = os.path.join(dirpath, file)
convert_line_endings(csPath)
if __name__ == "__main__":
if len(sys.argv) > 1:
convert_line_endings(sys.argv[1])
return
processPath('.', '.cs')
processPath('testpackages', '.h')
processPath('testpackages', '.c')
processPath('testpackages', '.cpp')
|
<commit_before>#!/usr/bin/python
import os
import sys
def convert_line_endings(file):
if '\r\n' in open(file, 'rb').read():
print '%s contains DOS line endings. Converting' % file
with open(file, 'rb') as infile:
text = infile.read()
text = text.replace('\r\n', '\n')
with open(file, 'wb') as outfile:
outfile.write(text)
def main():
if len(sys.argv) > 1:
convert_line_endings(sys.argv[1])
return
for dirpath, dirnames, filenames in os.walk('.'):
for file in filenames:
if os.path.splitext(file)[1] == '.cs':
csPath = os.path.join(dirpath, file)
convert_line_endings(csPath)
if __name__ == "__main__":
main()
<commit_msg>[trunk] Convert line endings for .h, .c and .cpp files as well as .cs<commit_after>
|
#!/usr/bin/python
import os
import sys
def convert_line_endings(file):
if '\r\n' in open(file, 'rb').read():
print '%s contains DOS line endings. Converting' % file
with open(file, 'rb') as infile:
text = infile.read()
text = text.replace('\r\n', '\n')
with open(file, 'wb') as outfile:
outfile.write(text)
def processPath(dirPath, ext):
for dirpath, dirnames, filenames in os.walk(dirPath):
for file in filenames:
if os.path.splitext(file)[1] == ext:
csPath = os.path.join(dirpath, file)
convert_line_endings(csPath)
if __name__ == "__main__":
if len(sys.argv) > 1:
convert_line_endings(sys.argv[1])
return
processPath('.', '.cs')
processPath('testpackages', '.h')
processPath('testpackages', '.c')
processPath('testpackages', '.cpp')
|
#!/usr/bin/python
import os
import sys
def convert_line_endings(file):
if '\r\n' in open(file, 'rb').read():
print '%s contains DOS line endings. Converting' % file
with open(file, 'rb') as infile:
text = infile.read()
text = text.replace('\r\n', '\n')
with open(file, 'wb') as outfile:
outfile.write(text)
def main():
if len(sys.argv) > 1:
convert_line_endings(sys.argv[1])
return
for dirpath, dirnames, filenames in os.walk('.'):
for file in filenames:
if os.path.splitext(file)[1] == '.cs':
csPath = os.path.join(dirpath, file)
convert_line_endings(csPath)
if __name__ == "__main__":
main()
[trunk] Convert line endings for .h, .c and .cpp files as well as .cs#!/usr/bin/python
import os
import sys
def convert_line_endings(file):
if '\r\n' in open(file, 'rb').read():
print '%s contains DOS line endings. Converting' % file
with open(file, 'rb') as infile:
text = infile.read()
text = text.replace('\r\n', '\n')
with open(file, 'wb') as outfile:
outfile.write(text)
def processPath(dirPath, ext):
for dirpath, dirnames, filenames in os.walk(dirPath):
for file in filenames:
if os.path.splitext(file)[1] == ext:
csPath = os.path.join(dirpath, file)
convert_line_endings(csPath)
if __name__ == "__main__":
if len(sys.argv) > 1:
convert_line_endings(sys.argv[1])
return
processPath('.', '.cs')
processPath('testpackages', '.h')
processPath('testpackages', '.c')
processPath('testpackages', '.cpp')
|
<commit_before>#!/usr/bin/python
import os
import sys
def convert_line_endings(file):
if '\r\n' in open(file, 'rb').read():
print '%s contains DOS line endings. Converting' % file
with open(file, 'rb') as infile:
text = infile.read()
text = text.replace('\r\n', '\n')
with open(file, 'wb') as outfile:
outfile.write(text)
def main():
if len(sys.argv) > 1:
convert_line_endings(sys.argv[1])
return
for dirpath, dirnames, filenames in os.walk('.'):
for file in filenames:
if os.path.splitext(file)[1] == '.cs':
csPath = os.path.join(dirpath, file)
convert_line_endings(csPath)
if __name__ == "__main__":
main()
<commit_msg>[trunk] Convert line endings for .h, .c and .cpp files as well as .cs<commit_after>#!/usr/bin/python
import os
import sys
def convert_line_endings(file):
if '\r\n' in open(file, 'rb').read():
print '%s contains DOS line endings. Converting' % file
with open(file, 'rb') as infile:
text = infile.read()
text = text.replace('\r\n', '\n')
with open(file, 'wb') as outfile:
outfile.write(text)
def processPath(dirPath, ext):
for dirpath, dirnames, filenames in os.walk(dirPath):
for file in filenames:
if os.path.splitext(file)[1] == ext:
csPath = os.path.join(dirpath, file)
convert_line_endings(csPath)
if __name__ == "__main__":
if len(sys.argv) > 1:
convert_line_endings(sys.argv[1])
return
processPath('.', '.cs')
processPath('testpackages', '.h')
processPath('testpackages', '.c')
processPath('testpackages', '.cpp')
|
ef0a6968dedad74ddd40bd4ae81595be6092f24f
|
wrapper/__init__.py
|
wrapper/__init__.py
|
__version__ = '2.2.0'
from libsbol import *
import unit_tests
|
from __future__ import absolute_import
__version__ = '2.2.0'
from sbol.libsbol import *
import sbol.unit_tests
|
Fix import issue with Python 3.6/Support future Python by forcing absolute import
|
Fix import issue with Python 3.6/Support future Python by forcing absolute import
|
Python
|
apache-2.0
|
SynBioDex/libSBOL,SynBioDex/libSBOL,SynBioDex/libSBOL,SynBioDex/libSBOL
|
__version__ = '2.2.0'
from libsbol import *
import unit_testsFix import issue with Python 3.6/Support future Python by forcing absolute import
|
from __future__ import absolute_import
__version__ = '2.2.0'
from sbol.libsbol import *
import sbol.unit_tests
|
<commit_before>__version__ = '2.2.0'
from libsbol import *
import unit_tests<commit_msg>Fix import issue with Python 3.6/Support future Python by forcing absolute import<commit_after>
|
from __future__ import absolute_import
__version__ = '2.2.0'
from sbol.libsbol import *
import sbol.unit_tests
|
__version__ = '2.2.0'
from libsbol import *
import unit_testsFix import issue with Python 3.6/Support future Python by forcing absolute importfrom __future__ import absolute_import
__version__ = '2.2.0'
from sbol.libsbol import *
import sbol.unit_tests
|
<commit_before>__version__ = '2.2.0'
from libsbol import *
import unit_tests<commit_msg>Fix import issue with Python 3.6/Support future Python by forcing absolute import<commit_after>from __future__ import absolute_import
__version__ = '2.2.0'
from sbol.libsbol import *
import sbol.unit_tests
|
1403882c74850804e2c87cb359e21715610c64ef
|
pywinauto/controls/__init__.py
|
pywinauto/controls/__init__.py
|
# GUI Application automation and testing library
# Copyright (C) 2015 Intel Corporation
# Copyright (C) 2009 Mark Mc Mahon
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation; either version 2.1
# of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc.,
# 59 Temple Place,
# Suite 330,
# Boston, MA 02111-1307 USA
"""Controls package"""
from ..sysinfo import UIA_support
if UIA_support:
from . import UIAWrapper # register "uia" back-end (at the end of UIAWrapper module)
from .HwndWrapper import GetDialogPropsFromHandle
from .HwndWrapper import InvalidWindowHandle
# import the control classes - this will register the classes they
# contain
from . import common_controls
from . import win32_controls
from . import uia_controls
from ..base_wrapper import InvalidElement
|
# GUI Application automation and testing library
# Copyright (C) 2015 Intel Corporation
# Copyright (C) 2009 Mark Mc Mahon
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation; either version 2.1
# of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc.,
# 59 Temple Place,
# Suite 330,
# Boston, MA 02111-1307 USA
"""Controls package"""
from ..sysinfo import UIA_support
if UIA_support:
from . import UIAWrapper # register "uia" back-end (at the end of UIAWrapper module)
from . import uia_controls
from .HwndWrapper import GetDialogPropsFromHandle
from .HwndWrapper import InvalidWindowHandle
# import the control classes - this will register the classes they
# contain
from . import common_controls
from . import win32_controls
from ..base_wrapper import InvalidElement
|
Fix uia_controls registration only when UIA is supported
|
Fix uia_controls registration only when UIA is supported
|
Python
|
bsd-3-clause
|
MagazinnikIvan/pywinauto,vasily-v-ryabov/pywinauto,moden-py/pywinauto,cetygamer/pywinauto,airelil/pywinauto,drinkertea/pywinauto,pywinauto/pywinauto,moden-py/pywinauto
|
# GUI Application automation and testing library
# Copyright (C) 2015 Intel Corporation
# Copyright (C) 2009 Mark Mc Mahon
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation; either version 2.1
# of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc.,
# 59 Temple Place,
# Suite 330,
# Boston, MA 02111-1307 USA
"""Controls package"""
from ..sysinfo import UIA_support
if UIA_support:
from . import UIAWrapper # register "uia" back-end (at the end of UIAWrapper module)
from .HwndWrapper import GetDialogPropsFromHandle
from .HwndWrapper import InvalidWindowHandle
# import the control classes - this will register the classes they
# contain
from . import common_controls
from . import win32_controls
from . import uia_controls
from ..base_wrapper import InvalidElement
Fix uia_controls registration only when UIA is supported
|
# GUI Application automation and testing library
# Copyright (C) 2015 Intel Corporation
# Copyright (C) 2009 Mark Mc Mahon
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation; either version 2.1
# of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc.,
# 59 Temple Place,
# Suite 330,
# Boston, MA 02111-1307 USA
"""Controls package"""
from ..sysinfo import UIA_support
if UIA_support:
from . import UIAWrapper # register "uia" back-end (at the end of UIAWrapper module)
from . import uia_controls
from .HwndWrapper import GetDialogPropsFromHandle
from .HwndWrapper import InvalidWindowHandle
# import the control classes - this will register the classes they
# contain
from . import common_controls
from . import win32_controls
from ..base_wrapper import InvalidElement
|
<commit_before># GUI Application automation and testing library
# Copyright (C) 2015 Intel Corporation
# Copyright (C) 2009 Mark Mc Mahon
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation; either version 2.1
# of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc.,
# 59 Temple Place,
# Suite 330,
# Boston, MA 02111-1307 USA
"""Controls package"""
from ..sysinfo import UIA_support
if UIA_support:
from . import UIAWrapper # register "uia" back-end (at the end of UIAWrapper module)
from .HwndWrapper import GetDialogPropsFromHandle
from .HwndWrapper import InvalidWindowHandle
# import the control classes - this will register the classes they
# contain
from . import common_controls
from . import win32_controls
from . import uia_controls
from ..base_wrapper import InvalidElement
<commit_msg>Fix uia_controls registration only when UIA is supported<commit_after>
|
# GUI Application automation and testing library
# Copyright (C) 2015 Intel Corporation
# Copyright (C) 2009 Mark Mc Mahon
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation; either version 2.1
# of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc.,
# 59 Temple Place,
# Suite 330,
# Boston, MA 02111-1307 USA
"""Controls package"""
from ..sysinfo import UIA_support
if UIA_support:
from . import UIAWrapper # register "uia" back-end (at the end of UIAWrapper module)
from . import uia_controls
from .HwndWrapper import GetDialogPropsFromHandle
from .HwndWrapper import InvalidWindowHandle
# import the control classes - this will register the classes they
# contain
from . import common_controls
from . import win32_controls
from ..base_wrapper import InvalidElement
|
# GUI Application automation and testing library
# Copyright (C) 2015 Intel Corporation
# Copyright (C) 2009 Mark Mc Mahon
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation; either version 2.1
# of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc.,
# 59 Temple Place,
# Suite 330,
# Boston, MA 02111-1307 USA
"""Controls package"""
from ..sysinfo import UIA_support
if UIA_support:
from . import UIAWrapper # register "uia" back-end (at the end of UIAWrapper module)
from .HwndWrapper import GetDialogPropsFromHandle
from .HwndWrapper import InvalidWindowHandle
# import the control classes - this will register the classes they
# contain
from . import common_controls
from . import win32_controls
from . import uia_controls
from ..base_wrapper import InvalidElement
Fix uia_controls registration only when UIA is supported# GUI Application automation and testing library
# Copyright (C) 2015 Intel Corporation
# Copyright (C) 2009 Mark Mc Mahon
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation; either version 2.1
# of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc.,
# 59 Temple Place,
# Suite 330,
# Boston, MA 02111-1307 USA
"""Controls package"""
from ..sysinfo import UIA_support
if UIA_support:
from . import UIAWrapper # register "uia" back-end (at the end of UIAWrapper module)
from . import uia_controls
from .HwndWrapper import GetDialogPropsFromHandle
from .HwndWrapper import InvalidWindowHandle
# import the control classes - this will register the classes they
# contain
from . import common_controls
from . import win32_controls
from ..base_wrapper import InvalidElement
|
<commit_before># GUI Application automation and testing library
# Copyright (C) 2015 Intel Corporation
# Copyright (C) 2009 Mark Mc Mahon
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation; either version 2.1
# of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc.,
# 59 Temple Place,
# Suite 330,
# Boston, MA 02111-1307 USA
"""Controls package"""
from ..sysinfo import UIA_support
if UIA_support:
from . import UIAWrapper # register "uia" back-end (at the end of UIAWrapper module)
from .HwndWrapper import GetDialogPropsFromHandle
from .HwndWrapper import InvalidWindowHandle
# import the control classes - this will register the classes they
# contain
from . import common_controls
from . import win32_controls
from . import uia_controls
from ..base_wrapper import InvalidElement
<commit_msg>Fix uia_controls registration only when UIA is supported<commit_after># GUI Application automation and testing library
# Copyright (C) 2015 Intel Corporation
# Copyright (C) 2009 Mark Mc Mahon
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation; either version 2.1
# of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc.,
# 59 Temple Place,
# Suite 330,
# Boston, MA 02111-1307 USA
"""Controls package"""
from ..sysinfo import UIA_support
if UIA_support:
from . import UIAWrapper # register "uia" back-end (at the end of UIAWrapper module)
from . import uia_controls
from .HwndWrapper import GetDialogPropsFromHandle
from .HwndWrapper import InvalidWindowHandle
# import the control classes - this will register the classes they
# contain
from . import common_controls
from . import win32_controls
from ..base_wrapper import InvalidElement
|
c2d1621e089b10418785e173145fb16b0759df1a
|
lib/jasy/core/Info.py
|
lib/jasy/core/Info.py
|
#
# Jasy - JavaScript Tooling Refined
# Copyright 2010 Sebastian Werner
#
import os, sys
def root():
""" Returns the root path of Jasy """
return os.path.normpath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, os.pardir))
def cldrData(what):
return os.path.join(root(), "data", "cldr", what)
def localeProject(locale):
return os.path.join(root(), "data", "jslocale", locale)
def coreProject():
return os.path.join(root(), "data", "jscore")
|
#
# Jasy - JavaScript Tooling Refined
# Copyright 2010 Sebastian Werner
#
import os, sys
def root():
""" Returns the root path of Jasy """
return os.path.relpath(os.path.normpath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, os.pardir)))
return os.path.normpath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, os.pardir))
def cldrData(what):
return os.path.join(root(), "data", "cldr", what)
def localeProject(locale):
return os.path.join(root(), "data", "jslocale", locale)
def coreProject():
return os.path.join(root(), "data", "jscore")
|
Reduce path to shortest possible from current dir.
|
Reduce path to shortest possible from current dir.
|
Python
|
mit
|
zynga/jasy,sebastian-software/jasy,zynga/jasy,sebastian-software/jasy
|
#
# Jasy - JavaScript Tooling Refined
# Copyright 2010 Sebastian Werner
#
import os, sys
def root():
""" Returns the root path of Jasy """
return os.path.normpath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, os.pardir))
def cldrData(what):
return os.path.join(root(), "data", "cldr", what)
def localeProject(locale):
return os.path.join(root(), "data", "jslocale", locale)
def coreProject():
return os.path.join(root(), "data", "jscore")
Reduce path to shortest possible from current dir.
|
#
# Jasy - JavaScript Tooling Refined
# Copyright 2010 Sebastian Werner
#
import os, sys
def root():
""" Returns the root path of Jasy """
return os.path.relpath(os.path.normpath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, os.pardir)))
return os.path.normpath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, os.pardir))
def cldrData(what):
return os.path.join(root(), "data", "cldr", what)
def localeProject(locale):
return os.path.join(root(), "data", "jslocale", locale)
def coreProject():
return os.path.join(root(), "data", "jscore")
|
<commit_before>#
# Jasy - JavaScript Tooling Refined
# Copyright 2010 Sebastian Werner
#
import os, sys
def root():
""" Returns the root path of Jasy """
return os.path.normpath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, os.pardir))
def cldrData(what):
return os.path.join(root(), "data", "cldr", what)
def localeProject(locale):
return os.path.join(root(), "data", "jslocale", locale)
def coreProject():
return os.path.join(root(), "data", "jscore")
<commit_msg>Reduce path to shortest possible from current dir.<commit_after>
|
#
# Jasy - JavaScript Tooling Refined
# Copyright 2010 Sebastian Werner
#
import os, sys
def root():
""" Returns the root path of Jasy """
return os.path.relpath(os.path.normpath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, os.pardir)))
return os.path.normpath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, os.pardir))
def cldrData(what):
return os.path.join(root(), "data", "cldr", what)
def localeProject(locale):
return os.path.join(root(), "data", "jslocale", locale)
def coreProject():
return os.path.join(root(), "data", "jscore")
|
#
# Jasy - JavaScript Tooling Refined
# Copyright 2010 Sebastian Werner
#
import os, sys
def root():
""" Returns the root path of Jasy """
return os.path.normpath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, os.pardir))
def cldrData(what):
return os.path.join(root(), "data", "cldr", what)
def localeProject(locale):
return os.path.join(root(), "data", "jslocale", locale)
def coreProject():
return os.path.join(root(), "data", "jscore")
Reduce path to shortest possible from current dir.#
# Jasy - JavaScript Tooling Refined
# Copyright 2010 Sebastian Werner
#
import os, sys
def root():
""" Returns the root path of Jasy """
return os.path.relpath(os.path.normpath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, os.pardir)))
return os.path.normpath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, os.pardir))
def cldrData(what):
return os.path.join(root(), "data", "cldr", what)
def localeProject(locale):
return os.path.join(root(), "data", "jslocale", locale)
def coreProject():
return os.path.join(root(), "data", "jscore")
|
<commit_before>#
# Jasy - JavaScript Tooling Refined
# Copyright 2010 Sebastian Werner
#
import os, sys
def root():
""" Returns the root path of Jasy """
return os.path.normpath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, os.pardir))
def cldrData(what):
return os.path.join(root(), "data", "cldr", what)
def localeProject(locale):
return os.path.join(root(), "data", "jslocale", locale)
def coreProject():
return os.path.join(root(), "data", "jscore")
<commit_msg>Reduce path to shortest possible from current dir.<commit_after>#
# Jasy - JavaScript Tooling Refined
# Copyright 2010 Sebastian Werner
#
import os, sys
def root():
""" Returns the root path of Jasy """
return os.path.relpath(os.path.normpath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, os.pardir)))
return os.path.normpath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, os.pardir))
def cldrData(what):
return os.path.join(root(), "data", "cldr", what)
def localeProject(locale):
return os.path.join(root(), "data", "jslocale", locale)
def coreProject():
return os.path.join(root(), "data", "jscore")
|
8d85db01b7582aa93c3b9871cb199277fae87d53
|
remote-scripts/BVT-VERIFY-HOSTNAME.py
|
remote-scripts/BVT-VERIFY-HOSTNAME.py
|
#!/usr/bin/python
from azuremodules import *
import argparse
import sys
import time
#for error checking
parser = argparse.ArgumentParser()
parser.add_argument('-e', '--expected', help='specify expected hostname', required=True)
args = parser.parse_args()
#if no value specified then stop
expectedHostname = args.expected
def RunTest(expectedHost):
UpdateState("TestRunning")
RunLog.info("Checking hostname...")
temp = Run("hostname")
output = temp
if (expectedHost in output) :
RunLog.info('Hostname is set successfully to %s' %expectedHost)
ResultLog.info('PASS')
UpdateState("TestCompleted")
else :
RunLog.error('Hostname change failed. Current hostname : %s Expected hostname : %s' % (output, expectedHost))
ResultLog.error('FAIL')
UpdateState("TestCompleted")
RunTest(expectedHostname)
|
#!/usr/bin/python
from azuremodules import *
import argparse
import sys
import time
import re
#for error checking
parser = argparse.ArgumentParser()
parser.add_argument('-e', '--expected', help='specify expected hostname', required=True)
args = parser.parse_args()
#if no value specified then stop
expectedHostname = args.expected
def RunTest(expectedHost):
UpdateState("TestRunning")
if CheckHostName(expectedHost) and CheckFQDN(expectedHost):
ResultLog.info('PASS')
UpdateState("TestCompleted")
else:
ResultLog.error('FAIL')
UpdateState("TestCompleted")
def CheckHostName(expectedHost):
RunLog.info("Checking hostname...")
output = Run("hostname")
if expectedHost in output:
RunLog.info('Hostname is set successfully to {0}'.format(expectedHost))
return True
else:
RunLog.error('Hostname change failed. Current hostname : {0} Expected hostname : {1}'.format(output, expectedHost))
return False
def CheckFQDN(expectedHost):
RunLog.info("Checking fqdn...")
[current_distro, distro_version] = DetectDistro()
nslookupCmd = "nslookup {0}".format(expectedHost)
if current_distro == 'coreos':
nslookupCmd = "python nslookup.py -n {0}".format(expectedHost)
output = Run(nslookupCmd)
if re.search("server can't find", output) is None:
RunLog.info('nslookup successfully for: {0}'.format(expectedHost))
return True
else:
RunLog.error("nslookup failed for: {0}, {1}".format(expectedHost, output))
return False
RunTest(expectedHostname)
|
Add fqdn verification to BVT
|
Add fqdn verification to BVT
|
Python
|
apache-2.0
|
FreeBSDonHyper-V/azure-freebsd-automation,v-sirebb/azure-linux-automation,konkasoftci/azure-linux-automation,Nidylei/azure-linux-automation,Nidylei/azure-linux-automation,hglkrijger/azure-linux-automation,v-sirebb/azure-linux-automation,v-sirebb/azure-linux-automation,iamshital/azure-linux-automation,konkasoftci/azure-linux-automation,iamshital/azure-linux-automation,FreeBSDonHyper-V/azure-freebsd-automation,konkasoftci/azure-linux-automation,hglkrijger/azure-linux-automation,Nidylei/azure-linux-automation,hglkrijger/azure-linux-automation,FreeBSDonHyper-V/azure-freebsd-automation,iamshital/azure-linux-automation
|
#!/usr/bin/python
from azuremodules import *
import argparse
import sys
import time
#for error checking
parser = argparse.ArgumentParser()
parser.add_argument('-e', '--expected', help='specify expected hostname', required=True)
args = parser.parse_args()
#if no value specified then stop
expectedHostname = args.expected
def RunTest(expectedHost):
UpdateState("TestRunning")
RunLog.info("Checking hostname...")
temp = Run("hostname")
output = temp
if (expectedHost in output) :
RunLog.info('Hostname is set successfully to %s' %expectedHost)
ResultLog.info('PASS')
UpdateState("TestCompleted")
else :
RunLog.error('Hostname change failed. Current hostname : %s Expected hostname : %s' % (output, expectedHost))
ResultLog.error('FAIL')
UpdateState("TestCompleted")
RunTest(expectedHostname)Add fqdn verification to BVT
|
#!/usr/bin/python
from azuremodules import *
import argparse
import sys
import time
import re
#for error checking
parser = argparse.ArgumentParser()
parser.add_argument('-e', '--expected', help='specify expected hostname', required=True)
args = parser.parse_args()
#if no value specified then stop
expectedHostname = args.expected
def RunTest(expectedHost):
UpdateState("TestRunning")
if CheckHostName(expectedHost) and CheckFQDN(expectedHost):
ResultLog.info('PASS')
UpdateState("TestCompleted")
else:
ResultLog.error('FAIL')
UpdateState("TestCompleted")
def CheckHostName(expectedHost):
RunLog.info("Checking hostname...")
output = Run("hostname")
if expectedHost in output:
RunLog.info('Hostname is set successfully to {0}'.format(expectedHost))
return True
else:
RunLog.error('Hostname change failed. Current hostname : {0} Expected hostname : {1}'.format(output, expectedHost))
return False
def CheckFQDN(expectedHost):
RunLog.info("Checking fqdn...")
[current_distro, distro_version] = DetectDistro()
nslookupCmd = "nslookup {0}".format(expectedHost)
if current_distro == 'coreos':
nslookupCmd = "python nslookup.py -n {0}".format(expectedHost)
output = Run(nslookupCmd)
if re.search("server can't find", output) is None:
RunLog.info('nslookup successfully for: {0}'.format(expectedHost))
return True
else:
RunLog.error("nslookup failed for: {0}, {1}".format(expectedHost, output))
return False
RunTest(expectedHostname)
|
<commit_before>#!/usr/bin/python
from azuremodules import *
import argparse
import sys
import time
#for error checking
parser = argparse.ArgumentParser()
parser.add_argument('-e', '--expected', help='specify expected hostname', required=True)
args = parser.parse_args()
#if no value specified then stop
expectedHostname = args.expected
def RunTest(expectedHost):
UpdateState("TestRunning")
RunLog.info("Checking hostname...")
temp = Run("hostname")
output = temp
if (expectedHost in output) :
RunLog.info('Hostname is set successfully to %s' %expectedHost)
ResultLog.info('PASS')
UpdateState("TestCompleted")
else :
RunLog.error('Hostname change failed. Current hostname : %s Expected hostname : %s' % (output, expectedHost))
ResultLog.error('FAIL')
UpdateState("TestCompleted")
RunTest(expectedHostname)<commit_msg>Add fqdn verification to BVT<commit_after>
|
#!/usr/bin/python
from azuremodules import *
import argparse
import sys
import time
import re
#for error checking
parser = argparse.ArgumentParser()
parser.add_argument('-e', '--expected', help='specify expected hostname', required=True)
args = parser.parse_args()
#if no value specified then stop
expectedHostname = args.expected
def RunTest(expectedHost):
UpdateState("TestRunning")
if CheckHostName(expectedHost) and CheckFQDN(expectedHost):
ResultLog.info('PASS')
UpdateState("TestCompleted")
else:
ResultLog.error('FAIL')
UpdateState("TestCompleted")
def CheckHostName(expectedHost):
RunLog.info("Checking hostname...")
output = Run("hostname")
if expectedHost in output:
RunLog.info('Hostname is set successfully to {0}'.format(expectedHost))
return True
else:
RunLog.error('Hostname change failed. Current hostname : {0} Expected hostname : {1}'.format(output, expectedHost))
return False
def CheckFQDN(expectedHost):
RunLog.info("Checking fqdn...")
[current_distro, distro_version] = DetectDistro()
nslookupCmd = "nslookup {0}".format(expectedHost)
if current_distro == 'coreos':
nslookupCmd = "python nslookup.py -n {0}".format(expectedHost)
output = Run(nslookupCmd)
if re.search("server can't find", output) is None:
RunLog.info('nslookup successfully for: {0}'.format(expectedHost))
return True
else:
RunLog.error("nslookup failed for: {0}, {1}".format(expectedHost, output))
return False
RunTest(expectedHostname)
|
#!/usr/bin/python
from azuremodules import *
import argparse
import sys
import time
#for error checking
parser = argparse.ArgumentParser()
parser.add_argument('-e', '--expected', help='specify expected hostname', required=True)
args = parser.parse_args()
#if no value specified then stop
expectedHostname = args.expected
def RunTest(expectedHost):
UpdateState("TestRunning")
RunLog.info("Checking hostname...")
temp = Run("hostname")
output = temp
if (expectedHost in output) :
RunLog.info('Hostname is set successfully to %s' %expectedHost)
ResultLog.info('PASS')
UpdateState("TestCompleted")
else :
RunLog.error('Hostname change failed. Current hostname : %s Expected hostname : %s' % (output, expectedHost))
ResultLog.error('FAIL')
UpdateState("TestCompleted")
RunTest(expectedHostname)Add fqdn verification to BVT#!/usr/bin/python
from azuremodules import *
import argparse
import sys
import time
import re
#for error checking
parser = argparse.ArgumentParser()
parser.add_argument('-e', '--expected', help='specify expected hostname', required=True)
args = parser.parse_args()
#if no value specified then stop
expectedHostname = args.expected
def RunTest(expectedHost):
UpdateState("TestRunning")
if CheckHostName(expectedHost) and CheckFQDN(expectedHost):
ResultLog.info('PASS')
UpdateState("TestCompleted")
else:
ResultLog.error('FAIL')
UpdateState("TestCompleted")
def CheckHostName(expectedHost):
RunLog.info("Checking hostname...")
output = Run("hostname")
if expectedHost in output:
RunLog.info('Hostname is set successfully to {0}'.format(expectedHost))
return True
else:
RunLog.error('Hostname change failed. Current hostname : {0} Expected hostname : {1}'.format(output, expectedHost))
return False
def CheckFQDN(expectedHost):
RunLog.info("Checking fqdn...")
[current_distro, distro_version] = DetectDistro()
nslookupCmd = "nslookup {0}".format(expectedHost)
if current_distro == 'coreos':
nslookupCmd = "python nslookup.py -n {0}".format(expectedHost)
output = Run(nslookupCmd)
if re.search("server can't find", output) is None:
RunLog.info('nslookup successfully for: {0}'.format(expectedHost))
return True
else:
RunLog.error("nslookup failed for: {0}, {1}".format(expectedHost, output))
return False
RunTest(expectedHostname)
|
<commit_before>#!/usr/bin/python
from azuremodules import *
import argparse
import sys
import time
#for error checking
parser = argparse.ArgumentParser()
parser.add_argument('-e', '--expected', help='specify expected hostname', required=True)
args = parser.parse_args()
#if no value specified then stop
expectedHostname = args.expected
def RunTest(expectedHost):
UpdateState("TestRunning")
RunLog.info("Checking hostname...")
temp = Run("hostname")
output = temp
if (expectedHost in output) :
RunLog.info('Hostname is set successfully to %s' %expectedHost)
ResultLog.info('PASS')
UpdateState("TestCompleted")
else :
RunLog.error('Hostname change failed. Current hostname : %s Expected hostname : %s' % (output, expectedHost))
ResultLog.error('FAIL')
UpdateState("TestCompleted")
RunTest(expectedHostname)<commit_msg>Add fqdn verification to BVT<commit_after>#!/usr/bin/python
from azuremodules import *
import argparse
import sys
import time
import re
#for error checking
parser = argparse.ArgumentParser()
parser.add_argument('-e', '--expected', help='specify expected hostname', required=True)
args = parser.parse_args()
#if no value specified then stop
expectedHostname = args.expected
def RunTest(expectedHost):
UpdateState("TestRunning")
if CheckHostName(expectedHost) and CheckFQDN(expectedHost):
ResultLog.info('PASS')
UpdateState("TestCompleted")
else:
ResultLog.error('FAIL')
UpdateState("TestCompleted")
def CheckHostName(expectedHost):
RunLog.info("Checking hostname...")
output = Run("hostname")
if expectedHost in output:
RunLog.info('Hostname is set successfully to {0}'.format(expectedHost))
return True
else:
RunLog.error('Hostname change failed. Current hostname : {0} Expected hostname : {1}'.format(output, expectedHost))
return False
def CheckFQDN(expectedHost):
RunLog.info("Checking fqdn...")
[current_distro, distro_version] = DetectDistro()
nslookupCmd = "nslookup {0}".format(expectedHost)
if current_distro == 'coreos':
nslookupCmd = "python nslookup.py -n {0}".format(expectedHost)
output = Run(nslookupCmd)
if re.search("server can't find", output) is None:
RunLog.info('nslookup successfully for: {0}'.format(expectedHost))
return True
else:
RunLog.error("nslookup failed for: {0}, {1}".format(expectedHost, output))
return False
RunTest(expectedHostname)
|
707cb1aca7c37ece417e070f5d22146c1f36ab10
|
modules/botModule.py
|
modules/botModule.py
|
from tinydb import TinyDB, Query
class BotModule:
name = '' # name of your module
description = '' # description of its function
help_text = '' # help text for explaining how to do things
trigger_string = '' # string to listen for as trigger
has_background_loop = False
listen_for_reaction = False
loaded_modules = []
admin_modules = [370934086111330308, 372729159933362177]
trigger_char = '!' # char preceding trigger string
module_version = '0.0.0'
def __init__(self):
self.module_db = TinyDB('./modules/databases/' + self.name)
async def parse_command(self, message, client):
raise NotImplementedError("Parse function not implemented in module:" + self.name)
async def background_loop(self, client):
raise NotImplementedError("background_loop function not implemented in module:" + self.name)
async def on_reaction_add(self, reaction, client, user):
raise NotImplementedError("on_reaction_add function not implemented in module:" + self.name)
async def on_reaction_remove(self, reaction, client, user):
raise NotImplementedError("on_reaction_remove function not implemented in module:" + self.name)
|
from tinydb import TinyDB, Query
class BotModule:
name = '' # name of your module
description = '' # description of its function
help_text = '' # help text for explaining how to do things
trigger_string = '' # string to listen for as trigger
has_background_loop = False
listen_for_reaction = False
loaded_modules = []
admin_modules = ['370934086111330308', '372729159933362177']
trigger_char = '!' # char preceding trigger string
module_version = '0.0.0'
def __init__(self):
self.module_db = TinyDB('./modules/databases/' + self.name)
async def parse_command(self, message, client):
raise NotImplementedError("Parse function not implemented in module:" + self.name)
async def background_loop(self, client):
raise NotImplementedError("background_loop function not implemented in module:" + self.name)
async def on_reaction_add(self, reaction, client, user):
raise NotImplementedError("on_reaction_add function not implemented in module:" + self.name)
async def on_reaction_remove(self, reaction, client, user):
raise NotImplementedError("on_reaction_remove function not implemented in module:" + self.name)
|
Fix bug in admin_module checking
|
Fix bug in admin_module checking
|
Python
|
mit
|
suclearnub/scubot
|
from tinydb import TinyDB, Query
class BotModule:
name = '' # name of your module
description = '' # description of its function
help_text = '' # help text for explaining how to do things
trigger_string = '' # string to listen for as trigger
has_background_loop = False
listen_for_reaction = False
loaded_modules = []
admin_modules = [370934086111330308, 372729159933362177]
trigger_char = '!' # char preceding trigger string
module_version = '0.0.0'
def __init__(self):
self.module_db = TinyDB('./modules/databases/' + self.name)
async def parse_command(self, message, client):
raise NotImplementedError("Parse function not implemented in module:" + self.name)
async def background_loop(self, client):
raise NotImplementedError("background_loop function not implemented in module:" + self.name)
async def on_reaction_add(self, reaction, client, user):
raise NotImplementedError("on_reaction_add function not implemented in module:" + self.name)
async def on_reaction_remove(self, reaction, client, user):
raise NotImplementedError("on_reaction_remove function not implemented in module:" + self.name)
Fix bug in admin_module checking
|
from tinydb import TinyDB, Query
class BotModule:
name = '' # name of your module
description = '' # description of its function
help_text = '' # help text for explaining how to do things
trigger_string = '' # string to listen for as trigger
has_background_loop = False
listen_for_reaction = False
loaded_modules = []
admin_modules = ['370934086111330308', '372729159933362177']
trigger_char = '!' # char preceding trigger string
module_version = '0.0.0'
def __init__(self):
self.module_db = TinyDB('./modules/databases/' + self.name)
async def parse_command(self, message, client):
raise NotImplementedError("Parse function not implemented in module:" + self.name)
async def background_loop(self, client):
raise NotImplementedError("background_loop function not implemented in module:" + self.name)
async def on_reaction_add(self, reaction, client, user):
raise NotImplementedError("on_reaction_add function not implemented in module:" + self.name)
async def on_reaction_remove(self, reaction, client, user):
raise NotImplementedError("on_reaction_remove function not implemented in module:" + self.name)
|
<commit_before>from tinydb import TinyDB, Query
class BotModule:
name = '' # name of your module
description = '' # description of its function
help_text = '' # help text for explaining how to do things
trigger_string = '' # string to listen for as trigger
has_background_loop = False
listen_for_reaction = False
loaded_modules = []
admin_modules = [370934086111330308, 372729159933362177]
trigger_char = '!' # char preceding trigger string
module_version = '0.0.0'
def __init__(self):
self.module_db = TinyDB('./modules/databases/' + self.name)
async def parse_command(self, message, client):
raise NotImplementedError("Parse function not implemented in module:" + self.name)
async def background_loop(self, client):
raise NotImplementedError("background_loop function not implemented in module:" + self.name)
async def on_reaction_add(self, reaction, client, user):
raise NotImplementedError("on_reaction_add function not implemented in module:" + self.name)
async def on_reaction_remove(self, reaction, client, user):
raise NotImplementedError("on_reaction_remove function not implemented in module:" + self.name)
<commit_msg>Fix bug in admin_module checking<commit_after>
|
from tinydb import TinyDB, Query
class BotModule:
name = '' # name of your module
description = '' # description of its function
help_text = '' # help text for explaining how to do things
trigger_string = '' # string to listen for as trigger
has_background_loop = False
listen_for_reaction = False
loaded_modules = []
admin_modules = ['370934086111330308', '372729159933362177']
trigger_char = '!' # char preceding trigger string
module_version = '0.0.0'
def __init__(self):
self.module_db = TinyDB('./modules/databases/' + self.name)
async def parse_command(self, message, client):
raise NotImplementedError("Parse function not implemented in module:" + self.name)
async def background_loop(self, client):
raise NotImplementedError("background_loop function not implemented in module:" + self.name)
async def on_reaction_add(self, reaction, client, user):
raise NotImplementedError("on_reaction_add function not implemented in module:" + self.name)
async def on_reaction_remove(self, reaction, client, user):
raise NotImplementedError("on_reaction_remove function not implemented in module:" + self.name)
|
from tinydb import TinyDB, Query
class BotModule:
name = '' # name of your module
description = '' # description of its function
help_text = '' # help text for explaining how to do things
trigger_string = '' # string to listen for as trigger
has_background_loop = False
listen_for_reaction = False
loaded_modules = []
admin_modules = [370934086111330308, 372729159933362177]
trigger_char = '!' # char preceding trigger string
module_version = '0.0.0'
def __init__(self):
self.module_db = TinyDB('./modules/databases/' + self.name)
async def parse_command(self, message, client):
raise NotImplementedError("Parse function not implemented in module:" + self.name)
async def background_loop(self, client):
raise NotImplementedError("background_loop function not implemented in module:" + self.name)
async def on_reaction_add(self, reaction, client, user):
raise NotImplementedError("on_reaction_add function not implemented in module:" + self.name)
async def on_reaction_remove(self, reaction, client, user):
raise NotImplementedError("on_reaction_remove function not implemented in module:" + self.name)
Fix bug in admin_module checkingfrom tinydb import TinyDB, Query
class BotModule:
name = '' # name of your module
description = '' # description of its function
help_text = '' # help text for explaining how to do things
trigger_string = '' # string to listen for as trigger
has_background_loop = False
listen_for_reaction = False
loaded_modules = []
admin_modules = ['370934086111330308', '372729159933362177']
trigger_char = '!' # char preceding trigger string
module_version = '0.0.0'
def __init__(self):
self.module_db = TinyDB('./modules/databases/' + self.name)
async def parse_command(self, message, client):
raise NotImplementedError("Parse function not implemented in module:" + self.name)
async def background_loop(self, client):
raise NotImplementedError("background_loop function not implemented in module:" + self.name)
async def on_reaction_add(self, reaction, client, user):
raise NotImplementedError("on_reaction_add function not implemented in module:" + self.name)
async def on_reaction_remove(self, reaction, client, user):
raise NotImplementedError("on_reaction_remove function not implemented in module:" + self.name)
|
<commit_before>from tinydb import TinyDB, Query
class BotModule:
name = '' # name of your module
description = '' # description of its function
help_text = '' # help text for explaining how to do things
trigger_string = '' # string to listen for as trigger
has_background_loop = False
listen_for_reaction = False
loaded_modules = []
admin_modules = [370934086111330308, 372729159933362177]
trigger_char = '!' # char preceding trigger string
module_version = '0.0.0'
def __init__(self):
self.module_db = TinyDB('./modules/databases/' + self.name)
async def parse_command(self, message, client):
raise NotImplementedError("Parse function not implemented in module:" + self.name)
async def background_loop(self, client):
raise NotImplementedError("background_loop function not implemented in module:" + self.name)
async def on_reaction_add(self, reaction, client, user):
raise NotImplementedError("on_reaction_add function not implemented in module:" + self.name)
async def on_reaction_remove(self, reaction, client, user):
raise NotImplementedError("on_reaction_remove function not implemented in module:" + self.name)
<commit_msg>Fix bug in admin_module checking<commit_after>from tinydb import TinyDB, Query
class BotModule:
name = '' # name of your module
description = '' # description of its function
help_text = '' # help text for explaining how to do things
trigger_string = '' # string to listen for as trigger
has_background_loop = False
listen_for_reaction = False
loaded_modules = []
admin_modules = ['370934086111330308', '372729159933362177']
trigger_char = '!' # char preceding trigger string
module_version = '0.0.0'
def __init__(self):
self.module_db = TinyDB('./modules/databases/' + self.name)
async def parse_command(self, message, client):
raise NotImplementedError("Parse function not implemented in module:" + self.name)
async def background_loop(self, client):
raise NotImplementedError("background_loop function not implemented in module:" + self.name)
async def on_reaction_add(self, reaction, client, user):
raise NotImplementedError("on_reaction_add function not implemented in module:" + self.name)
async def on_reaction_remove(self, reaction, client, user):
raise NotImplementedError("on_reaction_remove function not implemented in module:" + self.name)
|
862f877cdcdef7aa4a853b2cce8eed2d7ba95fdc
|
providers/org/cogprints/apps.py
|
providers/org/cogprints/apps.py
|
from share.provider import OAIProviderAppConfig
class AppConfig(OAIProviderAppConfig):
name = 'providers.org.cogprints'
version = '0.0.1'
title = 'cogprints'
long_title = 'Cognitive Sciences ePrint Archive'
home_page = 'http://www.cogprints.org/'
url = 'http://cogprints.org/cgi/oai2'
|
from share.provider import OAIProviderAppConfig
class AppConfig(OAIProviderAppConfig):
name = 'providers.org.cogprints'
version = '0.0.1'
title = 'cogprints'
long_title = 'Cognitive Sciences ePrint Archive'
home_page = 'http://www.cogprints.org/'
url = 'http://cogprints.org/cgi/oai2'
emitted_type = 'preprint'
|
Update cogprints to emit preprints
|
Update cogprints to emit preprints
|
Python
|
apache-2.0
|
aaxelb/SHARE,CenterForOpenScience/SHARE,CenterForOpenScience/SHARE,zamattiac/SHARE,laurenbarker/SHARE,laurenbarker/SHARE,aaxelb/SHARE,zamattiac/SHARE,aaxelb/SHARE,zamattiac/SHARE,laurenbarker/SHARE,CenterForOpenScience/SHARE
|
from share.provider import OAIProviderAppConfig
class AppConfig(OAIProviderAppConfig):
name = 'providers.org.cogprints'
version = '0.0.1'
title = 'cogprints'
long_title = 'Cognitive Sciences ePrint Archive'
home_page = 'http://www.cogprints.org/'
url = 'http://cogprints.org/cgi/oai2'
Update cogprints to emit preprints
|
from share.provider import OAIProviderAppConfig
class AppConfig(OAIProviderAppConfig):
name = 'providers.org.cogprints'
version = '0.0.1'
title = 'cogprints'
long_title = 'Cognitive Sciences ePrint Archive'
home_page = 'http://www.cogprints.org/'
url = 'http://cogprints.org/cgi/oai2'
emitted_type = 'preprint'
|
<commit_before>from share.provider import OAIProviderAppConfig
class AppConfig(OAIProviderAppConfig):
name = 'providers.org.cogprints'
version = '0.0.1'
title = 'cogprints'
long_title = 'Cognitive Sciences ePrint Archive'
home_page = 'http://www.cogprints.org/'
url = 'http://cogprints.org/cgi/oai2'
<commit_msg>Update cogprints to emit preprints<commit_after>
|
from share.provider import OAIProviderAppConfig
class AppConfig(OAIProviderAppConfig):
name = 'providers.org.cogprints'
version = '0.0.1'
title = 'cogprints'
long_title = 'Cognitive Sciences ePrint Archive'
home_page = 'http://www.cogprints.org/'
url = 'http://cogprints.org/cgi/oai2'
emitted_type = 'preprint'
|
from share.provider import OAIProviderAppConfig
class AppConfig(OAIProviderAppConfig):
name = 'providers.org.cogprints'
version = '0.0.1'
title = 'cogprints'
long_title = 'Cognitive Sciences ePrint Archive'
home_page = 'http://www.cogprints.org/'
url = 'http://cogprints.org/cgi/oai2'
Update cogprints to emit preprintsfrom share.provider import OAIProviderAppConfig
class AppConfig(OAIProviderAppConfig):
name = 'providers.org.cogprints'
version = '0.0.1'
title = 'cogprints'
long_title = 'Cognitive Sciences ePrint Archive'
home_page = 'http://www.cogprints.org/'
url = 'http://cogprints.org/cgi/oai2'
emitted_type = 'preprint'
|
<commit_before>from share.provider import OAIProviderAppConfig
class AppConfig(OAIProviderAppConfig):
name = 'providers.org.cogprints'
version = '0.0.1'
title = 'cogprints'
long_title = 'Cognitive Sciences ePrint Archive'
home_page = 'http://www.cogprints.org/'
url = 'http://cogprints.org/cgi/oai2'
<commit_msg>Update cogprints to emit preprints<commit_after>from share.provider import OAIProviderAppConfig
class AppConfig(OAIProviderAppConfig):
name = 'providers.org.cogprints'
version = '0.0.1'
title = 'cogprints'
long_title = 'Cognitive Sciences ePrint Archive'
home_page = 'http://www.cogprints.org/'
url = 'http://cogprints.org/cgi/oai2'
emitted_type = 'preprint'
|
55fd840b06c5481ff5e3171dba1ef98d973f0747
|
nlppln/wfgenerator.py
|
nlppln/wfgenerator.py
|
from scriptcwl import WorkflowGenerator as WFGenerator
from .utils import CWL_PATH
class WorkflowGenerator(WFGenerator):
def __init__(self):
WFGenerator.__init__(self, steps_dir=CWL_PATH)
def save(self, fname, inline=True, relative=False, validate=True,
encoding='utf-8'):
"""Save workflow to file
For nlppln, the default is to save steps inline.
"""
super(WorkflowGenerator, self).save(fname,
inline=inline,
relative=relative,
validate=validate,
encoding=encoding)
|
from scriptcwl import WorkflowGenerator as WFGenerator
from .utils import CWL_PATH
class WorkflowGenerator(WFGenerator):
def __init__(self, working_dir=None, copy_steps=True):
WFGenerator.__init__(self, steps_dir=CWL_PATH, working_dir=working_dir,
copy_steps=copy_steps)
def save(self, fname, inline=True, relative=False, validate=True,
encoding='utf-8'):
"""Save workflow to file
For nlppln, the default is to save steps inline.
"""
super(WorkflowGenerator, self).save(fname,
inline=inline,
relative=relative,
validate=validate,
encoding=encoding)
|
Add working_dir and copy_steps options
|
Add working_dir and copy_steps options
|
Python
|
apache-2.0
|
WhatWorksWhenForWhom/nlppln,WhatWorksWhenForWhom/nlppln,WhatWorksWhenForWhom/nlppln
|
from scriptcwl import WorkflowGenerator as WFGenerator
from .utils import CWL_PATH
class WorkflowGenerator(WFGenerator):
def __init__(self):
WFGenerator.__init__(self, steps_dir=CWL_PATH)
def save(self, fname, inline=True, relative=False, validate=True,
encoding='utf-8'):
"""Save workflow to file
For nlppln, the default is to save steps inline.
"""
super(WorkflowGenerator, self).save(fname,
inline=inline,
relative=relative,
validate=validate,
encoding=encoding)
Add working_dir and copy_steps options
|
from scriptcwl import WorkflowGenerator as WFGenerator
from .utils import CWL_PATH
class WorkflowGenerator(WFGenerator):
def __init__(self, working_dir=None, copy_steps=True):
WFGenerator.__init__(self, steps_dir=CWL_PATH, working_dir=working_dir,
copy_steps=copy_steps)
def save(self, fname, inline=True, relative=False, validate=True,
encoding='utf-8'):
"""Save workflow to file
For nlppln, the default is to save steps inline.
"""
super(WorkflowGenerator, self).save(fname,
inline=inline,
relative=relative,
validate=validate,
encoding=encoding)
|
<commit_before>from scriptcwl import WorkflowGenerator as WFGenerator
from .utils import CWL_PATH
class WorkflowGenerator(WFGenerator):
def __init__(self):
WFGenerator.__init__(self, steps_dir=CWL_PATH)
def save(self, fname, inline=True, relative=False, validate=True,
encoding='utf-8'):
"""Save workflow to file
For nlppln, the default is to save steps inline.
"""
super(WorkflowGenerator, self).save(fname,
inline=inline,
relative=relative,
validate=validate,
encoding=encoding)
<commit_msg>Add working_dir and copy_steps options<commit_after>
|
from scriptcwl import WorkflowGenerator as WFGenerator
from .utils import CWL_PATH
class WorkflowGenerator(WFGenerator):
def __init__(self, working_dir=None, copy_steps=True):
WFGenerator.__init__(self, steps_dir=CWL_PATH, working_dir=working_dir,
copy_steps=copy_steps)
def save(self, fname, inline=True, relative=False, validate=True,
encoding='utf-8'):
"""Save workflow to file
For nlppln, the default is to save steps inline.
"""
super(WorkflowGenerator, self).save(fname,
inline=inline,
relative=relative,
validate=validate,
encoding=encoding)
|
from scriptcwl import WorkflowGenerator as WFGenerator
from .utils import CWL_PATH
class WorkflowGenerator(WFGenerator):
def __init__(self):
WFGenerator.__init__(self, steps_dir=CWL_PATH)
def save(self, fname, inline=True, relative=False, validate=True,
encoding='utf-8'):
"""Save workflow to file
For nlppln, the default is to save steps inline.
"""
super(WorkflowGenerator, self).save(fname,
inline=inline,
relative=relative,
validate=validate,
encoding=encoding)
Add working_dir and copy_steps optionsfrom scriptcwl import WorkflowGenerator as WFGenerator
from .utils import CWL_PATH
class WorkflowGenerator(WFGenerator):
def __init__(self, working_dir=None, copy_steps=True):
WFGenerator.__init__(self, steps_dir=CWL_PATH, working_dir=working_dir,
copy_steps=copy_steps)
def save(self, fname, inline=True, relative=False, validate=True,
encoding='utf-8'):
"""Save workflow to file
For nlppln, the default is to save steps inline.
"""
super(WorkflowGenerator, self).save(fname,
inline=inline,
relative=relative,
validate=validate,
encoding=encoding)
|
<commit_before>from scriptcwl import WorkflowGenerator as WFGenerator
from .utils import CWL_PATH
class WorkflowGenerator(WFGenerator):
def __init__(self):
WFGenerator.__init__(self, steps_dir=CWL_PATH)
def save(self, fname, inline=True, relative=False, validate=True,
encoding='utf-8'):
"""Save workflow to file
For nlppln, the default is to save steps inline.
"""
super(WorkflowGenerator, self).save(fname,
inline=inline,
relative=relative,
validate=validate,
encoding=encoding)
<commit_msg>Add working_dir and copy_steps options<commit_after>from scriptcwl import WorkflowGenerator as WFGenerator
from .utils import CWL_PATH
class WorkflowGenerator(WFGenerator):
def __init__(self, working_dir=None, copy_steps=True):
WFGenerator.__init__(self, steps_dir=CWL_PATH, working_dir=working_dir,
copy_steps=copy_steps)
def save(self, fname, inline=True, relative=False, validate=True,
encoding='utf-8'):
"""Save workflow to file
For nlppln, the default is to save steps inline.
"""
super(WorkflowGenerator, self).save(fname,
inline=inline,
relative=relative,
validate=validate,
encoding=encoding)
|
f114e5ecf62a5a08c22e1db23e891abe066b61f8
|
oneflow/core/forms.py
|
oneflow/core/forms.py
|
# -*- coding: utf-8 -*-
import logging
#from django import forms
#from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import get_user_model
LOGGER = logging.getLogger(__name__)
User = get_user_model()
class FullUserCreationForm(UserCreationForm):
""" Like the django UserCreationForm,
with optional first_name and last_name,
and email too.
.. note:: the ``username`` field from Django's ``UserCreationForm``
is overriden by our Model's one. Thus the 30 chars limit
doesn't apply.
"""
class Meta:
model = User
# We want a different order of fields on the page.
fields = ['first_name', 'last_name',
'username', 'email',
'password1', 'password2', ]
def save(self, commit=True):
user = super(FullUserCreationForm, self).save(commit=False)
user.email = self.cleaned_data["email"]
user.first_name = self.cleaned_data["first_name"]
user.last_name = self.cleaned_data["last_name"]
if commit:
user.save()
return user
|
# -*- coding: utf-8 -*-
import logging
from django import forms
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth import get_user_model
LOGGER = logging.getLogger(__name__)
User = get_user_model()
class FullUserCreationForm(forms.ModelForm):
""" Like the django UserCreationForm,
with optional first_name and last_name,
and email too.
.. note:: the ``username`` field from Django's ``UserCreationForm``
is overriden by our Model's one. Thus the 30 chars limit
doesn't apply.
"""
error_messages = {
'password_mismatch': _("The two password fields didn't match."),
}
email = forms.EmailField()
password1 = forms.CharField(label=_("Password"),
widget=forms.PasswordInput)
password2 = forms.CharField(label=_("Password confirmation"),
widget=forms.PasswordInput,
help_text=_("Enter the same password as "
"above, for verification."))
class Meta:
model = User
fields = ['first_name', 'last_name',
'username', 'email',
'password1', 'password2', ]
def clean_password2(self):
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError(
self.error_messages['password_mismatch'])
return password2
def save(self, commit=True):
user = super(FullUserCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
user.email = self.cleaned_data["email"]
user.first_name = self.cleaned_data["first_name"]
user.last_name = self.cleaned_data["last_name"]
if commit:
user.save()
return user
|
Make the FullUserCreationForm work on a fresh database which doesn't have Django's auth_user table.
|
Make the FullUserCreationForm work on a fresh database which doesn't have Django's auth_user table.
|
Python
|
agpl-3.0
|
1flow/1flow,1flow/1flow,WillianPaiva/1flow,1flow/1flow,1flow/1flow,1flow/1flow,WillianPaiva/1flow,WillianPaiva/1flow,WillianPaiva/1flow,WillianPaiva/1flow
|
# -*- coding: utf-8 -*-
import logging
#from django import forms
#from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import get_user_model
LOGGER = logging.getLogger(__name__)
User = get_user_model()
class FullUserCreationForm(UserCreationForm):
""" Like the django UserCreationForm,
with optional first_name and last_name,
and email too.
.. note:: the ``username`` field from Django's ``UserCreationForm``
is overriden by our Model's one. Thus the 30 chars limit
doesn't apply.
"""
class Meta:
model = User
# We want a different order of fields on the page.
fields = ['first_name', 'last_name',
'username', 'email',
'password1', 'password2', ]
def save(self, commit=True):
user = super(FullUserCreationForm, self).save(commit=False)
user.email = self.cleaned_data["email"]
user.first_name = self.cleaned_data["first_name"]
user.last_name = self.cleaned_data["last_name"]
if commit:
user.save()
return user
Make the FullUserCreationForm work on a fresh database which doesn't have Django's auth_user table.
|
# -*- coding: utf-8 -*-
import logging
from django import forms
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth import get_user_model
LOGGER = logging.getLogger(__name__)
User = get_user_model()
class FullUserCreationForm(forms.ModelForm):
""" Like the django UserCreationForm,
with optional first_name and last_name,
and email too.
.. note:: the ``username`` field from Django's ``UserCreationForm``
is overriden by our Model's one. Thus the 30 chars limit
doesn't apply.
"""
error_messages = {
'password_mismatch': _("The two password fields didn't match."),
}
email = forms.EmailField()
password1 = forms.CharField(label=_("Password"),
widget=forms.PasswordInput)
password2 = forms.CharField(label=_("Password confirmation"),
widget=forms.PasswordInput,
help_text=_("Enter the same password as "
"above, for verification."))
class Meta:
model = User
fields = ['first_name', 'last_name',
'username', 'email',
'password1', 'password2', ]
def clean_password2(self):
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError(
self.error_messages['password_mismatch'])
return password2
def save(self, commit=True):
user = super(FullUserCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
user.email = self.cleaned_data["email"]
user.first_name = self.cleaned_data["first_name"]
user.last_name = self.cleaned_data["last_name"]
if commit:
user.save()
return user
|
<commit_before># -*- coding: utf-8 -*-
import logging
#from django import forms
#from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import get_user_model
LOGGER = logging.getLogger(__name__)
User = get_user_model()
class FullUserCreationForm(UserCreationForm):
""" Like the django UserCreationForm,
with optional first_name and last_name,
and email too.
.. note:: the ``username`` field from Django's ``UserCreationForm``
is overriden by our Model's one. Thus the 30 chars limit
doesn't apply.
"""
class Meta:
model = User
# We want a different order of fields on the page.
fields = ['first_name', 'last_name',
'username', 'email',
'password1', 'password2', ]
def save(self, commit=True):
user = super(FullUserCreationForm, self).save(commit=False)
user.email = self.cleaned_data["email"]
user.first_name = self.cleaned_data["first_name"]
user.last_name = self.cleaned_data["last_name"]
if commit:
user.save()
return user
<commit_msg>Make the FullUserCreationForm work on a fresh database which doesn't have Django's auth_user table.<commit_after>
|
# -*- coding: utf-8 -*-
import logging
from django import forms
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth import get_user_model
LOGGER = logging.getLogger(__name__)
User = get_user_model()
class FullUserCreationForm(forms.ModelForm):
""" Like the django UserCreationForm,
with optional first_name and last_name,
and email too.
.. note:: the ``username`` field from Django's ``UserCreationForm``
is overriden by our Model's one. Thus the 30 chars limit
doesn't apply.
"""
error_messages = {
'password_mismatch': _("The two password fields didn't match."),
}
email = forms.EmailField()
password1 = forms.CharField(label=_("Password"),
widget=forms.PasswordInput)
password2 = forms.CharField(label=_("Password confirmation"),
widget=forms.PasswordInput,
help_text=_("Enter the same password as "
"above, for verification."))
class Meta:
model = User
fields = ['first_name', 'last_name',
'username', 'email',
'password1', 'password2', ]
def clean_password2(self):
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError(
self.error_messages['password_mismatch'])
return password2
def save(self, commit=True):
user = super(FullUserCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
user.email = self.cleaned_data["email"]
user.first_name = self.cleaned_data["first_name"]
user.last_name = self.cleaned_data["last_name"]
if commit:
user.save()
return user
|
# -*- coding: utf-8 -*-
import logging
#from django import forms
#from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import get_user_model
LOGGER = logging.getLogger(__name__)
User = get_user_model()
class FullUserCreationForm(UserCreationForm):
""" Like the django UserCreationForm,
with optional first_name and last_name,
and email too.
.. note:: the ``username`` field from Django's ``UserCreationForm``
is overriden by our Model's one. Thus the 30 chars limit
doesn't apply.
"""
class Meta:
model = User
# We want a different order of fields on the page.
fields = ['first_name', 'last_name',
'username', 'email',
'password1', 'password2', ]
def save(self, commit=True):
user = super(FullUserCreationForm, self).save(commit=False)
user.email = self.cleaned_data["email"]
user.first_name = self.cleaned_data["first_name"]
user.last_name = self.cleaned_data["last_name"]
if commit:
user.save()
return user
Make the FullUserCreationForm work on a fresh database which doesn't have Django's auth_user table.# -*- coding: utf-8 -*-
import logging
from django import forms
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth import get_user_model
LOGGER = logging.getLogger(__name__)
User = get_user_model()
class FullUserCreationForm(forms.ModelForm):
""" Like the django UserCreationForm,
with optional first_name and last_name,
and email too.
.. note:: the ``username`` field from Django's ``UserCreationForm``
is overriden by our Model's one. Thus the 30 chars limit
doesn't apply.
"""
error_messages = {
'password_mismatch': _("The two password fields didn't match."),
}
email = forms.EmailField()
password1 = forms.CharField(label=_("Password"),
widget=forms.PasswordInput)
password2 = forms.CharField(label=_("Password confirmation"),
widget=forms.PasswordInput,
help_text=_("Enter the same password as "
"above, for verification."))
class Meta:
model = User
fields = ['first_name', 'last_name',
'username', 'email',
'password1', 'password2', ]
def clean_password2(self):
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError(
self.error_messages['password_mismatch'])
return password2
def save(self, commit=True):
user = super(FullUserCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
user.email = self.cleaned_data["email"]
user.first_name = self.cleaned_data["first_name"]
user.last_name = self.cleaned_data["last_name"]
if commit:
user.save()
return user
|
<commit_before># -*- coding: utf-8 -*-
import logging
#from django import forms
#from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import get_user_model
LOGGER = logging.getLogger(__name__)
User = get_user_model()
class FullUserCreationForm(UserCreationForm):
""" Like the django UserCreationForm,
with optional first_name and last_name,
and email too.
.. note:: the ``username`` field from Django's ``UserCreationForm``
is overriden by our Model's one. Thus the 30 chars limit
doesn't apply.
"""
class Meta:
model = User
# We want a different order of fields on the page.
fields = ['first_name', 'last_name',
'username', 'email',
'password1', 'password2', ]
def save(self, commit=True):
user = super(FullUserCreationForm, self).save(commit=False)
user.email = self.cleaned_data["email"]
user.first_name = self.cleaned_data["first_name"]
user.last_name = self.cleaned_data["last_name"]
if commit:
user.save()
return user
<commit_msg>Make the FullUserCreationForm work on a fresh database which doesn't have Django's auth_user table.<commit_after># -*- coding: utf-8 -*-
import logging
from django import forms
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth import get_user_model
LOGGER = logging.getLogger(__name__)
User = get_user_model()
class FullUserCreationForm(forms.ModelForm):
""" Like the django UserCreationForm,
with optional first_name and last_name,
and email too.
.. note:: the ``username`` field from Django's ``UserCreationForm``
is overriden by our Model's one. Thus the 30 chars limit
doesn't apply.
"""
error_messages = {
'password_mismatch': _("The two password fields didn't match."),
}
email = forms.EmailField()
password1 = forms.CharField(label=_("Password"),
widget=forms.PasswordInput)
password2 = forms.CharField(label=_("Password confirmation"),
widget=forms.PasswordInput,
help_text=_("Enter the same password as "
"above, for verification."))
class Meta:
model = User
fields = ['first_name', 'last_name',
'username', 'email',
'password1', 'password2', ]
def clean_password2(self):
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError(
self.error_messages['password_mismatch'])
return password2
def save(self, commit=True):
user = super(FullUserCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
user.email = self.cleaned_data["email"]
user.first_name = self.cleaned_data["first_name"]
user.last_name = self.cleaned_data["last_name"]
if commit:
user.save()
return user
|
c684dbb999ac622d5bba266d39e2dd7e69265393
|
yunity/api/utils.py
|
yunity/api/utils.py
|
from django.http import JsonResponse
class ApiBase(object):
STATUS_ERROR = 0
STATUS_SUCCESS = 1
STATUS_WARNING = 2
def json_response(self, data=None, status=STATUS_SUCCESS, message=None):
status_code = 400 if status == ApiBase.STATUS_ERROR else 200
return JsonResponse({
"data": data,
"status": status,
"message": message
}, status=status_code)
|
from django.http import JsonResponse
class ApiBase(object):
@classmethod
def success(cls, data, status=200):
"""
:type data: dict
:type status: int
:rtype JsonResponse
"""
return JsonResponse(data, status=status)
@classmethod
def error(cls, error, status=400):
"""
:type error: str
:type status: int
:rtype JsonResponse
"""
return JsonResponse({'error': error}, status=status)
|
Refactor json_response to more BDD methods
|
Refactor json_response to more BDD methods
|
Python
|
agpl-3.0
|
yunity/foodsaving-backend,yunity/yunity-core,yunity/foodsaving-backend,yunity/yunity-core,yunity/foodsaving-backend
|
from django.http import JsonResponse
class ApiBase(object):
STATUS_ERROR = 0
STATUS_SUCCESS = 1
STATUS_WARNING = 2
def json_response(self, data=None, status=STATUS_SUCCESS, message=None):
status_code = 400 if status == ApiBase.STATUS_ERROR else 200
return JsonResponse({
"data": data,
"status": status,
"message": message
}, status=status_code)
Refactor json_response to more BDD methods
|
from django.http import JsonResponse
class ApiBase(object):
@classmethod
def success(cls, data, status=200):
"""
:type data: dict
:type status: int
:rtype JsonResponse
"""
return JsonResponse(data, status=status)
@classmethod
def error(cls, error, status=400):
"""
:type error: str
:type status: int
:rtype JsonResponse
"""
return JsonResponse({'error': error}, status=status)
|
<commit_before>from django.http import JsonResponse
class ApiBase(object):
STATUS_ERROR = 0
STATUS_SUCCESS = 1
STATUS_WARNING = 2
def json_response(self, data=None, status=STATUS_SUCCESS, message=None):
status_code = 400 if status == ApiBase.STATUS_ERROR else 200
return JsonResponse({
"data": data,
"status": status,
"message": message
}, status=status_code)
<commit_msg>Refactor json_response to more BDD methods<commit_after>
|
from django.http import JsonResponse
class ApiBase(object):
@classmethod
def success(cls, data, status=200):
"""
:type data: dict
:type status: int
:rtype JsonResponse
"""
return JsonResponse(data, status=status)
@classmethod
def error(cls, error, status=400):
"""
:type error: str
:type status: int
:rtype JsonResponse
"""
return JsonResponse({'error': error}, status=status)
|
from django.http import JsonResponse
class ApiBase(object):
STATUS_ERROR = 0
STATUS_SUCCESS = 1
STATUS_WARNING = 2
def json_response(self, data=None, status=STATUS_SUCCESS, message=None):
status_code = 400 if status == ApiBase.STATUS_ERROR else 200
return JsonResponse({
"data": data,
"status": status,
"message": message
}, status=status_code)
Refactor json_response to more BDD methodsfrom django.http import JsonResponse
class ApiBase(object):
@classmethod
def success(cls, data, status=200):
"""
:type data: dict
:type status: int
:rtype JsonResponse
"""
return JsonResponse(data, status=status)
@classmethod
def error(cls, error, status=400):
"""
:type error: str
:type status: int
:rtype JsonResponse
"""
return JsonResponse({'error': error}, status=status)
|
<commit_before>from django.http import JsonResponse
class ApiBase(object):
STATUS_ERROR = 0
STATUS_SUCCESS = 1
STATUS_WARNING = 2
def json_response(self, data=None, status=STATUS_SUCCESS, message=None):
status_code = 400 if status == ApiBase.STATUS_ERROR else 200
return JsonResponse({
"data": data,
"status": status,
"message": message
}, status=status_code)
<commit_msg>Refactor json_response to more BDD methods<commit_after>from django.http import JsonResponse
class ApiBase(object):
@classmethod
def success(cls, data, status=200):
"""
:type data: dict
:type status: int
:rtype JsonResponse
"""
return JsonResponse(data, status=status)
@classmethod
def error(cls, error, status=400):
"""
:type error: str
:type status: int
:rtype JsonResponse
"""
return JsonResponse({'error': error}, status=status)
|
6977b25faacc4714363fe0cddf7ae436e74595ac
|
fmn/rules/koschei.py
|
fmn/rules/koschei.py
|
from fmn.lib.hinting import hint, prefixed as _
@hint(topics=[_('koschei.package.state.change')])
def koschei_package_state_change(config, message):
""" Continuous integration state changes for a package (koschei)
`Koschei <https://apps.fedoraproject.org/koschei/>`_ publishes
this message when package's build or resolution state changes.
"""
return message['topic'].endswith('koschei.package.state.change')
@hint(categories=['koschei'], invertible=False)
def koschei_group(config, message, group=None):
""" Particular Koschei package groups
This rule limits message to particular
`Koschei <https://apps.fedoraproject.org/koschei/>`_ groups.
You can specify more groups separated by commas.
"""
if not group or 'koschei' not in message['topic']:
return False
groups = set([item.strip() for item in group.split(',')])
return bool(groups.intersection(message['msg'].get('groups')))
|
from fmn.lib.hinting import hint, prefixed as _
@hint(topics=[_('koschei.package.state.change')])
def koschei_package_state_change(config, message):
""" Continuous integration state changes for a package (koschei)
`Koschei <https://apps.fedoraproject.org/koschei/>`_ publishes
this message when package's build or resolution state changes.
"""
return message['topic'].endswith('koschei.package.state.change')
@hint(categories=['koschei'], invertible=False)
def koschei_group(config, message, group=None):
""" Particular Koschei package groups
This rule limits message to particular
`Koschei <https://apps.fedoraproject.org/koschei/>`_ groups.
You can specify more groups separated by commas.
"""
if not group or 'koschei' not in message['topic']:
return False
groups = set([item.strip() for item in group.split(',')])
return bool(groups.intersection(message['msg'].get('groups', [])))
|
Work with broken Koschei rules
|
Work with broken Koschei rules
Messages sent in the morning of 2015-09-25 were missing the groups
field. Deal with that not existing.
Example messages:
- 2015-eebf137e-cc22-48c2-87f0-7d736950f76b
- 2015-2a5361ec-9c36-438a-8233-709e9f006003
Signed-off-by: Patrick Uiterwijk <bd6d5394796bee9cca2245486eb583fd64b70226@redhat.com>
|
Python
|
lgpl-2.1
|
jeremycline/fmn,fedora-infra/fmn.rules,jeremycline/fmn,jeremycline/fmn
|
from fmn.lib.hinting import hint, prefixed as _
@hint(topics=[_('koschei.package.state.change')])
def koschei_package_state_change(config, message):
""" Continuous integration state changes for a package (koschei)
`Koschei <https://apps.fedoraproject.org/koschei/>`_ publishes
this message when package's build or resolution state changes.
"""
return message['topic'].endswith('koschei.package.state.change')
@hint(categories=['koschei'], invertible=False)
def koschei_group(config, message, group=None):
""" Particular Koschei package groups
This rule limits message to particular
`Koschei <https://apps.fedoraproject.org/koschei/>`_ groups.
You can specify more groups separated by commas.
"""
if not group or 'koschei' not in message['topic']:
return False
groups = set([item.strip() for item in group.split(',')])
return bool(groups.intersection(message['msg'].get('groups')))
Work with broken Koschei rules
Messages sent in the morning of 2015-09-25 were missing the groups
field. Deal with that not existing.
Example messages:
- 2015-eebf137e-cc22-48c2-87f0-7d736950f76b
- 2015-2a5361ec-9c36-438a-8233-709e9f006003
Signed-off-by: Patrick Uiterwijk <bd6d5394796bee9cca2245486eb583fd64b70226@redhat.com>
|
from fmn.lib.hinting import hint, prefixed as _
@hint(topics=[_('koschei.package.state.change')])
def koschei_package_state_change(config, message):
""" Continuous integration state changes for a package (koschei)
`Koschei <https://apps.fedoraproject.org/koschei/>`_ publishes
this message when package's build or resolution state changes.
"""
return message['topic'].endswith('koschei.package.state.change')
@hint(categories=['koschei'], invertible=False)
def koschei_group(config, message, group=None):
""" Particular Koschei package groups
This rule limits message to particular
`Koschei <https://apps.fedoraproject.org/koschei/>`_ groups.
You can specify more groups separated by commas.
"""
if not group or 'koschei' not in message['topic']:
return False
groups = set([item.strip() for item in group.split(',')])
return bool(groups.intersection(message['msg'].get('groups', [])))
|
<commit_before>from fmn.lib.hinting import hint, prefixed as _
@hint(topics=[_('koschei.package.state.change')])
def koschei_package_state_change(config, message):
""" Continuous integration state changes for a package (koschei)
`Koschei <https://apps.fedoraproject.org/koschei/>`_ publishes
this message when package's build or resolution state changes.
"""
return message['topic'].endswith('koschei.package.state.change')
@hint(categories=['koschei'], invertible=False)
def koschei_group(config, message, group=None):
""" Particular Koschei package groups
This rule limits message to particular
`Koschei <https://apps.fedoraproject.org/koschei/>`_ groups.
You can specify more groups separated by commas.
"""
if not group or 'koschei' not in message['topic']:
return False
groups = set([item.strip() for item in group.split(',')])
return bool(groups.intersection(message['msg'].get('groups')))
<commit_msg>Work with broken Koschei rules
Messages sent in the morning of 2015-09-25 were missing the groups
field. Deal with that not existing.
Example messages:
- 2015-eebf137e-cc22-48c2-87f0-7d736950f76b
- 2015-2a5361ec-9c36-438a-8233-709e9f006003
Signed-off-by: Patrick Uiterwijk <bd6d5394796bee9cca2245486eb583fd64b70226@redhat.com><commit_after>
|
from fmn.lib.hinting import hint, prefixed as _
@hint(topics=[_('koschei.package.state.change')])
def koschei_package_state_change(config, message):
""" Continuous integration state changes for a package (koschei)
`Koschei <https://apps.fedoraproject.org/koschei/>`_ publishes
this message when package's build or resolution state changes.
"""
return message['topic'].endswith('koschei.package.state.change')
@hint(categories=['koschei'], invertible=False)
def koschei_group(config, message, group=None):
""" Particular Koschei package groups
This rule limits message to particular
`Koschei <https://apps.fedoraproject.org/koschei/>`_ groups.
You can specify more groups separated by commas.
"""
if not group or 'koschei' not in message['topic']:
return False
groups = set([item.strip() for item in group.split(',')])
return bool(groups.intersection(message['msg'].get('groups', [])))
|
from fmn.lib.hinting import hint, prefixed as _
@hint(topics=[_('koschei.package.state.change')])
def koschei_package_state_change(config, message):
""" Continuous integration state changes for a package (koschei)
`Koschei <https://apps.fedoraproject.org/koschei/>`_ publishes
this message when package's build or resolution state changes.
"""
return message['topic'].endswith('koschei.package.state.change')
@hint(categories=['koschei'], invertible=False)
def koschei_group(config, message, group=None):
""" Particular Koschei package groups
This rule limits message to particular
`Koschei <https://apps.fedoraproject.org/koschei/>`_ groups.
You can specify more groups separated by commas.
"""
if not group or 'koschei' not in message['topic']:
return False
groups = set([item.strip() for item in group.split(',')])
return bool(groups.intersection(message['msg'].get('groups')))
Work with broken Koschei rules
Messages sent in the morning of 2015-09-25 were missing the groups
field. Deal with that not existing.
Example messages:
- 2015-eebf137e-cc22-48c2-87f0-7d736950f76b
- 2015-2a5361ec-9c36-438a-8233-709e9f006003
Signed-off-by: Patrick Uiterwijk <bd6d5394796bee9cca2245486eb583fd64b70226@redhat.com>from fmn.lib.hinting import hint, prefixed as _
@hint(topics=[_('koschei.package.state.change')])
def koschei_package_state_change(config, message):
""" Continuous integration state changes for a package (koschei)
`Koschei <https://apps.fedoraproject.org/koschei/>`_ publishes
this message when package's build or resolution state changes.
"""
return message['topic'].endswith('koschei.package.state.change')
@hint(categories=['koschei'], invertible=False)
def koschei_group(config, message, group=None):
""" Particular Koschei package groups
This rule limits message to particular
`Koschei <https://apps.fedoraproject.org/koschei/>`_ groups.
You can specify more groups separated by commas.
"""
if not group or 'koschei' not in message['topic']:
return False
groups = set([item.strip() for item in group.split(',')])
return bool(groups.intersection(message['msg'].get('groups', [])))
|
<commit_before>from fmn.lib.hinting import hint, prefixed as _
@hint(topics=[_('koschei.package.state.change')])
def koschei_package_state_change(config, message):
""" Continuous integration state changes for a package (koschei)
`Koschei <https://apps.fedoraproject.org/koschei/>`_ publishes
this message when package's build or resolution state changes.
"""
return message['topic'].endswith('koschei.package.state.change')
@hint(categories=['koschei'], invertible=False)
def koschei_group(config, message, group=None):
""" Particular Koschei package groups
This rule limits message to particular
`Koschei <https://apps.fedoraproject.org/koschei/>`_ groups.
You can specify more groups separated by commas.
"""
if not group or 'koschei' not in message['topic']:
return False
groups = set([item.strip() for item in group.split(',')])
return bool(groups.intersection(message['msg'].get('groups')))
<commit_msg>Work with broken Koschei rules
Messages sent in the morning of 2015-09-25 were missing the groups
field. Deal with that not existing.
Example messages:
- 2015-eebf137e-cc22-48c2-87f0-7d736950f76b
- 2015-2a5361ec-9c36-438a-8233-709e9f006003
Signed-off-by: Patrick Uiterwijk <bd6d5394796bee9cca2245486eb583fd64b70226@redhat.com><commit_after>from fmn.lib.hinting import hint, prefixed as _
@hint(topics=[_('koschei.package.state.change')])
def koschei_package_state_change(config, message):
""" Continuous integration state changes for a package (koschei)
`Koschei <https://apps.fedoraproject.org/koschei/>`_ publishes
this message when package's build or resolution state changes.
"""
return message['topic'].endswith('koschei.package.state.change')
@hint(categories=['koschei'], invertible=False)
def koschei_group(config, message, group=None):
""" Particular Koschei package groups
This rule limits message to particular
`Koschei <https://apps.fedoraproject.org/koschei/>`_ groups.
You can specify more groups separated by commas.
"""
if not group or 'koschei' not in message['topic']:
return False
groups = set([item.strip() for item in group.split(',')])
return bool(groups.intersection(message['msg'].get('groups', [])))
|
dbb223d64d1058e34c35867dcca2665766d0edbf
|
synapse/tests/test_config.py
|
synapse/tests/test_config.py
|
from synapse.tests.common import *
import synapse.lib.config as s_config
class ConfTest(SynTest):
def test_conf_base(self):
defs = (
('fooval',{'type':'int','doc':'what is foo val?','defval':99}),
('enabled',{'type':'bool','doc':'is thing enabled?','defval':0}),
)
data = {}
def callback(v):
data['woot'] = v
with s_config.Config(defs=defs) as conf:
conf.onConfOptSet('enabled',callback)
conf.setConfOpt('enabled','true')
self.eq(data.get('woot'), 1)
conf.setConfOpts({'fooval':'0x20'})
self.eq(conf.getConfOpt('fooval'), 0x20)
conf.setConfOpts({'fooval':0x30})
self.eq(conf.getConfOpt('fooval'), 0x30)
self.assertRaises( NoSuchOpt, conf.setConfOpts, {'newp':'hehe'} )
def test_conf_asloc(self):
with s_config.Config() as conf:
conf.addConfDef('foo',type='int',defval=0,asloc='_foo_valu')
self.eq( conf._foo_valu, 0 )
conf.setConfOpt('foo','0x20')
self.eq( conf._foo_valu, 0x20)
|
from synapse.tests.common import *
import synapse.lib.config as s_config
class ConfTest(SynTest):
def test_conf_base(self):
defs = (
('fooval',{'type':'int','doc':'what is foo val?','defval':99}),
('enabled',{'type':'bool','doc':'is thing enabled?','defval':0}),
)
data = {}
def callback(v):
data['woot'] = v
with s_config.Config(defs=defs) as conf:
self.eq(conf.getConfOpt('enabled'), 0)
self.eq(conf.getConfOpt('fooval'), 99)
conf.onConfOptSet('enabled',callback)
conf.setConfOpt('enabled','true')
self.eq(data.get('woot'), 1)
conf.setConfOpts({'fooval':'0x20'})
self.eq(conf.getConfOpt('fooval'), 0x20)
conf.setConfOpts({'fooval':0x30})
self.eq(conf.getConfOpt('fooval'), 0x30)
self.assertRaises( NoSuchOpt, conf.setConfOpts, {'newp':'hehe'} )
def test_conf_asloc(self):
with s_config.Config() as conf:
conf.addConfDef('foo',type='int',defval=0,asloc='_foo_valu')
self.eq( conf._foo_valu, 0 )
conf.setConfOpt('foo','0x20')
self.eq( conf._foo_valu, 0x20)
|
Update test to ensure that default configuration values are available via getConfOpt
|
Update test to ensure that default configuration values are available via getConfOpt
|
Python
|
apache-2.0
|
vertexproject/synapse,vertexproject/synapse,vertexproject/synapse,vivisect/synapse
|
from synapse.tests.common import *
import synapse.lib.config as s_config
class ConfTest(SynTest):
def test_conf_base(self):
defs = (
('fooval',{'type':'int','doc':'what is foo val?','defval':99}),
('enabled',{'type':'bool','doc':'is thing enabled?','defval':0}),
)
data = {}
def callback(v):
data['woot'] = v
with s_config.Config(defs=defs) as conf:
conf.onConfOptSet('enabled',callback)
conf.setConfOpt('enabled','true')
self.eq(data.get('woot'), 1)
conf.setConfOpts({'fooval':'0x20'})
self.eq(conf.getConfOpt('fooval'), 0x20)
conf.setConfOpts({'fooval':0x30})
self.eq(conf.getConfOpt('fooval'), 0x30)
self.assertRaises( NoSuchOpt, conf.setConfOpts, {'newp':'hehe'} )
def test_conf_asloc(self):
with s_config.Config() as conf:
conf.addConfDef('foo',type='int',defval=0,asloc='_foo_valu')
self.eq( conf._foo_valu, 0 )
conf.setConfOpt('foo','0x20')
self.eq( conf._foo_valu, 0x20)
Update test to ensure that default configuration values are available via getConfOpt
|
from synapse.tests.common import *
import synapse.lib.config as s_config
class ConfTest(SynTest):
def test_conf_base(self):
defs = (
('fooval',{'type':'int','doc':'what is foo val?','defval':99}),
('enabled',{'type':'bool','doc':'is thing enabled?','defval':0}),
)
data = {}
def callback(v):
data['woot'] = v
with s_config.Config(defs=defs) as conf:
self.eq(conf.getConfOpt('enabled'), 0)
self.eq(conf.getConfOpt('fooval'), 99)
conf.onConfOptSet('enabled',callback)
conf.setConfOpt('enabled','true')
self.eq(data.get('woot'), 1)
conf.setConfOpts({'fooval':'0x20'})
self.eq(conf.getConfOpt('fooval'), 0x20)
conf.setConfOpts({'fooval':0x30})
self.eq(conf.getConfOpt('fooval'), 0x30)
self.assertRaises( NoSuchOpt, conf.setConfOpts, {'newp':'hehe'} )
def test_conf_asloc(self):
with s_config.Config() as conf:
conf.addConfDef('foo',type='int',defval=0,asloc='_foo_valu')
self.eq( conf._foo_valu, 0 )
conf.setConfOpt('foo','0x20')
self.eq( conf._foo_valu, 0x20)
|
<commit_before>from synapse.tests.common import *
import synapse.lib.config as s_config
class ConfTest(SynTest):
def test_conf_base(self):
defs = (
('fooval',{'type':'int','doc':'what is foo val?','defval':99}),
('enabled',{'type':'bool','doc':'is thing enabled?','defval':0}),
)
data = {}
def callback(v):
data['woot'] = v
with s_config.Config(defs=defs) as conf:
conf.onConfOptSet('enabled',callback)
conf.setConfOpt('enabled','true')
self.eq(data.get('woot'), 1)
conf.setConfOpts({'fooval':'0x20'})
self.eq(conf.getConfOpt('fooval'), 0x20)
conf.setConfOpts({'fooval':0x30})
self.eq(conf.getConfOpt('fooval'), 0x30)
self.assertRaises( NoSuchOpt, conf.setConfOpts, {'newp':'hehe'} )
def test_conf_asloc(self):
with s_config.Config() as conf:
conf.addConfDef('foo',type='int',defval=0,asloc='_foo_valu')
self.eq( conf._foo_valu, 0 )
conf.setConfOpt('foo','0x20')
self.eq( conf._foo_valu, 0x20)
<commit_msg>Update test to ensure that default configuration values are available via getConfOpt<commit_after>
|
from synapse.tests.common import *
import synapse.lib.config as s_config
class ConfTest(SynTest):
def test_conf_base(self):
defs = (
('fooval',{'type':'int','doc':'what is foo val?','defval':99}),
('enabled',{'type':'bool','doc':'is thing enabled?','defval':0}),
)
data = {}
def callback(v):
data['woot'] = v
with s_config.Config(defs=defs) as conf:
self.eq(conf.getConfOpt('enabled'), 0)
self.eq(conf.getConfOpt('fooval'), 99)
conf.onConfOptSet('enabled',callback)
conf.setConfOpt('enabled','true')
self.eq(data.get('woot'), 1)
conf.setConfOpts({'fooval':'0x20'})
self.eq(conf.getConfOpt('fooval'), 0x20)
conf.setConfOpts({'fooval':0x30})
self.eq(conf.getConfOpt('fooval'), 0x30)
self.assertRaises( NoSuchOpt, conf.setConfOpts, {'newp':'hehe'} )
def test_conf_asloc(self):
with s_config.Config() as conf:
conf.addConfDef('foo',type='int',defval=0,asloc='_foo_valu')
self.eq( conf._foo_valu, 0 )
conf.setConfOpt('foo','0x20')
self.eq( conf._foo_valu, 0x20)
|
from synapse.tests.common import *
import synapse.lib.config as s_config
class ConfTest(SynTest):
def test_conf_base(self):
defs = (
('fooval',{'type':'int','doc':'what is foo val?','defval':99}),
('enabled',{'type':'bool','doc':'is thing enabled?','defval':0}),
)
data = {}
def callback(v):
data['woot'] = v
with s_config.Config(defs=defs) as conf:
conf.onConfOptSet('enabled',callback)
conf.setConfOpt('enabled','true')
self.eq(data.get('woot'), 1)
conf.setConfOpts({'fooval':'0x20'})
self.eq(conf.getConfOpt('fooval'), 0x20)
conf.setConfOpts({'fooval':0x30})
self.eq(conf.getConfOpt('fooval'), 0x30)
self.assertRaises( NoSuchOpt, conf.setConfOpts, {'newp':'hehe'} )
def test_conf_asloc(self):
with s_config.Config() as conf:
conf.addConfDef('foo',type='int',defval=0,asloc='_foo_valu')
self.eq( conf._foo_valu, 0 )
conf.setConfOpt('foo','0x20')
self.eq( conf._foo_valu, 0x20)
Update test to ensure that default configuration values are available via getConfOptfrom synapse.tests.common import *
import synapse.lib.config as s_config
class ConfTest(SynTest):
def test_conf_base(self):
defs = (
('fooval',{'type':'int','doc':'what is foo val?','defval':99}),
('enabled',{'type':'bool','doc':'is thing enabled?','defval':0}),
)
data = {}
def callback(v):
data['woot'] = v
with s_config.Config(defs=defs) as conf:
self.eq(conf.getConfOpt('enabled'), 0)
self.eq(conf.getConfOpt('fooval'), 99)
conf.onConfOptSet('enabled',callback)
conf.setConfOpt('enabled','true')
self.eq(data.get('woot'), 1)
conf.setConfOpts({'fooval':'0x20'})
self.eq(conf.getConfOpt('fooval'), 0x20)
conf.setConfOpts({'fooval':0x30})
self.eq(conf.getConfOpt('fooval'), 0x30)
self.assertRaises( NoSuchOpt, conf.setConfOpts, {'newp':'hehe'} )
def test_conf_asloc(self):
with s_config.Config() as conf:
conf.addConfDef('foo',type='int',defval=0,asloc='_foo_valu')
self.eq( conf._foo_valu, 0 )
conf.setConfOpt('foo','0x20')
self.eq( conf._foo_valu, 0x20)
|
<commit_before>from synapse.tests.common import *
import synapse.lib.config as s_config
class ConfTest(SynTest):
def test_conf_base(self):
defs = (
('fooval',{'type':'int','doc':'what is foo val?','defval':99}),
('enabled',{'type':'bool','doc':'is thing enabled?','defval':0}),
)
data = {}
def callback(v):
data['woot'] = v
with s_config.Config(defs=defs) as conf:
conf.onConfOptSet('enabled',callback)
conf.setConfOpt('enabled','true')
self.eq(data.get('woot'), 1)
conf.setConfOpts({'fooval':'0x20'})
self.eq(conf.getConfOpt('fooval'), 0x20)
conf.setConfOpts({'fooval':0x30})
self.eq(conf.getConfOpt('fooval'), 0x30)
self.assertRaises( NoSuchOpt, conf.setConfOpts, {'newp':'hehe'} )
def test_conf_asloc(self):
with s_config.Config() as conf:
conf.addConfDef('foo',type='int',defval=0,asloc='_foo_valu')
self.eq( conf._foo_valu, 0 )
conf.setConfOpt('foo','0x20')
self.eq( conf._foo_valu, 0x20)
<commit_msg>Update test to ensure that default configuration values are available via getConfOpt<commit_after>from synapse.tests.common import *
import synapse.lib.config as s_config
class ConfTest(SynTest):
def test_conf_base(self):
defs = (
('fooval',{'type':'int','doc':'what is foo val?','defval':99}),
('enabled',{'type':'bool','doc':'is thing enabled?','defval':0}),
)
data = {}
def callback(v):
data['woot'] = v
with s_config.Config(defs=defs) as conf:
self.eq(conf.getConfOpt('enabled'), 0)
self.eq(conf.getConfOpt('fooval'), 99)
conf.onConfOptSet('enabled',callback)
conf.setConfOpt('enabled','true')
self.eq(data.get('woot'), 1)
conf.setConfOpts({'fooval':'0x20'})
self.eq(conf.getConfOpt('fooval'), 0x20)
conf.setConfOpts({'fooval':0x30})
self.eq(conf.getConfOpt('fooval'), 0x30)
self.assertRaises( NoSuchOpt, conf.setConfOpts, {'newp':'hehe'} )
def test_conf_asloc(self):
with s_config.Config() as conf:
conf.addConfDef('foo',type='int',defval=0,asloc='_foo_valu')
self.eq( conf._foo_valu, 0 )
conf.setConfOpt('foo','0x20')
self.eq( conf._foo_valu, 0x20)
|
876cfd11bf57101ca7774e0f003855ab7603bfba
|
dh/thirdparty/__init__.py
|
dh/thirdparty/__init__.py
|
"""
Third-party modules which are essential and must always available.
For maximum compatibility, these modules should be pure Python without
non-standard dependencies.
List of current modules:
* atomicwrites-1.1.5 (https://github.com/untitaker/python-atomicwrites)
* colorama-0.3.9 (https://github.com/tartley/colorama)
* humanize-0.5.1 (https://github.com/jmoiron/humanize)
* tabulate-0.7.7 (https://bitbucket.org/astanin/python-tabulate)
* transitions-0.5.3 (https://github.com/tyarkoni/transitions)
* tqdm-4.13.0 (https://github.com/tqdm/tqdm)
Note: `transitions` was modified to remove the requirement for the module
`six`.
"""
|
"""
Third-party modules which are essential and must always available.
For maximum compatibility, these modules should be pure Python without
non-standard dependencies.
List of current modules:
* atomicwrites-1.1.5 (https://github.com/untitaker/python-atomicwrites)
* colorama-0.3.9 (https://github.com/tartley/colorama)
* humanize-0.5.1 (https://github.com/jmoiron/humanize)
* tabulate-0.7.7 (https://bitbucket.org/astanin/python-tabulate)
* tqdm-4.13.0 (https://github.com/tqdm/tqdm)
Note: `transitions` was modified to remove the requirement for the module
`six`.
"""
|
Remove package transitions in documentation
|
Remove package transitions in documentation
|
Python
|
mit
|
dhaase-de/dh-python-dh,dhaase-de/dh-python-dh
|
"""
Third-party modules which are essential and must always available.
For maximum compatibility, these modules should be pure Python without
non-standard dependencies.
List of current modules:
* atomicwrites-1.1.5 (https://github.com/untitaker/python-atomicwrites)
* colorama-0.3.9 (https://github.com/tartley/colorama)
* humanize-0.5.1 (https://github.com/jmoiron/humanize)
* tabulate-0.7.7 (https://bitbucket.org/astanin/python-tabulate)
* transitions-0.5.3 (https://github.com/tyarkoni/transitions)
* tqdm-4.13.0 (https://github.com/tqdm/tqdm)
Note: `transitions` was modified to remove the requirement for the module
`six`.
"""
Remove package transitions in documentation
|
"""
Third-party modules which are essential and must always available.
For maximum compatibility, these modules should be pure Python without
non-standard dependencies.
List of current modules:
* atomicwrites-1.1.5 (https://github.com/untitaker/python-atomicwrites)
* colorama-0.3.9 (https://github.com/tartley/colorama)
* humanize-0.5.1 (https://github.com/jmoiron/humanize)
* tabulate-0.7.7 (https://bitbucket.org/astanin/python-tabulate)
* tqdm-4.13.0 (https://github.com/tqdm/tqdm)
Note: `transitions` was modified to remove the requirement for the module
`six`.
"""
|
<commit_before>"""
Third-party modules which are essential and must always available.
For maximum compatibility, these modules should be pure Python without
non-standard dependencies.
List of current modules:
* atomicwrites-1.1.5 (https://github.com/untitaker/python-atomicwrites)
* colorama-0.3.9 (https://github.com/tartley/colorama)
* humanize-0.5.1 (https://github.com/jmoiron/humanize)
* tabulate-0.7.7 (https://bitbucket.org/astanin/python-tabulate)
* transitions-0.5.3 (https://github.com/tyarkoni/transitions)
* tqdm-4.13.0 (https://github.com/tqdm/tqdm)
Note: `transitions` was modified to remove the requirement for the module
`six`.
"""
<commit_msg>Remove package transitions in documentation<commit_after>
|
"""
Third-party modules which are essential and must always available.
For maximum compatibility, these modules should be pure Python without
non-standard dependencies.
List of current modules:
* atomicwrites-1.1.5 (https://github.com/untitaker/python-atomicwrites)
* colorama-0.3.9 (https://github.com/tartley/colorama)
* humanize-0.5.1 (https://github.com/jmoiron/humanize)
* tabulate-0.7.7 (https://bitbucket.org/astanin/python-tabulate)
* tqdm-4.13.0 (https://github.com/tqdm/tqdm)
Note: `transitions` was modified to remove the requirement for the module
`six`.
"""
|
"""
Third-party modules which are essential and must always available.
For maximum compatibility, these modules should be pure Python without
non-standard dependencies.
List of current modules:
* atomicwrites-1.1.5 (https://github.com/untitaker/python-atomicwrites)
* colorama-0.3.9 (https://github.com/tartley/colorama)
* humanize-0.5.1 (https://github.com/jmoiron/humanize)
* tabulate-0.7.7 (https://bitbucket.org/astanin/python-tabulate)
* transitions-0.5.3 (https://github.com/tyarkoni/transitions)
* tqdm-4.13.0 (https://github.com/tqdm/tqdm)
Note: `transitions` was modified to remove the requirement for the module
`six`.
"""
Remove package transitions in documentation"""
Third-party modules which are essential and must always available.
For maximum compatibility, these modules should be pure Python without
non-standard dependencies.
List of current modules:
* atomicwrites-1.1.5 (https://github.com/untitaker/python-atomicwrites)
* colorama-0.3.9 (https://github.com/tartley/colorama)
* humanize-0.5.1 (https://github.com/jmoiron/humanize)
* tabulate-0.7.7 (https://bitbucket.org/astanin/python-tabulate)
* tqdm-4.13.0 (https://github.com/tqdm/tqdm)
Note: `transitions` was modified to remove the requirement for the module
`six`.
"""
|
<commit_before>"""
Third-party modules which are essential and must always available.
For maximum compatibility, these modules should be pure Python without
non-standard dependencies.
List of current modules:
* atomicwrites-1.1.5 (https://github.com/untitaker/python-atomicwrites)
* colorama-0.3.9 (https://github.com/tartley/colorama)
* humanize-0.5.1 (https://github.com/jmoiron/humanize)
* tabulate-0.7.7 (https://bitbucket.org/astanin/python-tabulate)
* transitions-0.5.3 (https://github.com/tyarkoni/transitions)
* tqdm-4.13.0 (https://github.com/tqdm/tqdm)
Note: `transitions` was modified to remove the requirement for the module
`six`.
"""
<commit_msg>Remove package transitions in documentation<commit_after>"""
Third-party modules which are essential and must always available.
For maximum compatibility, these modules should be pure Python without
non-standard dependencies.
List of current modules:
* atomicwrites-1.1.5 (https://github.com/untitaker/python-atomicwrites)
* colorama-0.3.9 (https://github.com/tartley/colorama)
* humanize-0.5.1 (https://github.com/jmoiron/humanize)
* tabulate-0.7.7 (https://bitbucket.org/astanin/python-tabulate)
* tqdm-4.13.0 (https://github.com/tqdm/tqdm)
Note: `transitions` was modified to remove the requirement for the module
`six`.
"""
|
62b177e0a0fd7adbabe72d04befff566f05e9a74
|
scudcloud/notifier.py
|
scudcloud/notifier.py
|
from dbus.exceptions import DBusException
try:
import gi
gi.require_version('Notify', '0.7')
from gi.repository import Notify
except (ImportError, AttributeError):
from scudcloud import notify2
Notify = None
class Notifier(object):
def __init__(self, app_name, icon):
self.icon = icon
try:
if Notify is not None:
Notify.init(app_name)
self.notifier = Notify
else:
notify2.init(app_name)
self.notifier = notify2
self.enabled = True
except DBusException:
print("WARNING: No notification daemon found! "
"Notifications will be ignored.")
self.enabled = False
def notify(self, title, message, icon=None):
if not self.enabled:
return
if icon is None:
icon = self.icon
if Notify is not None:
notice = self.notifier.Notification.new(title, message, icon)
else:
notice = notify2.Notification(title, message, icon)
notice.set_hint_string('x-canonical-append', '')
try:
notice.show()
except:
pass
|
from dbus.exceptions import DBusException
try:
import gi
gi.require_version('Notify', '0.7')
from gi.repository import Notify
except (ImportError, AttributeError, ValueError):
from scudcloud import notify2
Notify = None
class Notifier(object):
def __init__(self, app_name, icon):
self.icon = icon
try:
if Notify is not None:
Notify.init(app_name)
self.notifier = Notify
else:
notify2.init(app_name)
self.notifier = notify2
self.enabled = True
except DBusException:
print("WARNING: No notification daemon found! "
"Notifications will be ignored.")
self.enabled = False
def notify(self, title, message, icon=None):
if not self.enabled:
return
if icon is None:
icon = self.icon
if Notify is not None:
notice = self.notifier.Notification.new(title, message, icon)
else:
notice = notify2.Notification(title, message, icon)
notice.set_hint_string('x-canonical-append', '')
try:
notice.show()
except:
pass
|
Allow ValueError as a notify exception
|
Allow ValueError as a notify exception
|
Python
|
mit
|
raelgc/scudcloud,raelgc/scudcloud,raelgc/scudcloud
|
from dbus.exceptions import DBusException
try:
import gi
gi.require_version('Notify', '0.7')
from gi.repository import Notify
except (ImportError, AttributeError):
from scudcloud import notify2
Notify = None
class Notifier(object):
def __init__(self, app_name, icon):
self.icon = icon
try:
if Notify is not None:
Notify.init(app_name)
self.notifier = Notify
else:
notify2.init(app_name)
self.notifier = notify2
self.enabled = True
except DBusException:
print("WARNING: No notification daemon found! "
"Notifications will be ignored.")
self.enabled = False
def notify(self, title, message, icon=None):
if not self.enabled:
return
if icon is None:
icon = self.icon
if Notify is not None:
notice = self.notifier.Notification.new(title, message, icon)
else:
notice = notify2.Notification(title, message, icon)
notice.set_hint_string('x-canonical-append', '')
try:
notice.show()
except:
pass
Allow ValueError as a notify exception
|
from dbus.exceptions import DBusException
try:
import gi
gi.require_version('Notify', '0.7')
from gi.repository import Notify
except (ImportError, AttributeError, ValueError):
from scudcloud import notify2
Notify = None
class Notifier(object):
def __init__(self, app_name, icon):
self.icon = icon
try:
if Notify is not None:
Notify.init(app_name)
self.notifier = Notify
else:
notify2.init(app_name)
self.notifier = notify2
self.enabled = True
except DBusException:
print("WARNING: No notification daemon found! "
"Notifications will be ignored.")
self.enabled = False
def notify(self, title, message, icon=None):
if not self.enabled:
return
if icon is None:
icon = self.icon
if Notify is not None:
notice = self.notifier.Notification.new(title, message, icon)
else:
notice = notify2.Notification(title, message, icon)
notice.set_hint_string('x-canonical-append', '')
try:
notice.show()
except:
pass
|
<commit_before>from dbus.exceptions import DBusException
try:
import gi
gi.require_version('Notify', '0.7')
from gi.repository import Notify
except (ImportError, AttributeError):
from scudcloud import notify2
Notify = None
class Notifier(object):
def __init__(self, app_name, icon):
self.icon = icon
try:
if Notify is not None:
Notify.init(app_name)
self.notifier = Notify
else:
notify2.init(app_name)
self.notifier = notify2
self.enabled = True
except DBusException:
print("WARNING: No notification daemon found! "
"Notifications will be ignored.")
self.enabled = False
def notify(self, title, message, icon=None):
if not self.enabled:
return
if icon is None:
icon = self.icon
if Notify is not None:
notice = self.notifier.Notification.new(title, message, icon)
else:
notice = notify2.Notification(title, message, icon)
notice.set_hint_string('x-canonical-append', '')
try:
notice.show()
except:
pass
<commit_msg>Allow ValueError as a notify exception<commit_after>
|
from dbus.exceptions import DBusException
try:
import gi
gi.require_version('Notify', '0.7')
from gi.repository import Notify
except (ImportError, AttributeError, ValueError):
from scudcloud import notify2
Notify = None
class Notifier(object):
def __init__(self, app_name, icon):
self.icon = icon
try:
if Notify is not None:
Notify.init(app_name)
self.notifier = Notify
else:
notify2.init(app_name)
self.notifier = notify2
self.enabled = True
except DBusException:
print("WARNING: No notification daemon found! "
"Notifications will be ignored.")
self.enabled = False
def notify(self, title, message, icon=None):
if not self.enabled:
return
if icon is None:
icon = self.icon
if Notify is not None:
notice = self.notifier.Notification.new(title, message, icon)
else:
notice = notify2.Notification(title, message, icon)
notice.set_hint_string('x-canonical-append', '')
try:
notice.show()
except:
pass
|
from dbus.exceptions import DBusException
try:
import gi
gi.require_version('Notify', '0.7')
from gi.repository import Notify
except (ImportError, AttributeError):
from scudcloud import notify2
Notify = None
class Notifier(object):
def __init__(self, app_name, icon):
self.icon = icon
try:
if Notify is not None:
Notify.init(app_name)
self.notifier = Notify
else:
notify2.init(app_name)
self.notifier = notify2
self.enabled = True
except DBusException:
print("WARNING: No notification daemon found! "
"Notifications will be ignored.")
self.enabled = False
def notify(self, title, message, icon=None):
if not self.enabled:
return
if icon is None:
icon = self.icon
if Notify is not None:
notice = self.notifier.Notification.new(title, message, icon)
else:
notice = notify2.Notification(title, message, icon)
notice.set_hint_string('x-canonical-append', '')
try:
notice.show()
except:
pass
Allow ValueError as a notify exceptionfrom dbus.exceptions import DBusException
try:
import gi
gi.require_version('Notify', '0.7')
from gi.repository import Notify
except (ImportError, AttributeError, ValueError):
from scudcloud import notify2
Notify = None
class Notifier(object):
def __init__(self, app_name, icon):
self.icon = icon
try:
if Notify is not None:
Notify.init(app_name)
self.notifier = Notify
else:
notify2.init(app_name)
self.notifier = notify2
self.enabled = True
except DBusException:
print("WARNING: No notification daemon found! "
"Notifications will be ignored.")
self.enabled = False
def notify(self, title, message, icon=None):
if not self.enabled:
return
if icon is None:
icon = self.icon
if Notify is not None:
notice = self.notifier.Notification.new(title, message, icon)
else:
notice = notify2.Notification(title, message, icon)
notice.set_hint_string('x-canonical-append', '')
try:
notice.show()
except:
pass
|
<commit_before>from dbus.exceptions import DBusException
try:
import gi
gi.require_version('Notify', '0.7')
from gi.repository import Notify
except (ImportError, AttributeError):
from scudcloud import notify2
Notify = None
class Notifier(object):
def __init__(self, app_name, icon):
self.icon = icon
try:
if Notify is not None:
Notify.init(app_name)
self.notifier = Notify
else:
notify2.init(app_name)
self.notifier = notify2
self.enabled = True
except DBusException:
print("WARNING: No notification daemon found! "
"Notifications will be ignored.")
self.enabled = False
def notify(self, title, message, icon=None):
if not self.enabled:
return
if icon is None:
icon = self.icon
if Notify is not None:
notice = self.notifier.Notification.new(title, message, icon)
else:
notice = notify2.Notification(title, message, icon)
notice.set_hint_string('x-canonical-append', '')
try:
notice.show()
except:
pass
<commit_msg>Allow ValueError as a notify exception<commit_after>from dbus.exceptions import DBusException
try:
import gi
gi.require_version('Notify', '0.7')
from gi.repository import Notify
except (ImportError, AttributeError, ValueError):
from scudcloud import notify2
Notify = None
class Notifier(object):
def __init__(self, app_name, icon):
self.icon = icon
try:
if Notify is not None:
Notify.init(app_name)
self.notifier = Notify
else:
notify2.init(app_name)
self.notifier = notify2
self.enabled = True
except DBusException:
print("WARNING: No notification daemon found! "
"Notifications will be ignored.")
self.enabled = False
def notify(self, title, message, icon=None):
if not self.enabled:
return
if icon is None:
icon = self.icon
if Notify is not None:
notice = self.notifier.Notification.new(title, message, icon)
else:
notice = notify2.Notification(title, message, icon)
notice.set_hint_string('x-canonical-append', '')
try:
notice.show()
except:
pass
|
c8429ec00772455c981ebb799f0c87de55bda64e
|
django_fixmystreet/backoffice/forms.py
|
django_fixmystreet/backoffice/forms.py
|
from django import forms
from django_fixmystreet.fixmystreet.models import FMSUser, getLoggedInUserId
from django.contrib.auth.models import User
from django.conf import settings
from django.utils.translation import ugettext_lazy
from django.contrib.sessions.models import Session
class ManagersChoiceField (forms.fields.ChoiceField):
def __init__(self, *args, **kwargs):
# assemble the opt groups.
choices = []
choices.append(('', ugettext_lazy("Select a manager")))
currentUserOrganisationId = FMSUser.objects.get(pk=getLoggedInUserId(Session.objects.all()[0].session_key)).organisation
managers = FMSUser.objects.filter(manager=True)
managers = managers.filter(organisation_id=currentUserOrganisationId)
for manager in managers:
choices.append((manager.pk,manager.first_name+manager.last_name))
super(ManagersChoiceField,self).__init__(choices,*args,**kwargs)
def clean(self, value):
super(ManagersChoiceField,self).clean(value)
try:
model = FMSUser.objects.get(pk=value)
except FMSUser.DoesNotExist:
raise ValidationError(self.error_messages['invalid_choice'])
return model
class ManagersListForm(forms.Form):
manager=ManagersChoiceField(label="")
|
from django import forms
from django_fixmystreet.fixmystreet.models import FMSUser, getLoggedInUserId
from django.contrib.auth.models import User
from django.conf import settings
from django.utils.translation import ugettext_lazy
from django.contrib.sessions.models import Session
from django.contrib.auth.decorators import login_required
class ManagersChoiceField (forms.fields.ChoiceField):
def __init__(self, *args, **kwargs):
choices = []
choices.append(('', ugettext_lazy("Select a manager")))
currentUserOrganisationId = 1
if Session.objects.all()[0].session_key:
currentUserOrganisationId = FMSUser.objects.get(pk=getLoggedInUserId(Session.objects.all()[0].session_key)).organisation
managers = FMSUser.objects.filter(manager=True)
managers = managers.filter(organisation_id=currentUserOrganisationId)
for manager in managers:
choices.append((manager.pk,manager.first_name+manager.last_name))
super(ManagersChoiceField,self).__init__(choices,*args,**kwargs)
def clean(self, value):
super(ManagersChoiceField,self).clean(value)
try:
model = FMSUser.objects.get(pk=value)
except FMSUser.DoesNotExist:
raise ValidationError(self.error_messages['invalid_choice'])
return model
class ManagersListForm(forms.Form):
manager=ManagersChoiceField(label="")
|
Fix user not defined error for not logged in users
|
Fix user not defined error for not logged in users
|
Python
|
agpl-3.0
|
IMIO/django-fixmystreet,IMIO/django-fixmystreet,IMIO/django-fixmystreet,IMIO/django-fixmystreet
|
from django import forms
from django_fixmystreet.fixmystreet.models import FMSUser, getLoggedInUserId
from django.contrib.auth.models import User
from django.conf import settings
from django.utils.translation import ugettext_lazy
from django.contrib.sessions.models import Session
class ManagersChoiceField (forms.fields.ChoiceField):
def __init__(self, *args, **kwargs):
# assemble the opt groups.
choices = []
choices.append(('', ugettext_lazy("Select a manager")))
currentUserOrganisationId = FMSUser.objects.get(pk=getLoggedInUserId(Session.objects.all()[0].session_key)).organisation
managers = FMSUser.objects.filter(manager=True)
managers = managers.filter(organisation_id=currentUserOrganisationId)
for manager in managers:
choices.append((manager.pk,manager.first_name+manager.last_name))
super(ManagersChoiceField,self).__init__(choices,*args,**kwargs)
def clean(self, value):
super(ManagersChoiceField,self).clean(value)
try:
model = FMSUser.objects.get(pk=value)
except FMSUser.DoesNotExist:
raise ValidationError(self.error_messages['invalid_choice'])
return model
class ManagersListForm(forms.Form):
manager=ManagersChoiceField(label="")Fix user not defined error for not logged in users
|
from django import forms
from django_fixmystreet.fixmystreet.models import FMSUser, getLoggedInUserId
from django.contrib.auth.models import User
from django.conf import settings
from django.utils.translation import ugettext_lazy
from django.contrib.sessions.models import Session
from django.contrib.auth.decorators import login_required
class ManagersChoiceField (forms.fields.ChoiceField):
def __init__(self, *args, **kwargs):
choices = []
choices.append(('', ugettext_lazy("Select a manager")))
currentUserOrganisationId = 1
if Session.objects.all()[0].session_key:
currentUserOrganisationId = FMSUser.objects.get(pk=getLoggedInUserId(Session.objects.all()[0].session_key)).organisation
managers = FMSUser.objects.filter(manager=True)
managers = managers.filter(organisation_id=currentUserOrganisationId)
for manager in managers:
choices.append((manager.pk,manager.first_name+manager.last_name))
super(ManagersChoiceField,self).__init__(choices,*args,**kwargs)
def clean(self, value):
super(ManagersChoiceField,self).clean(value)
try:
model = FMSUser.objects.get(pk=value)
except FMSUser.DoesNotExist:
raise ValidationError(self.error_messages['invalid_choice'])
return model
class ManagersListForm(forms.Form):
manager=ManagersChoiceField(label="")
|
<commit_before>from django import forms
from django_fixmystreet.fixmystreet.models import FMSUser, getLoggedInUserId
from django.contrib.auth.models import User
from django.conf import settings
from django.utils.translation import ugettext_lazy
from django.contrib.sessions.models import Session
class ManagersChoiceField (forms.fields.ChoiceField):
def __init__(self, *args, **kwargs):
# assemble the opt groups.
choices = []
choices.append(('', ugettext_lazy("Select a manager")))
currentUserOrganisationId = FMSUser.objects.get(pk=getLoggedInUserId(Session.objects.all()[0].session_key)).organisation
managers = FMSUser.objects.filter(manager=True)
managers = managers.filter(organisation_id=currentUserOrganisationId)
for manager in managers:
choices.append((manager.pk,manager.first_name+manager.last_name))
super(ManagersChoiceField,self).__init__(choices,*args,**kwargs)
def clean(self, value):
super(ManagersChoiceField,self).clean(value)
try:
model = FMSUser.objects.get(pk=value)
except FMSUser.DoesNotExist:
raise ValidationError(self.error_messages['invalid_choice'])
return model
class ManagersListForm(forms.Form):
manager=ManagersChoiceField(label="")<commit_msg>Fix user not defined error for not logged in users<commit_after>
|
from django import forms
from django_fixmystreet.fixmystreet.models import FMSUser, getLoggedInUserId
from django.contrib.auth.models import User
from django.conf import settings
from django.utils.translation import ugettext_lazy
from django.contrib.sessions.models import Session
from django.contrib.auth.decorators import login_required
class ManagersChoiceField (forms.fields.ChoiceField):
def __init__(self, *args, **kwargs):
choices = []
choices.append(('', ugettext_lazy("Select a manager")))
currentUserOrganisationId = 1
if Session.objects.all()[0].session_key:
currentUserOrganisationId = FMSUser.objects.get(pk=getLoggedInUserId(Session.objects.all()[0].session_key)).organisation
managers = FMSUser.objects.filter(manager=True)
managers = managers.filter(organisation_id=currentUserOrganisationId)
for manager in managers:
choices.append((manager.pk,manager.first_name+manager.last_name))
super(ManagersChoiceField,self).__init__(choices,*args,**kwargs)
def clean(self, value):
super(ManagersChoiceField,self).clean(value)
try:
model = FMSUser.objects.get(pk=value)
except FMSUser.DoesNotExist:
raise ValidationError(self.error_messages['invalid_choice'])
return model
class ManagersListForm(forms.Form):
manager=ManagersChoiceField(label="")
|
from django import forms
from django_fixmystreet.fixmystreet.models import FMSUser, getLoggedInUserId
from django.contrib.auth.models import User
from django.conf import settings
from django.utils.translation import ugettext_lazy
from django.contrib.sessions.models import Session
class ManagersChoiceField (forms.fields.ChoiceField):
def __init__(self, *args, **kwargs):
# assemble the opt groups.
choices = []
choices.append(('', ugettext_lazy("Select a manager")))
currentUserOrganisationId = FMSUser.objects.get(pk=getLoggedInUserId(Session.objects.all()[0].session_key)).organisation
managers = FMSUser.objects.filter(manager=True)
managers = managers.filter(organisation_id=currentUserOrganisationId)
for manager in managers:
choices.append((manager.pk,manager.first_name+manager.last_name))
super(ManagersChoiceField,self).__init__(choices,*args,**kwargs)
def clean(self, value):
super(ManagersChoiceField,self).clean(value)
try:
model = FMSUser.objects.get(pk=value)
except FMSUser.DoesNotExist:
raise ValidationError(self.error_messages['invalid_choice'])
return model
class ManagersListForm(forms.Form):
manager=ManagersChoiceField(label="")Fix user not defined error for not logged in usersfrom django import forms
from django_fixmystreet.fixmystreet.models import FMSUser, getLoggedInUserId
from django.contrib.auth.models import User
from django.conf import settings
from django.utils.translation import ugettext_lazy
from django.contrib.sessions.models import Session
from django.contrib.auth.decorators import login_required
class ManagersChoiceField (forms.fields.ChoiceField):
def __init__(self, *args, **kwargs):
choices = []
choices.append(('', ugettext_lazy("Select a manager")))
currentUserOrganisationId = 1
if Session.objects.all()[0].session_key:
currentUserOrganisationId = FMSUser.objects.get(pk=getLoggedInUserId(Session.objects.all()[0].session_key)).organisation
managers = FMSUser.objects.filter(manager=True)
managers = managers.filter(organisation_id=currentUserOrganisationId)
for manager in managers:
choices.append((manager.pk,manager.first_name+manager.last_name))
super(ManagersChoiceField,self).__init__(choices,*args,**kwargs)
def clean(self, value):
super(ManagersChoiceField,self).clean(value)
try:
model = FMSUser.objects.get(pk=value)
except FMSUser.DoesNotExist:
raise ValidationError(self.error_messages['invalid_choice'])
return model
class ManagersListForm(forms.Form):
manager=ManagersChoiceField(label="")
|
<commit_before>from django import forms
from django_fixmystreet.fixmystreet.models import FMSUser, getLoggedInUserId
from django.contrib.auth.models import User
from django.conf import settings
from django.utils.translation import ugettext_lazy
from django.contrib.sessions.models import Session
class ManagersChoiceField (forms.fields.ChoiceField):
def __init__(self, *args, **kwargs):
# assemble the opt groups.
choices = []
choices.append(('', ugettext_lazy("Select a manager")))
currentUserOrganisationId = FMSUser.objects.get(pk=getLoggedInUserId(Session.objects.all()[0].session_key)).organisation
managers = FMSUser.objects.filter(manager=True)
managers = managers.filter(organisation_id=currentUserOrganisationId)
for manager in managers:
choices.append((manager.pk,manager.first_name+manager.last_name))
super(ManagersChoiceField,self).__init__(choices,*args,**kwargs)
def clean(self, value):
super(ManagersChoiceField,self).clean(value)
try:
model = FMSUser.objects.get(pk=value)
except FMSUser.DoesNotExist:
raise ValidationError(self.error_messages['invalid_choice'])
return model
class ManagersListForm(forms.Form):
manager=ManagersChoiceField(label="")<commit_msg>Fix user not defined error for not logged in users<commit_after>from django import forms
from django_fixmystreet.fixmystreet.models import FMSUser, getLoggedInUserId
from django.contrib.auth.models import User
from django.conf import settings
from django.utils.translation import ugettext_lazy
from django.contrib.sessions.models import Session
from django.contrib.auth.decorators import login_required
class ManagersChoiceField (forms.fields.ChoiceField):
def __init__(self, *args, **kwargs):
choices = []
choices.append(('', ugettext_lazy("Select a manager")))
currentUserOrganisationId = 1
if Session.objects.all()[0].session_key:
currentUserOrganisationId = FMSUser.objects.get(pk=getLoggedInUserId(Session.objects.all()[0].session_key)).organisation
managers = FMSUser.objects.filter(manager=True)
managers = managers.filter(organisation_id=currentUserOrganisationId)
for manager in managers:
choices.append((manager.pk,manager.first_name+manager.last_name))
super(ManagersChoiceField,self).__init__(choices,*args,**kwargs)
def clean(self, value):
super(ManagersChoiceField,self).clean(value)
try:
model = FMSUser.objects.get(pk=value)
except FMSUser.DoesNotExist:
raise ValidationError(self.error_messages['invalid_choice'])
return model
class ManagersListForm(forms.Form):
manager=ManagersChoiceField(label="")
|
87b6f69fe53e0425dd5321fcecb613f31887c746
|
recipyCommon/libraryversions.py
|
recipyCommon/libraryversions.py
|
import sys
import warnings
def get_version(modulename):
"Return a string containing the module name and the library version."
version = '?'
# Get the root module name (in case we have something like `recipy.open`
# or `matplotlib.pyplot`)
modulename = modulename.split('.')[0]
if modulename in sys.modules:
try:
version = sys.modules[modulename].__version__
except:
pass
try:
version = sys.modules[modulename].version
except:
pass
try:
version = sys.modules[modulename].version.version
except:
pass
try:
version = sys.modules[modulename].VERSION
except:
pass
else:
warnings.warn('requesting version of a module that has not been '
'imported ({})'.format(modulename))
return '{} v{}'.format(modulename, version)
|
import sys
import warnings
def get_version(modulename):
"Return a string containing the module name and the library version."
version = '?'
# Get the root module name (in case we have something like `recipy.open`
# or `matplotlib.pyplot`)
modulename = modulename.split('.')[0]
if modulename in sys.modules:
try:
version = sys.modules[modulename].__version__
except (KeyError, AttributeError):
pass
try:
version = sys.modules[modulename].version
except (KeyError, AttributeError):
pass
try:
version = sys.modules[modulename].version.version
except (KeyError, AttributeError):
pass
try:
version = sys.modules[modulename].VERSION
except (KeyError, AttributeError):
pass
else:
warnings.warn('requesting version of a module that has not been '
'imported ({})'.format(modulename))
return '{} v{}'.format(modulename, version)
|
Add explicit (rather than broad/general) exceptions in get_version
|
Add explicit (rather than broad/general) exceptions in get_version
|
Python
|
apache-2.0
|
recipy/recipy,recipy/recipy
|
import sys
import warnings
def get_version(modulename):
"Return a string containing the module name and the library version."
version = '?'
# Get the root module name (in case we have something like `recipy.open`
# or `matplotlib.pyplot`)
modulename = modulename.split('.')[0]
if modulename in sys.modules:
try:
version = sys.modules[modulename].__version__
except:
pass
try:
version = sys.modules[modulename].version
except:
pass
try:
version = sys.modules[modulename].version.version
except:
pass
try:
version = sys.modules[modulename].VERSION
except:
pass
else:
warnings.warn('requesting version of a module that has not been '
'imported ({})'.format(modulename))
return '{} v{}'.format(modulename, version)
Add explicit (rather than broad/general) exceptions in get_version
|
import sys
import warnings
def get_version(modulename):
"Return a string containing the module name and the library version."
version = '?'
# Get the root module name (in case we have something like `recipy.open`
# or `matplotlib.pyplot`)
modulename = modulename.split('.')[0]
if modulename in sys.modules:
try:
version = sys.modules[modulename].__version__
except (KeyError, AttributeError):
pass
try:
version = sys.modules[modulename].version
except (KeyError, AttributeError):
pass
try:
version = sys.modules[modulename].version.version
except (KeyError, AttributeError):
pass
try:
version = sys.modules[modulename].VERSION
except (KeyError, AttributeError):
pass
else:
warnings.warn('requesting version of a module that has not been '
'imported ({})'.format(modulename))
return '{} v{}'.format(modulename, version)
|
<commit_before>import sys
import warnings
def get_version(modulename):
"Return a string containing the module name and the library version."
version = '?'
# Get the root module name (in case we have something like `recipy.open`
# or `matplotlib.pyplot`)
modulename = modulename.split('.')[0]
if modulename in sys.modules:
try:
version = sys.modules[modulename].__version__
except:
pass
try:
version = sys.modules[modulename].version
except:
pass
try:
version = sys.modules[modulename].version.version
except:
pass
try:
version = sys.modules[modulename].VERSION
except:
pass
else:
warnings.warn('requesting version of a module that has not been '
'imported ({})'.format(modulename))
return '{} v{}'.format(modulename, version)
<commit_msg>Add explicit (rather than broad/general) exceptions in get_version<commit_after>
|
import sys
import warnings
def get_version(modulename):
"Return a string containing the module name and the library version."
version = '?'
# Get the root module name (in case we have something like `recipy.open`
# or `matplotlib.pyplot`)
modulename = modulename.split('.')[0]
if modulename in sys.modules:
try:
version = sys.modules[modulename].__version__
except (KeyError, AttributeError):
pass
try:
version = sys.modules[modulename].version
except (KeyError, AttributeError):
pass
try:
version = sys.modules[modulename].version.version
except (KeyError, AttributeError):
pass
try:
version = sys.modules[modulename].VERSION
except (KeyError, AttributeError):
pass
else:
warnings.warn('requesting version of a module that has not been '
'imported ({})'.format(modulename))
return '{} v{}'.format(modulename, version)
|
import sys
import warnings
def get_version(modulename):
"Return a string containing the module name and the library version."
version = '?'
# Get the root module name (in case we have something like `recipy.open`
# or `matplotlib.pyplot`)
modulename = modulename.split('.')[0]
if modulename in sys.modules:
try:
version = sys.modules[modulename].__version__
except:
pass
try:
version = sys.modules[modulename].version
except:
pass
try:
version = sys.modules[modulename].version.version
except:
pass
try:
version = sys.modules[modulename].VERSION
except:
pass
else:
warnings.warn('requesting version of a module that has not been '
'imported ({})'.format(modulename))
return '{} v{}'.format(modulename, version)
Add explicit (rather than broad/general) exceptions in get_versionimport sys
import warnings
def get_version(modulename):
"Return a string containing the module name and the library version."
version = '?'
# Get the root module name (in case we have something like `recipy.open`
# or `matplotlib.pyplot`)
modulename = modulename.split('.')[0]
if modulename in sys.modules:
try:
version = sys.modules[modulename].__version__
except (KeyError, AttributeError):
pass
try:
version = sys.modules[modulename].version
except (KeyError, AttributeError):
pass
try:
version = sys.modules[modulename].version.version
except (KeyError, AttributeError):
pass
try:
version = sys.modules[modulename].VERSION
except (KeyError, AttributeError):
pass
else:
warnings.warn('requesting version of a module that has not been '
'imported ({})'.format(modulename))
return '{} v{}'.format(modulename, version)
|
<commit_before>import sys
import warnings
def get_version(modulename):
"Return a string containing the module name and the library version."
version = '?'
# Get the root module name (in case we have something like `recipy.open`
# or `matplotlib.pyplot`)
modulename = modulename.split('.')[0]
if modulename in sys.modules:
try:
version = sys.modules[modulename].__version__
except:
pass
try:
version = sys.modules[modulename].version
except:
pass
try:
version = sys.modules[modulename].version.version
except:
pass
try:
version = sys.modules[modulename].VERSION
except:
pass
else:
warnings.warn('requesting version of a module that has not been '
'imported ({})'.format(modulename))
return '{} v{}'.format(modulename, version)
<commit_msg>Add explicit (rather than broad/general) exceptions in get_version<commit_after>import sys
import warnings
def get_version(modulename):
"Return a string containing the module name and the library version."
version = '?'
# Get the root module name (in case we have something like `recipy.open`
# or `matplotlib.pyplot`)
modulename = modulename.split('.')[0]
if modulename in sys.modules:
try:
version = sys.modules[modulename].__version__
except (KeyError, AttributeError):
pass
try:
version = sys.modules[modulename].version
except (KeyError, AttributeError):
pass
try:
version = sys.modules[modulename].version.version
except (KeyError, AttributeError):
pass
try:
version = sys.modules[modulename].VERSION
except (KeyError, AttributeError):
pass
else:
warnings.warn('requesting version of a module that has not been '
'imported ({})'.format(modulename))
return '{} v{}'.format(modulename, version)
|
cdf046191942e490bc0392994373218aef4076e2
|
slash_bot/config.py
|
slash_bot/config.py
|
# coding: utf-8
"""
Created on 2016-08-23
@author: naoey
"""
VERSION = "0.0.3"
BOT_PREFIX = ":"
PATHS = {
"logs_dir": "./../logs/",
"database": "./../slash_bot.db",
"discord_creds": "./../private/discord.json",
"rito_creds": "./../private/rito.json",
"assets": "./../assets/",
}
MODULES = {
"League of Legends": {
"location": "games.lol",
"class": "LeagueOfLegends",
"active": True,
"prefix": "lol",
"config": {
"static_refresh_interval": {
"value": "604800",
"description": "The time interval in seconds before refreshing static data"
}
}
},
"osu!": {
"location": "games.osu.Osu",
"class": "Osu",
"active": False,
"prefix": "osu",
"config": {},
},
"MyAnimeList": {
"location": "anime.mal.MyAnimeList",
"class": "MyAnimeList",
"active": False,
"prefix": "mal",
"config": {},
},
}
API_LIMITS = {
"riot": {
"10": "10",
"600": "500",
}
}
GLOBAL = {
}
DISCORD_STATUS_ITER = [
"procrastination \(^-^)/",
]
|
# coding: utf-8
"""
Created on 2016-08-23
@author: naoey
"""
VERSION = "0.0.3"
BOT_PREFIX = ","
PATHS = {
"logs_dir": "./../logs/",
"database": "./../slash_bot.db",
"discord_creds": "./../private/discord.json",
"rito_creds": "./../private/rito.json",
"assets": "./../assets/",
}
MODULES = {
"League of Legends": {
"location": "games.lol",
"class": "LeagueOfLegends",
"active": True,
"prefix": "lol",
"config": {
"static_refresh_interval": {
"value": "604800",
"description": "The time interval in seconds before refreshing static data"
}
}
},
"osu!": {
"location": "games.osu.Osu",
"class": "Osu",
"active": False,
"prefix": "osu",
"config": {},
},
"MyAnimeList": {
"location": "anime.mal.MyAnimeList",
"class": "MyAnimeList",
"active": False,
"prefix": "mal",
"config": {},
},
}
API_LIMITS = {
"riot": {
"10": "10",
"600": "500",
}
}
GLOBAL = {
}
DISCORD_STATUS_ITER = [
"procrastination \(^-^)/",
]
|
Fix silly prefix change on this branch so that it won't affect master again
|
Fix silly prefix change on this branch so that it won't affect master again
|
Python
|
mit
|
naoey/slash-bot,naoey/slash-bot
|
# coding: utf-8
"""
Created on 2016-08-23
@author: naoey
"""
VERSION = "0.0.3"
BOT_PREFIX = ":"
PATHS = {
"logs_dir": "./../logs/",
"database": "./../slash_bot.db",
"discord_creds": "./../private/discord.json",
"rito_creds": "./../private/rito.json",
"assets": "./../assets/",
}
MODULES = {
"League of Legends": {
"location": "games.lol",
"class": "LeagueOfLegends",
"active": True,
"prefix": "lol",
"config": {
"static_refresh_interval": {
"value": "604800",
"description": "The time interval in seconds before refreshing static data"
}
}
},
"osu!": {
"location": "games.osu.Osu",
"class": "Osu",
"active": False,
"prefix": "osu",
"config": {},
},
"MyAnimeList": {
"location": "anime.mal.MyAnimeList",
"class": "MyAnimeList",
"active": False,
"prefix": "mal",
"config": {},
},
}
API_LIMITS = {
"riot": {
"10": "10",
"600": "500",
}
}
GLOBAL = {
}
DISCORD_STATUS_ITER = [
"procrastination \(^-^)/",
]
Fix silly prefix change on this branch so that it won't affect master again
|
# coding: utf-8
"""
Created on 2016-08-23
@author: naoey
"""
VERSION = "0.0.3"
BOT_PREFIX = ","
PATHS = {
"logs_dir": "./../logs/",
"database": "./../slash_bot.db",
"discord_creds": "./../private/discord.json",
"rito_creds": "./../private/rito.json",
"assets": "./../assets/",
}
MODULES = {
"League of Legends": {
"location": "games.lol",
"class": "LeagueOfLegends",
"active": True,
"prefix": "lol",
"config": {
"static_refresh_interval": {
"value": "604800",
"description": "The time interval in seconds before refreshing static data"
}
}
},
"osu!": {
"location": "games.osu.Osu",
"class": "Osu",
"active": False,
"prefix": "osu",
"config": {},
},
"MyAnimeList": {
"location": "anime.mal.MyAnimeList",
"class": "MyAnimeList",
"active": False,
"prefix": "mal",
"config": {},
},
}
API_LIMITS = {
"riot": {
"10": "10",
"600": "500",
}
}
GLOBAL = {
}
DISCORD_STATUS_ITER = [
"procrastination \(^-^)/",
]
|
<commit_before># coding: utf-8
"""
Created on 2016-08-23
@author: naoey
"""
VERSION = "0.0.3"
BOT_PREFIX = ":"
PATHS = {
"logs_dir": "./../logs/",
"database": "./../slash_bot.db",
"discord_creds": "./../private/discord.json",
"rito_creds": "./../private/rito.json",
"assets": "./../assets/",
}
MODULES = {
"League of Legends": {
"location": "games.lol",
"class": "LeagueOfLegends",
"active": True,
"prefix": "lol",
"config": {
"static_refresh_interval": {
"value": "604800",
"description": "The time interval in seconds before refreshing static data"
}
}
},
"osu!": {
"location": "games.osu.Osu",
"class": "Osu",
"active": False,
"prefix": "osu",
"config": {},
},
"MyAnimeList": {
"location": "anime.mal.MyAnimeList",
"class": "MyAnimeList",
"active": False,
"prefix": "mal",
"config": {},
},
}
API_LIMITS = {
"riot": {
"10": "10",
"600": "500",
}
}
GLOBAL = {
}
DISCORD_STATUS_ITER = [
"procrastination \(^-^)/",
]
<commit_msg>Fix silly prefix change on this branch so that it won't affect master again<commit_after>
|
# coding: utf-8
"""
Created on 2016-08-23
@author: naoey
"""
VERSION = "0.0.3"
BOT_PREFIX = ","
PATHS = {
"logs_dir": "./../logs/",
"database": "./../slash_bot.db",
"discord_creds": "./../private/discord.json",
"rito_creds": "./../private/rito.json",
"assets": "./../assets/",
}
MODULES = {
"League of Legends": {
"location": "games.lol",
"class": "LeagueOfLegends",
"active": True,
"prefix": "lol",
"config": {
"static_refresh_interval": {
"value": "604800",
"description": "The time interval in seconds before refreshing static data"
}
}
},
"osu!": {
"location": "games.osu.Osu",
"class": "Osu",
"active": False,
"prefix": "osu",
"config": {},
},
"MyAnimeList": {
"location": "anime.mal.MyAnimeList",
"class": "MyAnimeList",
"active": False,
"prefix": "mal",
"config": {},
},
}
API_LIMITS = {
"riot": {
"10": "10",
"600": "500",
}
}
GLOBAL = {
}
DISCORD_STATUS_ITER = [
"procrastination \(^-^)/",
]
|
# coding: utf-8
"""
Created on 2016-08-23
@author: naoey
"""
VERSION = "0.0.3"
BOT_PREFIX = ":"
PATHS = {
"logs_dir": "./../logs/",
"database": "./../slash_bot.db",
"discord_creds": "./../private/discord.json",
"rito_creds": "./../private/rito.json",
"assets": "./../assets/",
}
MODULES = {
"League of Legends": {
"location": "games.lol",
"class": "LeagueOfLegends",
"active": True,
"prefix": "lol",
"config": {
"static_refresh_interval": {
"value": "604800",
"description": "The time interval in seconds before refreshing static data"
}
}
},
"osu!": {
"location": "games.osu.Osu",
"class": "Osu",
"active": False,
"prefix": "osu",
"config": {},
},
"MyAnimeList": {
"location": "anime.mal.MyAnimeList",
"class": "MyAnimeList",
"active": False,
"prefix": "mal",
"config": {},
},
}
API_LIMITS = {
"riot": {
"10": "10",
"600": "500",
}
}
GLOBAL = {
}
DISCORD_STATUS_ITER = [
"procrastination \(^-^)/",
]
Fix silly prefix change on this branch so that it won't affect master again# coding: utf-8
"""
Created on 2016-08-23
@author: naoey
"""
VERSION = "0.0.3"
BOT_PREFIX = ","
PATHS = {
"logs_dir": "./../logs/",
"database": "./../slash_bot.db",
"discord_creds": "./../private/discord.json",
"rito_creds": "./../private/rito.json",
"assets": "./../assets/",
}
MODULES = {
"League of Legends": {
"location": "games.lol",
"class": "LeagueOfLegends",
"active": True,
"prefix": "lol",
"config": {
"static_refresh_interval": {
"value": "604800",
"description": "The time interval in seconds before refreshing static data"
}
}
},
"osu!": {
"location": "games.osu.Osu",
"class": "Osu",
"active": False,
"prefix": "osu",
"config": {},
},
"MyAnimeList": {
"location": "anime.mal.MyAnimeList",
"class": "MyAnimeList",
"active": False,
"prefix": "mal",
"config": {},
},
}
API_LIMITS = {
"riot": {
"10": "10",
"600": "500",
}
}
GLOBAL = {
}
DISCORD_STATUS_ITER = [
"procrastination \(^-^)/",
]
|
<commit_before># coding: utf-8
"""
Created on 2016-08-23
@author: naoey
"""
VERSION = "0.0.3"
BOT_PREFIX = ":"
PATHS = {
"logs_dir": "./../logs/",
"database": "./../slash_bot.db",
"discord_creds": "./../private/discord.json",
"rito_creds": "./../private/rito.json",
"assets": "./../assets/",
}
MODULES = {
"League of Legends": {
"location": "games.lol",
"class": "LeagueOfLegends",
"active": True,
"prefix": "lol",
"config": {
"static_refresh_interval": {
"value": "604800",
"description": "The time interval in seconds before refreshing static data"
}
}
},
"osu!": {
"location": "games.osu.Osu",
"class": "Osu",
"active": False,
"prefix": "osu",
"config": {},
},
"MyAnimeList": {
"location": "anime.mal.MyAnimeList",
"class": "MyAnimeList",
"active": False,
"prefix": "mal",
"config": {},
},
}
API_LIMITS = {
"riot": {
"10": "10",
"600": "500",
}
}
GLOBAL = {
}
DISCORD_STATUS_ITER = [
"procrastination \(^-^)/",
]
<commit_msg>Fix silly prefix change on this branch so that it won't affect master again<commit_after># coding: utf-8
"""
Created on 2016-08-23
@author: naoey
"""
VERSION = "0.0.3"
BOT_PREFIX = ","
PATHS = {
"logs_dir": "./../logs/",
"database": "./../slash_bot.db",
"discord_creds": "./../private/discord.json",
"rito_creds": "./../private/rito.json",
"assets": "./../assets/",
}
MODULES = {
"League of Legends": {
"location": "games.lol",
"class": "LeagueOfLegends",
"active": True,
"prefix": "lol",
"config": {
"static_refresh_interval": {
"value": "604800",
"description": "The time interval in seconds before refreshing static data"
}
}
},
"osu!": {
"location": "games.osu.Osu",
"class": "Osu",
"active": False,
"prefix": "osu",
"config": {},
},
"MyAnimeList": {
"location": "anime.mal.MyAnimeList",
"class": "MyAnimeList",
"active": False,
"prefix": "mal",
"config": {},
},
}
API_LIMITS = {
"riot": {
"10": "10",
"600": "500",
}
}
GLOBAL = {
}
DISCORD_STATUS_ITER = [
"procrastination \(^-^)/",
]
|
f9f9f385e4f425da0537680ba6afd2ce81bfb774
|
rembed/test/integration_test.py
|
rembed/test/integration_test.py
|
from hamcrest import *
import pytest
@pytest.mark.xfail
def test_should_get_correct_embedding():
consumer = REmbedConsumer()
embedding = consumer.embed('https://twitter.com/BarackObama/status/266031293945503744')
assert_that(embedding, contains_string('Four more years.'))
|
from rembed import consumer
from hamcrest import *
import pytest
@pytest.mark.xfail
def test_should_get_correct_embedding():
embedding = consumer.embed('https://twitter.com/BarackObama/status/266031293945503744')
assert_that(embedding, contains_string('Four more years.'))
|
Fix import in integration test
|
Fix import in integration test
|
Python
|
mit
|
tino/pyembed,pyembed/pyembed,pyembed/pyembed
|
from hamcrest import *
import pytest
@pytest.mark.xfail
def test_should_get_correct_embedding():
consumer = REmbedConsumer()
embedding = consumer.embed('https://twitter.com/BarackObama/status/266031293945503744')
assert_that(embedding, contains_string('Four more years.'))Fix import in integration test
|
from rembed import consumer
from hamcrest import *
import pytest
@pytest.mark.xfail
def test_should_get_correct_embedding():
embedding = consumer.embed('https://twitter.com/BarackObama/status/266031293945503744')
assert_that(embedding, contains_string('Four more years.'))
|
<commit_before>from hamcrest import *
import pytest
@pytest.mark.xfail
def test_should_get_correct_embedding():
consumer = REmbedConsumer()
embedding = consumer.embed('https://twitter.com/BarackObama/status/266031293945503744')
assert_that(embedding, contains_string('Four more years.'))<commit_msg>Fix import in integration test<commit_after>
|
from rembed import consumer
from hamcrest import *
import pytest
@pytest.mark.xfail
def test_should_get_correct_embedding():
embedding = consumer.embed('https://twitter.com/BarackObama/status/266031293945503744')
assert_that(embedding, contains_string('Four more years.'))
|
from hamcrest import *
import pytest
@pytest.mark.xfail
def test_should_get_correct_embedding():
consumer = REmbedConsumer()
embedding = consumer.embed('https://twitter.com/BarackObama/status/266031293945503744')
assert_that(embedding, contains_string('Four more years.'))Fix import in integration testfrom rembed import consumer
from hamcrest import *
import pytest
@pytest.mark.xfail
def test_should_get_correct_embedding():
embedding = consumer.embed('https://twitter.com/BarackObama/status/266031293945503744')
assert_that(embedding, contains_string('Four more years.'))
|
<commit_before>from hamcrest import *
import pytest
@pytest.mark.xfail
def test_should_get_correct_embedding():
consumer = REmbedConsumer()
embedding = consumer.embed('https://twitter.com/BarackObama/status/266031293945503744')
assert_that(embedding, contains_string('Four more years.'))<commit_msg>Fix import in integration test<commit_after>from rembed import consumer
from hamcrest import *
import pytest
@pytest.mark.xfail
def test_should_get_correct_embedding():
embedding = consumer.embed('https://twitter.com/BarackObama/status/266031293945503744')
assert_that(embedding, contains_string('Four more years.'))
|
7278be28410c111280d4ccb566842419979843d3
|
mla_game/apps/transcript/management/commands/fake_game_one_gameplay.py
|
mla_game/apps/transcript/management/commands/fake_game_one_gameplay.py
|
import random
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from mla_game.apps.accounts.models import Profile
from ...models import (
Transcript, TranscriptPhraseDownvote
)
class Command(BaseCommand):
help = 'Creates random votes for 5 phrases in a random transcript'
def handle(self, *args, **options):
users = User.objects.all()
transcript = Transcript.objects.random_transcript().first()
phrases = transcript.phrases.all()[:5]
for user in users:
profile = Profile.objects.get(user=user)
profile.considered_phrases.add(
*[phrase.pk for phrase in phrases]
)
for phrase in phrases:
for user in users:
if random.choice([True, False]):
TranscriptPhraseDownvote.objects.create(
transcript_phrase=phrase,
user=user
)
|
import random
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from mla_game.apps.accounts.models import Profile
from ...models import (
Transcript, TranscriptPhraseDownvote
)
from ...tasks import update_transcript_stats
class Command(BaseCommand):
help = 'Creates random votes for 5 phrases in a random transcript'
def handle(self, *args, **options):
users = User.objects.all()
transcript = Transcript.objects.random_transcript(in_progress=False).first()
phrases = transcript.phrases.all()[:5]
for user in users:
profile = Profile.objects.get(user=user)
profile.considered_phrases.add(
*[phrase.pk for phrase in phrases]
)
for phrase in phrases:
for user in users:
if random.choice([True, False]):
TranscriptPhraseDownvote.objects.create(
transcript_phrase=phrase,
user=user
)
update_transcript_stats(transcript)
|
Use an actually random transcript; update stats immediately
|
Use an actually random transcript; update stats immediately
|
Python
|
mit
|
WGBH/FixIt,WGBH/FixIt,WGBH/FixIt
|
import random
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from mla_game.apps.accounts.models import Profile
from ...models import (
Transcript, TranscriptPhraseDownvote
)
class Command(BaseCommand):
help = 'Creates random votes for 5 phrases in a random transcript'
def handle(self, *args, **options):
users = User.objects.all()
transcript = Transcript.objects.random_transcript().first()
phrases = transcript.phrases.all()[:5]
for user in users:
profile = Profile.objects.get(user=user)
profile.considered_phrases.add(
*[phrase.pk for phrase in phrases]
)
for phrase in phrases:
for user in users:
if random.choice([True, False]):
TranscriptPhraseDownvote.objects.create(
transcript_phrase=phrase,
user=user
)
Use an actually random transcript; update stats immediately
|
import random
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from mla_game.apps.accounts.models import Profile
from ...models import (
Transcript, TranscriptPhraseDownvote
)
from ...tasks import update_transcript_stats
class Command(BaseCommand):
help = 'Creates random votes for 5 phrases in a random transcript'
def handle(self, *args, **options):
users = User.objects.all()
transcript = Transcript.objects.random_transcript(in_progress=False).first()
phrases = transcript.phrases.all()[:5]
for user in users:
profile = Profile.objects.get(user=user)
profile.considered_phrases.add(
*[phrase.pk for phrase in phrases]
)
for phrase in phrases:
for user in users:
if random.choice([True, False]):
TranscriptPhraseDownvote.objects.create(
transcript_phrase=phrase,
user=user
)
update_transcript_stats(transcript)
|
<commit_before>import random
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from mla_game.apps.accounts.models import Profile
from ...models import (
Transcript, TranscriptPhraseDownvote
)
class Command(BaseCommand):
help = 'Creates random votes for 5 phrases in a random transcript'
def handle(self, *args, **options):
users = User.objects.all()
transcript = Transcript.objects.random_transcript().first()
phrases = transcript.phrases.all()[:5]
for user in users:
profile = Profile.objects.get(user=user)
profile.considered_phrases.add(
*[phrase.pk for phrase in phrases]
)
for phrase in phrases:
for user in users:
if random.choice([True, False]):
TranscriptPhraseDownvote.objects.create(
transcript_phrase=phrase,
user=user
)
<commit_msg>Use an actually random transcript; update stats immediately<commit_after>
|
import random
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from mla_game.apps.accounts.models import Profile
from ...models import (
Transcript, TranscriptPhraseDownvote
)
from ...tasks import update_transcript_stats
class Command(BaseCommand):
help = 'Creates random votes for 5 phrases in a random transcript'
def handle(self, *args, **options):
users = User.objects.all()
transcript = Transcript.objects.random_transcript(in_progress=False).first()
phrases = transcript.phrases.all()[:5]
for user in users:
profile = Profile.objects.get(user=user)
profile.considered_phrases.add(
*[phrase.pk for phrase in phrases]
)
for phrase in phrases:
for user in users:
if random.choice([True, False]):
TranscriptPhraseDownvote.objects.create(
transcript_phrase=phrase,
user=user
)
update_transcript_stats(transcript)
|
import random
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from mla_game.apps.accounts.models import Profile
from ...models import (
Transcript, TranscriptPhraseDownvote
)
class Command(BaseCommand):
help = 'Creates random votes for 5 phrases in a random transcript'
def handle(self, *args, **options):
users = User.objects.all()
transcript = Transcript.objects.random_transcript().first()
phrases = transcript.phrases.all()[:5]
for user in users:
profile = Profile.objects.get(user=user)
profile.considered_phrases.add(
*[phrase.pk for phrase in phrases]
)
for phrase in phrases:
for user in users:
if random.choice([True, False]):
TranscriptPhraseDownvote.objects.create(
transcript_phrase=phrase,
user=user
)
Use an actually random transcript; update stats immediatelyimport random
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from mla_game.apps.accounts.models import Profile
from ...models import (
Transcript, TranscriptPhraseDownvote
)
from ...tasks import update_transcript_stats
class Command(BaseCommand):
help = 'Creates random votes for 5 phrases in a random transcript'
def handle(self, *args, **options):
users = User.objects.all()
transcript = Transcript.objects.random_transcript(in_progress=False).first()
phrases = transcript.phrases.all()[:5]
for user in users:
profile = Profile.objects.get(user=user)
profile.considered_phrases.add(
*[phrase.pk for phrase in phrases]
)
for phrase in phrases:
for user in users:
if random.choice([True, False]):
TranscriptPhraseDownvote.objects.create(
transcript_phrase=phrase,
user=user
)
update_transcript_stats(transcript)
|
<commit_before>import random
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from mla_game.apps.accounts.models import Profile
from ...models import (
Transcript, TranscriptPhraseDownvote
)
class Command(BaseCommand):
help = 'Creates random votes for 5 phrases in a random transcript'
def handle(self, *args, **options):
users = User.objects.all()
transcript = Transcript.objects.random_transcript().first()
phrases = transcript.phrases.all()[:5]
for user in users:
profile = Profile.objects.get(user=user)
profile.considered_phrases.add(
*[phrase.pk for phrase in phrases]
)
for phrase in phrases:
for user in users:
if random.choice([True, False]):
TranscriptPhraseDownvote.objects.create(
transcript_phrase=phrase,
user=user
)
<commit_msg>Use an actually random transcript; update stats immediately<commit_after>import random
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from mla_game.apps.accounts.models import Profile
from ...models import (
Transcript, TranscriptPhraseDownvote
)
from ...tasks import update_transcript_stats
class Command(BaseCommand):
help = 'Creates random votes for 5 phrases in a random transcript'
def handle(self, *args, **options):
users = User.objects.all()
transcript = Transcript.objects.random_transcript(in_progress=False).first()
phrases = transcript.phrases.all()[:5]
for user in users:
profile = Profile.objects.get(user=user)
profile.considered_phrases.add(
*[phrase.pk for phrase in phrases]
)
for phrase in phrases:
for user in users:
if random.choice([True, False]):
TranscriptPhraseDownvote.objects.create(
transcript_phrase=phrase,
user=user
)
update_transcript_stats(transcript)
|
80b05e0cd3d73529d37843d398857289d5717e44
|
wagtail/tests/migrations/0005_auto_20141113_0642.py
|
wagtail/tests/migrations/0005_auto_20141113_0642.py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('tests', '0004_auto_20141008_0420'),
]
operations = [
migrations.AlterField(
model_name='formfield',
name='choices',
field=models.CharField(help_text='Comma separated list of choices. Only applicable in checkboxes, radio and dropdown.', max_length=512, blank=True),
preserve_default=True,
),
migrations.AlterField(
model_name='formfield',
name='default_value',
field=models.CharField(help_text='Default value. Comma separated values supported for checkboxes.', max_length=255, blank=True),
preserve_default=True,
),
]
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('wagtailcore', '0002_initial_data'),
('tests', '0004_auto_20141008_0420'),
]
operations = [
migrations.AlterField(
model_name='formfield',
name='choices',
field=models.CharField(help_text='Comma separated list of choices. Only applicable in checkboxes, radio and dropdown.', max_length=512, blank=True),
preserve_default=True,
),
migrations.AlterField(
model_name='formfield',
name='default_value',
field=models.CharField(help_text='Default value. Comma separated values supported for checkboxes.', max_length=255, blank=True),
preserve_default=True,
),
]
|
Add dependency on wagtailcore migration 0002 (necessary to cleanly merge the other migration 0005 being added in 0.9)
|
Add dependency on wagtailcore migration 0002 (necessary to cleanly merge the other migration 0005 being added in 0.9)
|
Python
|
bsd-3-clause
|
rsalmaso/wagtail,mikedingjan/wagtail,Toshakins/wagtail,dresiu/wagtail,nilnvoid/wagtail,iansprice/wagtail,kurtw/wagtail,takeflight/wagtail,thenewguy/wagtail,dresiu/wagtail,nutztherookie/wagtail,thenewguy/wagtail,mikedingjan/wagtail,mixxorz/wagtail,takeflight/wagtail,torchbox/wagtail,JoshBarr/wagtail,nealtodd/wagtail,jorge-marques/wagtail,takeshineshiro/wagtail,jnns/wagtail,chrxr/wagtail,inonit/wagtail,nrsimha/wagtail,jordij/wagtail,jorge-marques/wagtail,inonit/wagtail,Pennebaker/wagtail,nimasmi/wagtail,thenewguy/wagtail,taedori81/wagtail,tangentlabs/wagtail,benjaoming/wagtail,jnns/wagtail,mjec/wagtail,WQuanfeng/wagtail,nilnvoid/wagtail,m-sanders/wagtail,mixxorz/wagtail,kurtrwall/wagtail,mayapurmedia/wagtail,chrxr/wagtail,kaedroho/wagtail,quru/wagtail,rjsproxy/wagtail,jorge-marques/wagtail,bjesus/wagtail,benjaoming/wagtail,chrxr/wagtail,nutztherookie/wagtail,kaedroho/wagtail,takeshineshiro/wagtail,kaedroho/wagtail,mephizzle/wagtail,timorieber/wagtail,gogobook/wagtail,mjec/wagtail,timorieber/wagtail,kurtrwall/wagtail,rv816/wagtail,kaedroho/wagtail,janusnic/wagtail,gogobook/wagtail,Toshakins/wagtail,nimasmi/wagtail,takeshineshiro/wagtail,Toshakins/wagtail,KimGlazebrook/wagtail-experiment,KimGlazebrook/wagtail-experiment,tangentlabs/wagtail,inonit/wagtail,davecranwell/wagtail,wagtail/wagtail,gogobook/wagtail,darith27/wagtail,wagtail/wagtail,rsalmaso/wagtail,mjec/wagtail,davecranwell/wagtail,chimeno/wagtail,iho/wagtail,jorge-marques/wagtail,gasman/wagtail,quru/wagtail,serzans/wagtail,nutztherookie/wagtail,gasman/wagtail,iho/wagtail,takeshineshiro/wagtail,quru/wagtail,rsalmaso/wagtail,taedori81/wagtail,kurtrwall/wagtail,zerolab/wagtail,Pennebaker/wagtail,taedori81/wagtail,wagtail/wagtail,iansprice/wagtail,kurtw/wagtail,marctc/wagtail,m-sanders/wagtail,nrsimha/wagtail,Toshakins/wagtail,Tivix/wagtail,bjesus/wagtail,nimasmi/wagtail,chimeno/wagtail,nilnvoid/wagtail,chrxr/wagtail,zerolab/wagtail,serzans/wagtail,jordij/wagtail,hamsterbacke23/wagtail,nrsimha/wagtail,quru/wagtail,Pennebaker/wagtail,nilnvoid/wagtail,FlipperPA/wagtail,WQuanfeng/wagtail,jnns/wagtail,serzans/wagtail,rjsproxy/wagtail,timorieber/wagtail,gasman/wagtail,kurtrwall/wagtail,hanpama/wagtail,KimGlazebrook/wagtail-experiment,mayapurmedia/wagtail,FlipperPA/wagtail,marctc/wagtail,kurtw/wagtail,iho/wagtail,tangentlabs/wagtail,FlipperPA/wagtail,Pennebaker/wagtail,zerolab/wagtail,mixxorz/wagtail,iho/wagtail,rjsproxy/wagtail,jnns/wagtail,wagtail/wagtail,rjsproxy/wagtail,timorieber/wagtail,nimasmi/wagtail,mephizzle/wagtail,davecranwell/wagtail,Klaudit/wagtail,taedori81/wagtail,mikedingjan/wagtail,rv816/wagtail,torchbox/wagtail,hanpama/wagtail,stevenewey/wagtail,Klaudit/wagtail,mikedingjan/wagtail,janusnic/wagtail,bjesus/wagtail,darith27/wagtail,takeflight/wagtail,mjec/wagtail,wagtail/wagtail,marctc/wagtail,thenewguy/wagtail,nutztherookie/wagtail,JoshBarr/wagtail,hamsterbacke23/wagtail,JoshBarr/wagtail,nealtodd/wagtail,takeflight/wagtail,stevenewey/wagtail,hamsterbacke23/wagtail,hanpama/wagtail,mephizzle/wagtail,mephizzle/wagtail,davecranwell/wagtail,nealtodd/wagtail,m-sanders/wagtail,WQuanfeng/wagtail,FlipperPA/wagtail,stevenewey/wagtail,torchbox/wagtail,dresiu/wagtail,torchbox/wagtail,mayapurmedia/wagtail,hanpama/wagtail,gasman/wagtail,Tivix/wagtail,chimeno/wagtail,hamsterbacke23/wagtail,janusnic/wagtail,taedori81/wagtail,Tivix/wagtail,rsalmaso/wagtail,iansprice/wagtail,zerolab/wagtail,darith27/wagtail,m-sanders/wagtail,janusnic/wagtail,KimGlazebrook/wagtail-experiment,zerolab/wagtail,chimeno/wagtail,Klaudit/wagtail,benjaoming/wagtail,Tivix/wagtail,dresiu/wagtail,bjesus/wagtail,marctc/wagtail,mixxorz/wagtail,rsalmaso/wagtail,Klaudit/wagtail,JoshBarr/wagtail,kurtw/wagtail,jordij/wagtail,rv816/wagtail,WQuanfeng/wagtail,rv816/wagtail,mixxorz/wagtail,gogobook/wagtail,stevenewey/wagtail,dresiu/wagtail,chimeno/wagtail,jorge-marques/wagtail,thenewguy/wagtail,benjaoming/wagtail,serzans/wagtail,iansprice/wagtail,nealtodd/wagtail,kaedroho/wagtail,mayapurmedia/wagtail,gasman/wagtail,nrsimha/wagtail,inonit/wagtail,tangentlabs/wagtail,darith27/wagtail,jordij/wagtail
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('tests', '0004_auto_20141008_0420'),
]
operations = [
migrations.AlterField(
model_name='formfield',
name='choices',
field=models.CharField(help_text='Comma separated list of choices. Only applicable in checkboxes, radio and dropdown.', max_length=512, blank=True),
preserve_default=True,
),
migrations.AlterField(
model_name='formfield',
name='default_value',
field=models.CharField(help_text='Default value. Comma separated values supported for checkboxes.', max_length=255, blank=True),
preserve_default=True,
),
]
Add dependency on wagtailcore migration 0002 (necessary to cleanly merge the other migration 0005 being added in 0.9)
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('wagtailcore', '0002_initial_data'),
('tests', '0004_auto_20141008_0420'),
]
operations = [
migrations.AlterField(
model_name='formfield',
name='choices',
field=models.CharField(help_text='Comma separated list of choices. Only applicable in checkboxes, radio and dropdown.', max_length=512, blank=True),
preserve_default=True,
),
migrations.AlterField(
model_name='formfield',
name='default_value',
field=models.CharField(help_text='Default value. Comma separated values supported for checkboxes.', max_length=255, blank=True),
preserve_default=True,
),
]
|
<commit_before># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('tests', '0004_auto_20141008_0420'),
]
operations = [
migrations.AlterField(
model_name='formfield',
name='choices',
field=models.CharField(help_text='Comma separated list of choices. Only applicable in checkboxes, radio and dropdown.', max_length=512, blank=True),
preserve_default=True,
),
migrations.AlterField(
model_name='formfield',
name='default_value',
field=models.CharField(help_text='Default value. Comma separated values supported for checkboxes.', max_length=255, blank=True),
preserve_default=True,
),
]
<commit_msg>Add dependency on wagtailcore migration 0002 (necessary to cleanly merge the other migration 0005 being added in 0.9)<commit_after>
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('wagtailcore', '0002_initial_data'),
('tests', '0004_auto_20141008_0420'),
]
operations = [
migrations.AlterField(
model_name='formfield',
name='choices',
field=models.CharField(help_text='Comma separated list of choices. Only applicable in checkboxes, radio and dropdown.', max_length=512, blank=True),
preserve_default=True,
),
migrations.AlterField(
model_name='formfield',
name='default_value',
field=models.CharField(help_text='Default value. Comma separated values supported for checkboxes.', max_length=255, blank=True),
preserve_default=True,
),
]
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('tests', '0004_auto_20141008_0420'),
]
operations = [
migrations.AlterField(
model_name='formfield',
name='choices',
field=models.CharField(help_text='Comma separated list of choices. Only applicable in checkboxes, radio and dropdown.', max_length=512, blank=True),
preserve_default=True,
),
migrations.AlterField(
model_name='formfield',
name='default_value',
field=models.CharField(help_text='Default value. Comma separated values supported for checkboxes.', max_length=255, blank=True),
preserve_default=True,
),
]
Add dependency on wagtailcore migration 0002 (necessary to cleanly merge the other migration 0005 being added in 0.9)# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('wagtailcore', '0002_initial_data'),
('tests', '0004_auto_20141008_0420'),
]
operations = [
migrations.AlterField(
model_name='formfield',
name='choices',
field=models.CharField(help_text='Comma separated list of choices. Only applicable in checkboxes, radio and dropdown.', max_length=512, blank=True),
preserve_default=True,
),
migrations.AlterField(
model_name='formfield',
name='default_value',
field=models.CharField(help_text='Default value. Comma separated values supported for checkboxes.', max_length=255, blank=True),
preserve_default=True,
),
]
|
<commit_before># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('tests', '0004_auto_20141008_0420'),
]
operations = [
migrations.AlterField(
model_name='formfield',
name='choices',
field=models.CharField(help_text='Comma separated list of choices. Only applicable in checkboxes, radio and dropdown.', max_length=512, blank=True),
preserve_default=True,
),
migrations.AlterField(
model_name='formfield',
name='default_value',
field=models.CharField(help_text='Default value. Comma separated values supported for checkboxes.', max_length=255, blank=True),
preserve_default=True,
),
]
<commit_msg>Add dependency on wagtailcore migration 0002 (necessary to cleanly merge the other migration 0005 being added in 0.9)<commit_after># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('wagtailcore', '0002_initial_data'),
('tests', '0004_auto_20141008_0420'),
]
operations = [
migrations.AlterField(
model_name='formfield',
name='choices',
field=models.CharField(help_text='Comma separated list of choices. Only applicable in checkboxes, radio and dropdown.', max_length=512, blank=True),
preserve_default=True,
),
migrations.AlterField(
model_name='formfield',
name='default_value',
field=models.CharField(help_text='Default value. Comma separated values supported for checkboxes.', max_length=255, blank=True),
preserve_default=True,
),
]
|
79928051b481f9e19b45c8eebcf8ae2ff229b342
|
opps/boxes/models.py
|
opps/boxes/models.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#from django.conf import settings
#from django.utils.importlib import import_module
from django.db import models
from django.utils.translation import ugettext_lazy as _
from opps.core.models import Publishable, BaseBox
"""
from django.db.models import get_model
model = get_model('myapp', 'modelA')
model.objects.filter(**kwargs)
(Pdb) models.get_models()[15]._meta.local_fields[0].verbose_name
u'ID'
(Pdb) models.get_models()[15]._meta.local_fields[0].name
u'id'
"""
try:
OPPS_APPS = tuple([(app._meta.app_label, u"{0} - {1}".format(
app._meta.app_label, app._meta.object_name))
for app in models.get_models() if 'opps.' in app.__module__])
except ImportError:
OPPS_APPS = tuple([])
class QuerySet(Publishable):
name = models.CharField(_(u"Dynamic queryset name"), max_length=140)
slug = models.SlugField(
_(u"Slug"),
db_index=True,
max_length=150,
unique=True,
)
model = models.CharField(_(u'Model'), max_length=150, choices=OPPS_APPS)
order = models.CharField(_('Order'), max_length=2, choices=(
('-', 'DESC'), ('', 'ASC')))
class DynamicBox(BaseBox):
dynamicqueryset = models.ForeignKey(
'boxes.QuerySet',
verbose_name=_(u'Query Set')
)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#from django.conf import settings
#from django.utils.importlib import import_module
from django.db import models
from django.utils.translation import ugettext_lazy as _
from opps.core.models import Publishable, BaseBox
try:
OPPS_APPS = tuple([(u"{0}.{1}".format(
app._meta.app_label, app._meta.object_name), u"{0} - {1}".format(
app._meta.app_label, app._meta.object_name))
for app in models.get_models() if 'opps.' in app.__module__])
except ImportError:
OPPS_APPS = tuple([])
class QuerySet(Publishable):
name = models.CharField(_(u"Dynamic queryset name"), max_length=140)
slug = models.SlugField(
_(u"Slug"),
db_index=True,
max_length=150,
unique=True,
)
model = models.CharField(_(u'Model'), max_length=150, choices=OPPS_APPS)
limit = models.PositiveIntegerField(_(u'Limit'))
order = models.CharField(_('Order'), max_length=1, choices=(
('-', 'DESC'), ('+', 'ASC')))
class DynamicBox(BaseBox):
dynamicqueryset = models.ForeignKey(
'boxes.QuerySet',
verbose_name=_(u'Query Set')
)
|
Fix OPPS_APPS, get object_name in dropdawn
|
Fix OPPS_APPS, get object_name in dropdawn
|
Python
|
mit
|
YACOWS/opps,YACOWS/opps,jeanmask/opps,opps/opps,jeanmask/opps,opps/opps,YACOWS/opps,jeanmask/opps,williamroot/opps,opps/opps,williamroot/opps,williamroot/opps,jeanmask/opps,YACOWS/opps,opps/opps,williamroot/opps
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#from django.conf import settings
#from django.utils.importlib import import_module
from django.db import models
from django.utils.translation import ugettext_lazy as _
from opps.core.models import Publishable, BaseBox
"""
from django.db.models import get_model
model = get_model('myapp', 'modelA')
model.objects.filter(**kwargs)
(Pdb) models.get_models()[15]._meta.local_fields[0].verbose_name
u'ID'
(Pdb) models.get_models()[15]._meta.local_fields[0].name
u'id'
"""
try:
OPPS_APPS = tuple([(app._meta.app_label, u"{0} - {1}".format(
app._meta.app_label, app._meta.object_name))
for app in models.get_models() if 'opps.' in app.__module__])
except ImportError:
OPPS_APPS = tuple([])
class QuerySet(Publishable):
name = models.CharField(_(u"Dynamic queryset name"), max_length=140)
slug = models.SlugField(
_(u"Slug"),
db_index=True,
max_length=150,
unique=True,
)
model = models.CharField(_(u'Model'), max_length=150, choices=OPPS_APPS)
order = models.CharField(_('Order'), max_length=2, choices=(
('-', 'DESC'), ('', 'ASC')))
class DynamicBox(BaseBox):
dynamicqueryset = models.ForeignKey(
'boxes.QuerySet',
verbose_name=_(u'Query Set')
)
Fix OPPS_APPS, get object_name in dropdawn
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#from django.conf import settings
#from django.utils.importlib import import_module
from django.db import models
from django.utils.translation import ugettext_lazy as _
from opps.core.models import Publishable, BaseBox
try:
OPPS_APPS = tuple([(u"{0}.{1}".format(
app._meta.app_label, app._meta.object_name), u"{0} - {1}".format(
app._meta.app_label, app._meta.object_name))
for app in models.get_models() if 'opps.' in app.__module__])
except ImportError:
OPPS_APPS = tuple([])
class QuerySet(Publishable):
name = models.CharField(_(u"Dynamic queryset name"), max_length=140)
slug = models.SlugField(
_(u"Slug"),
db_index=True,
max_length=150,
unique=True,
)
model = models.CharField(_(u'Model'), max_length=150, choices=OPPS_APPS)
limit = models.PositiveIntegerField(_(u'Limit'))
order = models.CharField(_('Order'), max_length=1, choices=(
('-', 'DESC'), ('+', 'ASC')))
class DynamicBox(BaseBox):
dynamicqueryset = models.ForeignKey(
'boxes.QuerySet',
verbose_name=_(u'Query Set')
)
|
<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
#from django.conf import settings
#from django.utils.importlib import import_module
from django.db import models
from django.utils.translation import ugettext_lazy as _
from opps.core.models import Publishable, BaseBox
"""
from django.db.models import get_model
model = get_model('myapp', 'modelA')
model.objects.filter(**kwargs)
(Pdb) models.get_models()[15]._meta.local_fields[0].verbose_name
u'ID'
(Pdb) models.get_models()[15]._meta.local_fields[0].name
u'id'
"""
try:
OPPS_APPS = tuple([(app._meta.app_label, u"{0} - {1}".format(
app._meta.app_label, app._meta.object_name))
for app in models.get_models() if 'opps.' in app.__module__])
except ImportError:
OPPS_APPS = tuple([])
class QuerySet(Publishable):
name = models.CharField(_(u"Dynamic queryset name"), max_length=140)
slug = models.SlugField(
_(u"Slug"),
db_index=True,
max_length=150,
unique=True,
)
model = models.CharField(_(u'Model'), max_length=150, choices=OPPS_APPS)
order = models.CharField(_('Order'), max_length=2, choices=(
('-', 'DESC'), ('', 'ASC')))
class DynamicBox(BaseBox):
dynamicqueryset = models.ForeignKey(
'boxes.QuerySet',
verbose_name=_(u'Query Set')
)
<commit_msg>Fix OPPS_APPS, get object_name in dropdawn<commit_after>
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#from django.conf import settings
#from django.utils.importlib import import_module
from django.db import models
from django.utils.translation import ugettext_lazy as _
from opps.core.models import Publishable, BaseBox
try:
OPPS_APPS = tuple([(u"{0}.{1}".format(
app._meta.app_label, app._meta.object_name), u"{0} - {1}".format(
app._meta.app_label, app._meta.object_name))
for app in models.get_models() if 'opps.' in app.__module__])
except ImportError:
OPPS_APPS = tuple([])
class QuerySet(Publishable):
name = models.CharField(_(u"Dynamic queryset name"), max_length=140)
slug = models.SlugField(
_(u"Slug"),
db_index=True,
max_length=150,
unique=True,
)
model = models.CharField(_(u'Model'), max_length=150, choices=OPPS_APPS)
limit = models.PositiveIntegerField(_(u'Limit'))
order = models.CharField(_('Order'), max_length=1, choices=(
('-', 'DESC'), ('+', 'ASC')))
class DynamicBox(BaseBox):
dynamicqueryset = models.ForeignKey(
'boxes.QuerySet',
verbose_name=_(u'Query Set')
)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#from django.conf import settings
#from django.utils.importlib import import_module
from django.db import models
from django.utils.translation import ugettext_lazy as _
from opps.core.models import Publishable, BaseBox
"""
from django.db.models import get_model
model = get_model('myapp', 'modelA')
model.objects.filter(**kwargs)
(Pdb) models.get_models()[15]._meta.local_fields[0].verbose_name
u'ID'
(Pdb) models.get_models()[15]._meta.local_fields[0].name
u'id'
"""
try:
OPPS_APPS = tuple([(app._meta.app_label, u"{0} - {1}".format(
app._meta.app_label, app._meta.object_name))
for app in models.get_models() if 'opps.' in app.__module__])
except ImportError:
OPPS_APPS = tuple([])
class QuerySet(Publishable):
name = models.CharField(_(u"Dynamic queryset name"), max_length=140)
slug = models.SlugField(
_(u"Slug"),
db_index=True,
max_length=150,
unique=True,
)
model = models.CharField(_(u'Model'), max_length=150, choices=OPPS_APPS)
order = models.CharField(_('Order'), max_length=2, choices=(
('-', 'DESC'), ('', 'ASC')))
class DynamicBox(BaseBox):
dynamicqueryset = models.ForeignKey(
'boxes.QuerySet',
verbose_name=_(u'Query Set')
)
Fix OPPS_APPS, get object_name in dropdawn#!/usr/bin/env python
# -*- coding: utf-8 -*-
#from django.conf import settings
#from django.utils.importlib import import_module
from django.db import models
from django.utils.translation import ugettext_lazy as _
from opps.core.models import Publishable, BaseBox
try:
OPPS_APPS = tuple([(u"{0}.{1}".format(
app._meta.app_label, app._meta.object_name), u"{0} - {1}".format(
app._meta.app_label, app._meta.object_name))
for app in models.get_models() if 'opps.' in app.__module__])
except ImportError:
OPPS_APPS = tuple([])
class QuerySet(Publishable):
name = models.CharField(_(u"Dynamic queryset name"), max_length=140)
slug = models.SlugField(
_(u"Slug"),
db_index=True,
max_length=150,
unique=True,
)
model = models.CharField(_(u'Model'), max_length=150, choices=OPPS_APPS)
limit = models.PositiveIntegerField(_(u'Limit'))
order = models.CharField(_('Order'), max_length=1, choices=(
('-', 'DESC'), ('+', 'ASC')))
class DynamicBox(BaseBox):
dynamicqueryset = models.ForeignKey(
'boxes.QuerySet',
verbose_name=_(u'Query Set')
)
|
<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
#from django.conf import settings
#from django.utils.importlib import import_module
from django.db import models
from django.utils.translation import ugettext_lazy as _
from opps.core.models import Publishable, BaseBox
"""
from django.db.models import get_model
model = get_model('myapp', 'modelA')
model.objects.filter(**kwargs)
(Pdb) models.get_models()[15]._meta.local_fields[0].verbose_name
u'ID'
(Pdb) models.get_models()[15]._meta.local_fields[0].name
u'id'
"""
try:
OPPS_APPS = tuple([(app._meta.app_label, u"{0} - {1}".format(
app._meta.app_label, app._meta.object_name))
for app in models.get_models() if 'opps.' in app.__module__])
except ImportError:
OPPS_APPS = tuple([])
class QuerySet(Publishable):
name = models.CharField(_(u"Dynamic queryset name"), max_length=140)
slug = models.SlugField(
_(u"Slug"),
db_index=True,
max_length=150,
unique=True,
)
model = models.CharField(_(u'Model'), max_length=150, choices=OPPS_APPS)
order = models.CharField(_('Order'), max_length=2, choices=(
('-', 'DESC'), ('', 'ASC')))
class DynamicBox(BaseBox):
dynamicqueryset = models.ForeignKey(
'boxes.QuerySet',
verbose_name=_(u'Query Set')
)
<commit_msg>Fix OPPS_APPS, get object_name in dropdawn<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
#from django.conf import settings
#from django.utils.importlib import import_module
from django.db import models
from django.utils.translation import ugettext_lazy as _
from opps.core.models import Publishable, BaseBox
try:
OPPS_APPS = tuple([(u"{0}.{1}".format(
app._meta.app_label, app._meta.object_name), u"{0} - {1}".format(
app._meta.app_label, app._meta.object_name))
for app in models.get_models() if 'opps.' in app.__module__])
except ImportError:
OPPS_APPS = tuple([])
class QuerySet(Publishable):
name = models.CharField(_(u"Dynamic queryset name"), max_length=140)
slug = models.SlugField(
_(u"Slug"),
db_index=True,
max_length=150,
unique=True,
)
model = models.CharField(_(u'Model'), max_length=150, choices=OPPS_APPS)
limit = models.PositiveIntegerField(_(u'Limit'))
order = models.CharField(_('Order'), max_length=1, choices=(
('-', 'DESC'), ('+', 'ASC')))
class DynamicBox(BaseBox):
dynamicqueryset = models.ForeignKey(
'boxes.QuerySet',
verbose_name=_(u'Query Set')
)
|
d2be94715baa7e5b8e9af11dbeb48635e3eafea7
|
fluent_contents/plugins/text/models.py
|
fluent_contents/plugins/text/models.py
|
from django.db import models
from django.utils.html import strip_tags
from django.utils.text import truncate_words
from django.utils.translation import ugettext_lazy as _
from fluent_contents.models import ContentItem
from fluent_contents.plugins.text import appsettings
from django_wysiwyg.utils import clean_html, sanitize_html
class TextItem(ContentItem):
"""
A snippet of HTML text to display on a page.
"""
text = models.TextField(_('text'), blank=True)
class Meta:
verbose_name = _('Text item')
verbose_name_plural = _('Text items')
def __unicode__(self):
return truncate_words(strip_tags(self.text), 20)
def save(self, *args, **kwargs):
# Cleanup the HTML if requested
if appsettings.FLUENT_TEXT_CLEAN_HTML:
self.text = clean_html(self.text)
if appsettings.FLUENT_TEXT_SANITIZE_HTML:
self.text = sanitize_html(self.text)
super(ContentItem, self).save(*args, **kwargs)
|
from django.db import models
from django.utils.html import strip_tags
from django.utils.text import truncate_words
from django.utils.translation import ugettext_lazy as _
from fluent_contents.models import ContentItem
from fluent_contents.plugins.text import appsettings
from django_wysiwyg.utils import clean_html, sanitize_html
class TextItem(ContentItem):
"""
A snippet of HTML text to display on a page.
"""
text = models.TextField(_('text'), blank=True)
class Meta:
verbose_name = _('Text item')
verbose_name_plural = _('Text items')
def __unicode__(self):
return truncate_words(strip_tags(self.text), 20)
def save(self, *args, **kwargs):
# Cleanup the HTML if requested
if appsettings.FLUENT_TEXT_CLEAN_HTML:
self.text = clean_html(self.text)
if appsettings.FLUENT_TEXT_SANITIZE_HTML:
self.text = sanitize_html(self.text)
super(TextItem, self).save(*args, **kwargs)
|
Fix cache clearing with TextItem plugins
|
Fix cache clearing with TextItem plugins
|
Python
|
apache-2.0
|
jpotterm/django-fluent-contents,pombredanne/django-fluent-contents,pombredanne/django-fluent-contents,django-fluent/django-fluent-contents,django-fluent/django-fluent-contents,pombredanne/django-fluent-contents,ixc/django-fluent-contents,ixc/django-fluent-contents,edoburu/django-fluent-contents,ixc/django-fluent-contents,jpotterm/django-fluent-contents,edoburu/django-fluent-contents,edoburu/django-fluent-contents,jpotterm/django-fluent-contents,django-fluent/django-fluent-contents
|
from django.db import models
from django.utils.html import strip_tags
from django.utils.text import truncate_words
from django.utils.translation import ugettext_lazy as _
from fluent_contents.models import ContentItem
from fluent_contents.plugins.text import appsettings
from django_wysiwyg.utils import clean_html, sanitize_html
class TextItem(ContentItem):
"""
A snippet of HTML text to display on a page.
"""
text = models.TextField(_('text'), blank=True)
class Meta:
verbose_name = _('Text item')
verbose_name_plural = _('Text items')
def __unicode__(self):
return truncate_words(strip_tags(self.text), 20)
def save(self, *args, **kwargs):
# Cleanup the HTML if requested
if appsettings.FLUENT_TEXT_CLEAN_HTML:
self.text = clean_html(self.text)
if appsettings.FLUENT_TEXT_SANITIZE_HTML:
self.text = sanitize_html(self.text)
super(ContentItem, self).save(*args, **kwargs)
Fix cache clearing with TextItem plugins
|
from django.db import models
from django.utils.html import strip_tags
from django.utils.text import truncate_words
from django.utils.translation import ugettext_lazy as _
from fluent_contents.models import ContentItem
from fluent_contents.plugins.text import appsettings
from django_wysiwyg.utils import clean_html, sanitize_html
class TextItem(ContentItem):
"""
A snippet of HTML text to display on a page.
"""
text = models.TextField(_('text'), blank=True)
class Meta:
verbose_name = _('Text item')
verbose_name_plural = _('Text items')
def __unicode__(self):
return truncate_words(strip_tags(self.text), 20)
def save(self, *args, **kwargs):
# Cleanup the HTML if requested
if appsettings.FLUENT_TEXT_CLEAN_HTML:
self.text = clean_html(self.text)
if appsettings.FLUENT_TEXT_SANITIZE_HTML:
self.text = sanitize_html(self.text)
super(TextItem, self).save(*args, **kwargs)
|
<commit_before>from django.db import models
from django.utils.html import strip_tags
from django.utils.text import truncate_words
from django.utils.translation import ugettext_lazy as _
from fluent_contents.models import ContentItem
from fluent_contents.plugins.text import appsettings
from django_wysiwyg.utils import clean_html, sanitize_html
class TextItem(ContentItem):
"""
A snippet of HTML text to display on a page.
"""
text = models.TextField(_('text'), blank=True)
class Meta:
verbose_name = _('Text item')
verbose_name_plural = _('Text items')
def __unicode__(self):
return truncate_words(strip_tags(self.text), 20)
def save(self, *args, **kwargs):
# Cleanup the HTML if requested
if appsettings.FLUENT_TEXT_CLEAN_HTML:
self.text = clean_html(self.text)
if appsettings.FLUENT_TEXT_SANITIZE_HTML:
self.text = sanitize_html(self.text)
super(ContentItem, self).save(*args, **kwargs)
<commit_msg>Fix cache clearing with TextItem plugins<commit_after>
|
from django.db import models
from django.utils.html import strip_tags
from django.utils.text import truncate_words
from django.utils.translation import ugettext_lazy as _
from fluent_contents.models import ContentItem
from fluent_contents.plugins.text import appsettings
from django_wysiwyg.utils import clean_html, sanitize_html
class TextItem(ContentItem):
"""
A snippet of HTML text to display on a page.
"""
text = models.TextField(_('text'), blank=True)
class Meta:
verbose_name = _('Text item')
verbose_name_plural = _('Text items')
def __unicode__(self):
return truncate_words(strip_tags(self.text), 20)
def save(self, *args, **kwargs):
# Cleanup the HTML if requested
if appsettings.FLUENT_TEXT_CLEAN_HTML:
self.text = clean_html(self.text)
if appsettings.FLUENT_TEXT_SANITIZE_HTML:
self.text = sanitize_html(self.text)
super(TextItem, self).save(*args, **kwargs)
|
from django.db import models
from django.utils.html import strip_tags
from django.utils.text import truncate_words
from django.utils.translation import ugettext_lazy as _
from fluent_contents.models import ContentItem
from fluent_contents.plugins.text import appsettings
from django_wysiwyg.utils import clean_html, sanitize_html
class TextItem(ContentItem):
"""
A snippet of HTML text to display on a page.
"""
text = models.TextField(_('text'), blank=True)
class Meta:
verbose_name = _('Text item')
verbose_name_plural = _('Text items')
def __unicode__(self):
return truncate_words(strip_tags(self.text), 20)
def save(self, *args, **kwargs):
# Cleanup the HTML if requested
if appsettings.FLUENT_TEXT_CLEAN_HTML:
self.text = clean_html(self.text)
if appsettings.FLUENT_TEXT_SANITIZE_HTML:
self.text = sanitize_html(self.text)
super(ContentItem, self).save(*args, **kwargs)
Fix cache clearing with TextItem pluginsfrom django.db import models
from django.utils.html import strip_tags
from django.utils.text import truncate_words
from django.utils.translation import ugettext_lazy as _
from fluent_contents.models import ContentItem
from fluent_contents.plugins.text import appsettings
from django_wysiwyg.utils import clean_html, sanitize_html
class TextItem(ContentItem):
"""
A snippet of HTML text to display on a page.
"""
text = models.TextField(_('text'), blank=True)
class Meta:
verbose_name = _('Text item')
verbose_name_plural = _('Text items')
def __unicode__(self):
return truncate_words(strip_tags(self.text), 20)
def save(self, *args, **kwargs):
# Cleanup the HTML if requested
if appsettings.FLUENT_TEXT_CLEAN_HTML:
self.text = clean_html(self.text)
if appsettings.FLUENT_TEXT_SANITIZE_HTML:
self.text = sanitize_html(self.text)
super(TextItem, self).save(*args, **kwargs)
|
<commit_before>from django.db import models
from django.utils.html import strip_tags
from django.utils.text import truncate_words
from django.utils.translation import ugettext_lazy as _
from fluent_contents.models import ContentItem
from fluent_contents.plugins.text import appsettings
from django_wysiwyg.utils import clean_html, sanitize_html
class TextItem(ContentItem):
"""
A snippet of HTML text to display on a page.
"""
text = models.TextField(_('text'), blank=True)
class Meta:
verbose_name = _('Text item')
verbose_name_plural = _('Text items')
def __unicode__(self):
return truncate_words(strip_tags(self.text), 20)
def save(self, *args, **kwargs):
# Cleanup the HTML if requested
if appsettings.FLUENT_TEXT_CLEAN_HTML:
self.text = clean_html(self.text)
if appsettings.FLUENT_TEXT_SANITIZE_HTML:
self.text = sanitize_html(self.text)
super(ContentItem, self).save(*args, **kwargs)
<commit_msg>Fix cache clearing with TextItem plugins<commit_after>from django.db import models
from django.utils.html import strip_tags
from django.utils.text import truncate_words
from django.utils.translation import ugettext_lazy as _
from fluent_contents.models import ContentItem
from fluent_contents.plugins.text import appsettings
from django_wysiwyg.utils import clean_html, sanitize_html
class TextItem(ContentItem):
"""
A snippet of HTML text to display on a page.
"""
text = models.TextField(_('text'), blank=True)
class Meta:
verbose_name = _('Text item')
verbose_name_plural = _('Text items')
def __unicode__(self):
return truncate_words(strip_tags(self.text), 20)
def save(self, *args, **kwargs):
# Cleanup the HTML if requested
if appsettings.FLUENT_TEXT_CLEAN_HTML:
self.text = clean_html(self.text)
if appsettings.FLUENT_TEXT_SANITIZE_HTML:
self.text = sanitize_html(self.text)
super(TextItem, self).save(*args, **kwargs)
|
8f36430e6fc17485b422ed5e620de4b156101623
|
polyaxon_client/stores/stores/local_store.py
|
polyaxon_client/stores/stores/local_store.py
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
from polyaxon_client.stores.stores.base_store import Store
class LocalStore(Store):
"""
Local filesystem store.
This store is noop store since all data is accessible through the filesystem.
"""
# pylint:disable=arguments-differ
STORE_TYPE = Store._LOCAL_STORE # pylint:disable=protected-access
def download_file(self, *args, **kwargs):
pass
def upload_file(self, *args, **kwargs):
pass
def upload_dir(self, *args, **kwargs):
pass
def download_dir(self, *args, **kwargs):
pass
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
from polyaxon_client.stores.stores.base_store import BaseStore
class LocalStore(BaseStore):
"""
Local filesystem store.
This store is noop store since all data is accessible through the filesystem.
"""
# pylint:disable=arguments-differ
STORE_TYPE = BaseStore._LOCAL_STORE # pylint:disable=protected-access
def download_file(self, *args, **kwargs):
pass
def upload_file(self, *args, **kwargs):
pass
def upload_dir(self, *args, **kwargs):
pass
def download_dir(self, *args, **kwargs):
pass
|
Update local store base class
|
Update local store base class
|
Python
|
apache-2.0
|
polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
from polyaxon_client.stores.stores.base_store import Store
class LocalStore(Store):
"""
Local filesystem store.
This store is noop store since all data is accessible through the filesystem.
"""
# pylint:disable=arguments-differ
STORE_TYPE = Store._LOCAL_STORE # pylint:disable=protected-access
def download_file(self, *args, **kwargs):
pass
def upload_file(self, *args, **kwargs):
pass
def upload_dir(self, *args, **kwargs):
pass
def download_dir(self, *args, **kwargs):
pass
Update local store base class
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
from polyaxon_client.stores.stores.base_store import BaseStore
class LocalStore(BaseStore):
"""
Local filesystem store.
This store is noop store since all data is accessible through the filesystem.
"""
# pylint:disable=arguments-differ
STORE_TYPE = BaseStore._LOCAL_STORE # pylint:disable=protected-access
def download_file(self, *args, **kwargs):
pass
def upload_file(self, *args, **kwargs):
pass
def upload_dir(self, *args, **kwargs):
pass
def download_dir(self, *args, **kwargs):
pass
|
<commit_before># -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
from polyaxon_client.stores.stores.base_store import Store
class LocalStore(Store):
"""
Local filesystem store.
This store is noop store since all data is accessible through the filesystem.
"""
# pylint:disable=arguments-differ
STORE_TYPE = Store._LOCAL_STORE # pylint:disable=protected-access
def download_file(self, *args, **kwargs):
pass
def upload_file(self, *args, **kwargs):
pass
def upload_dir(self, *args, **kwargs):
pass
def download_dir(self, *args, **kwargs):
pass
<commit_msg>Update local store base class<commit_after>
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
from polyaxon_client.stores.stores.base_store import BaseStore
class LocalStore(BaseStore):
"""
Local filesystem store.
This store is noop store since all data is accessible through the filesystem.
"""
# pylint:disable=arguments-differ
STORE_TYPE = BaseStore._LOCAL_STORE # pylint:disable=protected-access
def download_file(self, *args, **kwargs):
pass
def upload_file(self, *args, **kwargs):
pass
def upload_dir(self, *args, **kwargs):
pass
def download_dir(self, *args, **kwargs):
pass
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
from polyaxon_client.stores.stores.base_store import Store
class LocalStore(Store):
"""
Local filesystem store.
This store is noop store since all data is accessible through the filesystem.
"""
# pylint:disable=arguments-differ
STORE_TYPE = Store._LOCAL_STORE # pylint:disable=protected-access
def download_file(self, *args, **kwargs):
pass
def upload_file(self, *args, **kwargs):
pass
def upload_dir(self, *args, **kwargs):
pass
def download_dir(self, *args, **kwargs):
pass
Update local store base class# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
from polyaxon_client.stores.stores.base_store import BaseStore
class LocalStore(BaseStore):
"""
Local filesystem store.
This store is noop store since all data is accessible through the filesystem.
"""
# pylint:disable=arguments-differ
STORE_TYPE = BaseStore._LOCAL_STORE # pylint:disable=protected-access
def download_file(self, *args, **kwargs):
pass
def upload_file(self, *args, **kwargs):
pass
def upload_dir(self, *args, **kwargs):
pass
def download_dir(self, *args, **kwargs):
pass
|
<commit_before># -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
from polyaxon_client.stores.stores.base_store import Store
class LocalStore(Store):
"""
Local filesystem store.
This store is noop store since all data is accessible through the filesystem.
"""
# pylint:disable=arguments-differ
STORE_TYPE = Store._LOCAL_STORE # pylint:disable=protected-access
def download_file(self, *args, **kwargs):
pass
def upload_file(self, *args, **kwargs):
pass
def upload_dir(self, *args, **kwargs):
pass
def download_dir(self, *args, **kwargs):
pass
<commit_msg>Update local store base class<commit_after># -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
from polyaxon_client.stores.stores.base_store import BaseStore
class LocalStore(BaseStore):
"""
Local filesystem store.
This store is noop store since all data is accessible through the filesystem.
"""
# pylint:disable=arguments-differ
STORE_TYPE = BaseStore._LOCAL_STORE # pylint:disable=protected-access
def download_file(self, *args, **kwargs):
pass
def upload_file(self, *args, **kwargs):
pass
def upload_dir(self, *args, **kwargs):
pass
def download_dir(self, *args, **kwargs):
pass
|
72895ee2d0064cbf3a44545fd2645680b8669989
|
foliant/gdrive.py
|
foliant/gdrive.py
|
import os.path
import webbrowser
import pydrive.auth, pydrive.drive
def upload(document):
"""Upload .docx file to Google Drive and return a web view link to it."""
auth = pydrive.auth.GoogleAuth()
auth.CommandLineAuth()
gdrive = pydrive.drive.GoogleDrive(auth)
gdoc = gdrive.CreateFile({
"title": os.path.splitext(os.path.basename(document))[0]
})
gdoc.SetContentFile(document)
gdoc.Upload({"convert": True})
webbrowser.open(gdoc["alternateLink"])
return gdoc["alternateLink"]
|
import os.path
import webbrowser
import pydrive.auth, pydrive.drive
def upload(document):
"""Upload .docx file to Google Drive and return a web view link to it."""
auth = pydrive.auth.GoogleAuth()
auth.CommandLineAuth()
gdrive = pydrive.drive.GoogleDrive(auth)
gdoc = gdrive.CreateFile({
"title": os.path.splitext(os.path.basename(document))[0]
})
gdoc.SetContentFile(document)
gdoc.Upload({"convert": True})
webbrowser.open(gdoc["alternateLink"])
return gdoc["alternateLink"]
|
Add another empty line between imports and def.
|
Gdrive: Add another empty line between imports and def.
|
Python
|
mit
|
foliant-docs/foliant
|
import os.path
import webbrowser
import pydrive.auth, pydrive.drive
def upload(document):
"""Upload .docx file to Google Drive and return a web view link to it."""
auth = pydrive.auth.GoogleAuth()
auth.CommandLineAuth()
gdrive = pydrive.drive.GoogleDrive(auth)
gdoc = gdrive.CreateFile({
"title": os.path.splitext(os.path.basename(document))[0]
})
gdoc.SetContentFile(document)
gdoc.Upload({"convert": True})
webbrowser.open(gdoc["alternateLink"])
return gdoc["alternateLink"]
Gdrive: Add another empty line between imports and def.
|
import os.path
import webbrowser
import pydrive.auth, pydrive.drive
def upload(document):
"""Upload .docx file to Google Drive and return a web view link to it."""
auth = pydrive.auth.GoogleAuth()
auth.CommandLineAuth()
gdrive = pydrive.drive.GoogleDrive(auth)
gdoc = gdrive.CreateFile({
"title": os.path.splitext(os.path.basename(document))[0]
})
gdoc.SetContentFile(document)
gdoc.Upload({"convert": True})
webbrowser.open(gdoc["alternateLink"])
return gdoc["alternateLink"]
|
<commit_before>import os.path
import webbrowser
import pydrive.auth, pydrive.drive
def upload(document):
"""Upload .docx file to Google Drive and return a web view link to it."""
auth = pydrive.auth.GoogleAuth()
auth.CommandLineAuth()
gdrive = pydrive.drive.GoogleDrive(auth)
gdoc = gdrive.CreateFile({
"title": os.path.splitext(os.path.basename(document))[0]
})
gdoc.SetContentFile(document)
gdoc.Upload({"convert": True})
webbrowser.open(gdoc["alternateLink"])
return gdoc["alternateLink"]
<commit_msg>Gdrive: Add another empty line between imports and def.<commit_after>
|
import os.path
import webbrowser
import pydrive.auth, pydrive.drive
def upload(document):
"""Upload .docx file to Google Drive and return a web view link to it."""
auth = pydrive.auth.GoogleAuth()
auth.CommandLineAuth()
gdrive = pydrive.drive.GoogleDrive(auth)
gdoc = gdrive.CreateFile({
"title": os.path.splitext(os.path.basename(document))[0]
})
gdoc.SetContentFile(document)
gdoc.Upload({"convert": True})
webbrowser.open(gdoc["alternateLink"])
return gdoc["alternateLink"]
|
import os.path
import webbrowser
import pydrive.auth, pydrive.drive
def upload(document):
"""Upload .docx file to Google Drive and return a web view link to it."""
auth = pydrive.auth.GoogleAuth()
auth.CommandLineAuth()
gdrive = pydrive.drive.GoogleDrive(auth)
gdoc = gdrive.CreateFile({
"title": os.path.splitext(os.path.basename(document))[0]
})
gdoc.SetContentFile(document)
gdoc.Upload({"convert": True})
webbrowser.open(gdoc["alternateLink"])
return gdoc["alternateLink"]
Gdrive: Add another empty line between imports and def.import os.path
import webbrowser
import pydrive.auth, pydrive.drive
def upload(document):
"""Upload .docx file to Google Drive and return a web view link to it."""
auth = pydrive.auth.GoogleAuth()
auth.CommandLineAuth()
gdrive = pydrive.drive.GoogleDrive(auth)
gdoc = gdrive.CreateFile({
"title": os.path.splitext(os.path.basename(document))[0]
})
gdoc.SetContentFile(document)
gdoc.Upload({"convert": True})
webbrowser.open(gdoc["alternateLink"])
return gdoc["alternateLink"]
|
<commit_before>import os.path
import webbrowser
import pydrive.auth, pydrive.drive
def upload(document):
"""Upload .docx file to Google Drive and return a web view link to it."""
auth = pydrive.auth.GoogleAuth()
auth.CommandLineAuth()
gdrive = pydrive.drive.GoogleDrive(auth)
gdoc = gdrive.CreateFile({
"title": os.path.splitext(os.path.basename(document))[0]
})
gdoc.SetContentFile(document)
gdoc.Upload({"convert": True})
webbrowser.open(gdoc["alternateLink"])
return gdoc["alternateLink"]
<commit_msg>Gdrive: Add another empty line between imports and def.<commit_after>import os.path
import webbrowser
import pydrive.auth, pydrive.drive
def upload(document):
"""Upload .docx file to Google Drive and return a web view link to it."""
auth = pydrive.auth.GoogleAuth()
auth.CommandLineAuth()
gdrive = pydrive.drive.GoogleDrive(auth)
gdoc = gdrive.CreateFile({
"title": os.path.splitext(os.path.basename(document))[0]
})
gdoc.SetContentFile(document)
gdoc.Upload({"convert": True})
webbrowser.open(gdoc["alternateLink"])
return gdoc["alternateLink"]
|
7048366af948773b6badfb1f3611f9e4c694e810
|
code/dataplot.py
|
code/dataplot.py
|
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import sys
def loadCudaStream(name):
"""
reads the file specified by name into a numpy array (and removes
the superfluous fourth bit from cuda's float4)
np.shape(data)=(N,3) where N is the length of a streamline
"""
data=np.fromfile(name, dtype="float32")
data=data.reshape(int(len(data)/4), 4)
data=np.delete(data,3,1)
return data
#
binfile = sys.argv[1]
data=np.fromfile(binfile, dtype="float32")
datasize = np.sqrt(data.shape[0])
data=data.reshape(datasize, datasize)
data = np.minimum(data,1*np.ones(data.shape))
data = np.maximum(data,-1*np.ones(data.shape))
img = plt.imshow(data)
#img.set_cmap('hot')
plt.colorbar()
plt.show()
|
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import sys
def loadCudaStream(name):
"""
reads the file specified by name into a numpy array (and removes
the superfluous fourth bit from cuda's float4)
np.shape(data)=(N,3) where N is the length of a streamline
"""
data=np.fromfile(name, dtype="float32")
data=data.reshape(int(len(data)/4), 4)
data=np.delete(data,3,1)
return data
clampVal = 1;
if (len(sys.argv) < 2) :
print("Usage: \n dataplot.py path_to_binfile [clamp value]")
sys.exit()
elif (len(sys.argv) > 2) :
clampVal = int(sys.argv[2])
binfile = sys.argv[1]
data=np.fromfile(binfile, dtype="float32")
datasize = np.sqrt(data.shape[0])
data=data.reshape(datasize, datasize)
data = np.minimum(data,clampVal*np.ones(data.shape))
data = np.maximum(data,-1*clampVal*np.ones(data.shape))
img = plt.imshow(data)
#img.set_cmap('hot')
plt.colorbar()
plt.show()
|
Create commandline options for the clampval
|
Create commandline options for the clampval
|
Python
|
mit
|
TAdeJong/plasma-analysis,TAdeJong/plasma-analysis
|
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import sys
def loadCudaStream(name):
"""
reads the file specified by name into a numpy array (and removes
the superfluous fourth bit from cuda's float4)
np.shape(data)=(N,3) where N is the length of a streamline
"""
data=np.fromfile(name, dtype="float32")
data=data.reshape(int(len(data)/4), 4)
data=np.delete(data,3,1)
return data
#
binfile = sys.argv[1]
data=np.fromfile(binfile, dtype="float32")
datasize = np.sqrt(data.shape[0])
data=data.reshape(datasize, datasize)
data = np.minimum(data,1*np.ones(data.shape))
data = np.maximum(data,-1*np.ones(data.shape))
img = plt.imshow(data)
#img.set_cmap('hot')
plt.colorbar()
plt.show()
Create commandline options for the clampval
|
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import sys
def loadCudaStream(name):
"""
reads the file specified by name into a numpy array (and removes
the superfluous fourth bit from cuda's float4)
np.shape(data)=(N,3) where N is the length of a streamline
"""
data=np.fromfile(name, dtype="float32")
data=data.reshape(int(len(data)/4), 4)
data=np.delete(data,3,1)
return data
clampVal = 1;
if (len(sys.argv) < 2) :
print("Usage: \n dataplot.py path_to_binfile [clamp value]")
sys.exit()
elif (len(sys.argv) > 2) :
clampVal = int(sys.argv[2])
binfile = sys.argv[1]
data=np.fromfile(binfile, dtype="float32")
datasize = np.sqrt(data.shape[0])
data=data.reshape(datasize, datasize)
data = np.minimum(data,clampVal*np.ones(data.shape))
data = np.maximum(data,-1*clampVal*np.ones(data.shape))
img = plt.imshow(data)
#img.set_cmap('hot')
plt.colorbar()
plt.show()
|
<commit_before>import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import sys
def loadCudaStream(name):
"""
reads the file specified by name into a numpy array (and removes
the superfluous fourth bit from cuda's float4)
np.shape(data)=(N,3) where N is the length of a streamline
"""
data=np.fromfile(name, dtype="float32")
data=data.reshape(int(len(data)/4), 4)
data=np.delete(data,3,1)
return data
#
binfile = sys.argv[1]
data=np.fromfile(binfile, dtype="float32")
datasize = np.sqrt(data.shape[0])
data=data.reshape(datasize, datasize)
data = np.minimum(data,1*np.ones(data.shape))
data = np.maximum(data,-1*np.ones(data.shape))
img = plt.imshow(data)
#img.set_cmap('hot')
plt.colorbar()
plt.show()
<commit_msg>Create commandline options for the clampval<commit_after>
|
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import sys
def loadCudaStream(name):
"""
reads the file specified by name into a numpy array (and removes
the superfluous fourth bit from cuda's float4)
np.shape(data)=(N,3) where N is the length of a streamline
"""
data=np.fromfile(name, dtype="float32")
data=data.reshape(int(len(data)/4), 4)
data=np.delete(data,3,1)
return data
clampVal = 1;
if (len(sys.argv) < 2) :
print("Usage: \n dataplot.py path_to_binfile [clamp value]")
sys.exit()
elif (len(sys.argv) > 2) :
clampVal = int(sys.argv[2])
binfile = sys.argv[1]
data=np.fromfile(binfile, dtype="float32")
datasize = np.sqrt(data.shape[0])
data=data.reshape(datasize, datasize)
data = np.minimum(data,clampVal*np.ones(data.shape))
data = np.maximum(data,-1*clampVal*np.ones(data.shape))
img = plt.imshow(data)
#img.set_cmap('hot')
plt.colorbar()
plt.show()
|
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import sys
def loadCudaStream(name):
"""
reads the file specified by name into a numpy array (and removes
the superfluous fourth bit from cuda's float4)
np.shape(data)=(N,3) where N is the length of a streamline
"""
data=np.fromfile(name, dtype="float32")
data=data.reshape(int(len(data)/4), 4)
data=np.delete(data,3,1)
return data
#
binfile = sys.argv[1]
data=np.fromfile(binfile, dtype="float32")
datasize = np.sqrt(data.shape[0])
data=data.reshape(datasize, datasize)
data = np.minimum(data,1*np.ones(data.shape))
data = np.maximum(data,-1*np.ones(data.shape))
img = plt.imshow(data)
#img.set_cmap('hot')
plt.colorbar()
plt.show()
Create commandline options for the clampvalimport numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import sys
def loadCudaStream(name):
"""
reads the file specified by name into a numpy array (and removes
the superfluous fourth bit from cuda's float4)
np.shape(data)=(N,3) where N is the length of a streamline
"""
data=np.fromfile(name, dtype="float32")
data=data.reshape(int(len(data)/4), 4)
data=np.delete(data,3,1)
return data
clampVal = 1;
if (len(sys.argv) < 2) :
print("Usage: \n dataplot.py path_to_binfile [clamp value]")
sys.exit()
elif (len(sys.argv) > 2) :
clampVal = int(sys.argv[2])
binfile = sys.argv[1]
data=np.fromfile(binfile, dtype="float32")
datasize = np.sqrt(data.shape[0])
data=data.reshape(datasize, datasize)
data = np.minimum(data,clampVal*np.ones(data.shape))
data = np.maximum(data,-1*clampVal*np.ones(data.shape))
img = plt.imshow(data)
#img.set_cmap('hot')
plt.colorbar()
plt.show()
|
<commit_before>import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import sys
def loadCudaStream(name):
"""
reads the file specified by name into a numpy array (and removes
the superfluous fourth bit from cuda's float4)
np.shape(data)=(N,3) where N is the length of a streamline
"""
data=np.fromfile(name, dtype="float32")
data=data.reshape(int(len(data)/4), 4)
data=np.delete(data,3,1)
return data
#
binfile = sys.argv[1]
data=np.fromfile(binfile, dtype="float32")
datasize = np.sqrt(data.shape[0])
data=data.reshape(datasize, datasize)
data = np.minimum(data,1*np.ones(data.shape))
data = np.maximum(data,-1*np.ones(data.shape))
img = plt.imshow(data)
#img.set_cmap('hot')
plt.colorbar()
plt.show()
<commit_msg>Create commandline options for the clampval<commit_after>import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import sys
def loadCudaStream(name):
"""
reads the file specified by name into a numpy array (and removes
the superfluous fourth bit from cuda's float4)
np.shape(data)=(N,3) where N is the length of a streamline
"""
data=np.fromfile(name, dtype="float32")
data=data.reshape(int(len(data)/4), 4)
data=np.delete(data,3,1)
return data
clampVal = 1;
if (len(sys.argv) < 2) :
print("Usage: \n dataplot.py path_to_binfile [clamp value]")
sys.exit()
elif (len(sys.argv) > 2) :
clampVal = int(sys.argv[2])
binfile = sys.argv[1]
data=np.fromfile(binfile, dtype="float32")
datasize = np.sqrt(data.shape[0])
data=data.reshape(datasize, datasize)
data = np.minimum(data,clampVal*np.ones(data.shape))
data = np.maximum(data,-1*clampVal*np.ones(data.shape))
img = plt.imshow(data)
#img.set_cmap('hot')
plt.colorbar()
plt.show()
|
a3a34026369391837d31d7424e78de207b98340d
|
preferences/views.py
|
preferences/views.py
|
from django.shortcuts import render
from django.db import transaction
# from django.views.generic import TemplateView
from registration.forms import RegistrationFormUniqueEmail
from registration.backends.default.views import RegistrationView
from preferences.models import PersonFollow
from opencivicdata.models.people_orgs import Person
class EmailRegistrationView(RegistrationView):
form_class = RegistrationFormUniqueEmail
def user_preferences(request):
user = request.user
senators = Person.objects.filter(memberships__organization__name='Florida Senate')
representatives = Person.objects.filter(memberships__organization__name='Florida House of Representatives')
if request.method == 'POST':
with transaction.atomic():
PersonFollow.objects.filter(user=user).delete()
for senator in request.POST.getlist('senators'):
PersonFollow.objects.create(user=user, person_id=senator)
for representative in request.POST.getlist('representatives'):
PersonFollow.objects.create(user=user, person_id=representitive)
return render(
request,
'preferences/preferences.html',
{'user': user, 'senators': senators, 'representatives': representatives}
)
|
from django.shortcuts import render
from django.db import transaction
# from django.views.generic import TemplateView
from tot.utils import get_current_people
from registration.forms import RegistrationFormUniqueEmail
from registration.backends.default.views import RegistrationView
from preferences.models import PersonFollow
from opencivicdata.models.people_orgs import Person
class EmailRegistrationView(RegistrationView):
form_class = RegistrationFormUniqueEmail
def user_preferences(request):
user = request.user
senators = get_current_people(position='senator')
representatives = get_current_people(position='representatives')
if request.method == 'POST':
with transaction.atomic():
PersonFollow.objects.filter(user=user).delete()
for senator in request.POST.getlist('senators'):
PersonFollow.objects.create(user=user, person_id=senator)
for representative in request.POST.getlist('representatives'):
PersonFollow.objects.create(user=user, person_id=representitive)
return render(
request,
'preferences/preferences.html',
{'user': user, 'senators': senators, 'representatives': representatives}
)
|
Use new util function for getting current people
|
Use new
util function for getting current people
|
Python
|
mit
|
jamesturk/tot,jamesturk/tot,jamesturk/tot,jamesturk/tot,jamesturk/tot
|
from django.shortcuts import render
from django.db import transaction
# from django.views.generic import TemplateView
from registration.forms import RegistrationFormUniqueEmail
from registration.backends.default.views import RegistrationView
from preferences.models import PersonFollow
from opencivicdata.models.people_orgs import Person
class EmailRegistrationView(RegistrationView):
form_class = RegistrationFormUniqueEmail
def user_preferences(request):
user = request.user
senators = Person.objects.filter(memberships__organization__name='Florida Senate')
representatives = Person.objects.filter(memberships__organization__name='Florida House of Representatives')
if request.method == 'POST':
with transaction.atomic():
PersonFollow.objects.filter(user=user).delete()
for senator in request.POST.getlist('senators'):
PersonFollow.objects.create(user=user, person_id=senator)
for representative in request.POST.getlist('representatives'):
PersonFollow.objects.create(user=user, person_id=representitive)
return render(
request,
'preferences/preferences.html',
{'user': user, 'senators': senators, 'representatives': representatives}
)Use new
util function for getting current people
|
from django.shortcuts import render
from django.db import transaction
# from django.views.generic import TemplateView
from tot.utils import get_current_people
from registration.forms import RegistrationFormUniqueEmail
from registration.backends.default.views import RegistrationView
from preferences.models import PersonFollow
from opencivicdata.models.people_orgs import Person
class EmailRegistrationView(RegistrationView):
form_class = RegistrationFormUniqueEmail
def user_preferences(request):
user = request.user
senators = get_current_people(position='senator')
representatives = get_current_people(position='representatives')
if request.method == 'POST':
with transaction.atomic():
PersonFollow.objects.filter(user=user).delete()
for senator in request.POST.getlist('senators'):
PersonFollow.objects.create(user=user, person_id=senator)
for representative in request.POST.getlist('representatives'):
PersonFollow.objects.create(user=user, person_id=representitive)
return render(
request,
'preferences/preferences.html',
{'user': user, 'senators': senators, 'representatives': representatives}
)
|
<commit_before>from django.shortcuts import render
from django.db import transaction
# from django.views.generic import TemplateView
from registration.forms import RegistrationFormUniqueEmail
from registration.backends.default.views import RegistrationView
from preferences.models import PersonFollow
from opencivicdata.models.people_orgs import Person
class EmailRegistrationView(RegistrationView):
form_class = RegistrationFormUniqueEmail
def user_preferences(request):
user = request.user
senators = Person.objects.filter(memberships__organization__name='Florida Senate')
representatives = Person.objects.filter(memberships__organization__name='Florida House of Representatives')
if request.method == 'POST':
with transaction.atomic():
PersonFollow.objects.filter(user=user).delete()
for senator in request.POST.getlist('senators'):
PersonFollow.objects.create(user=user, person_id=senator)
for representative in request.POST.getlist('representatives'):
PersonFollow.objects.create(user=user, person_id=representitive)
return render(
request,
'preferences/preferences.html',
{'user': user, 'senators': senators, 'representatives': representatives}
)<commit_msg>Use new
util function for getting current people<commit_after>
|
from django.shortcuts import render
from django.db import transaction
# from django.views.generic import TemplateView
from tot.utils import get_current_people
from registration.forms import RegistrationFormUniqueEmail
from registration.backends.default.views import RegistrationView
from preferences.models import PersonFollow
from opencivicdata.models.people_orgs import Person
class EmailRegistrationView(RegistrationView):
form_class = RegistrationFormUniqueEmail
def user_preferences(request):
user = request.user
senators = get_current_people(position='senator')
representatives = get_current_people(position='representatives')
if request.method == 'POST':
with transaction.atomic():
PersonFollow.objects.filter(user=user).delete()
for senator in request.POST.getlist('senators'):
PersonFollow.objects.create(user=user, person_id=senator)
for representative in request.POST.getlist('representatives'):
PersonFollow.objects.create(user=user, person_id=representitive)
return render(
request,
'preferences/preferences.html',
{'user': user, 'senators': senators, 'representatives': representatives}
)
|
from django.shortcuts import render
from django.db import transaction
# from django.views.generic import TemplateView
from registration.forms import RegistrationFormUniqueEmail
from registration.backends.default.views import RegistrationView
from preferences.models import PersonFollow
from opencivicdata.models.people_orgs import Person
class EmailRegistrationView(RegistrationView):
form_class = RegistrationFormUniqueEmail
def user_preferences(request):
user = request.user
senators = Person.objects.filter(memberships__organization__name='Florida Senate')
representatives = Person.objects.filter(memberships__organization__name='Florida House of Representatives')
if request.method == 'POST':
with transaction.atomic():
PersonFollow.objects.filter(user=user).delete()
for senator in request.POST.getlist('senators'):
PersonFollow.objects.create(user=user, person_id=senator)
for representative in request.POST.getlist('representatives'):
PersonFollow.objects.create(user=user, person_id=representitive)
return render(
request,
'preferences/preferences.html',
{'user': user, 'senators': senators, 'representatives': representatives}
)Use new
util function for getting current peoplefrom django.shortcuts import render
from django.db import transaction
# from django.views.generic import TemplateView
from tot.utils import get_current_people
from registration.forms import RegistrationFormUniqueEmail
from registration.backends.default.views import RegistrationView
from preferences.models import PersonFollow
from opencivicdata.models.people_orgs import Person
class EmailRegistrationView(RegistrationView):
form_class = RegistrationFormUniqueEmail
def user_preferences(request):
user = request.user
senators = get_current_people(position='senator')
representatives = get_current_people(position='representatives')
if request.method == 'POST':
with transaction.atomic():
PersonFollow.objects.filter(user=user).delete()
for senator in request.POST.getlist('senators'):
PersonFollow.objects.create(user=user, person_id=senator)
for representative in request.POST.getlist('representatives'):
PersonFollow.objects.create(user=user, person_id=representitive)
return render(
request,
'preferences/preferences.html',
{'user': user, 'senators': senators, 'representatives': representatives}
)
|
<commit_before>from django.shortcuts import render
from django.db import transaction
# from django.views.generic import TemplateView
from registration.forms import RegistrationFormUniqueEmail
from registration.backends.default.views import RegistrationView
from preferences.models import PersonFollow
from opencivicdata.models.people_orgs import Person
class EmailRegistrationView(RegistrationView):
form_class = RegistrationFormUniqueEmail
def user_preferences(request):
user = request.user
senators = Person.objects.filter(memberships__organization__name='Florida Senate')
representatives = Person.objects.filter(memberships__organization__name='Florida House of Representatives')
if request.method == 'POST':
with transaction.atomic():
PersonFollow.objects.filter(user=user).delete()
for senator in request.POST.getlist('senators'):
PersonFollow.objects.create(user=user, person_id=senator)
for representative in request.POST.getlist('representatives'):
PersonFollow.objects.create(user=user, person_id=representitive)
return render(
request,
'preferences/preferences.html',
{'user': user, 'senators': senators, 'representatives': representatives}
)<commit_msg>Use new
util function for getting current people<commit_after>from django.shortcuts import render
from django.db import transaction
# from django.views.generic import TemplateView
from tot.utils import get_current_people
from registration.forms import RegistrationFormUniqueEmail
from registration.backends.default.views import RegistrationView
from preferences.models import PersonFollow
from opencivicdata.models.people_orgs import Person
class EmailRegistrationView(RegistrationView):
form_class = RegistrationFormUniqueEmail
def user_preferences(request):
user = request.user
senators = get_current_people(position='senator')
representatives = get_current_people(position='representatives')
if request.method == 'POST':
with transaction.atomic():
PersonFollow.objects.filter(user=user).delete()
for senator in request.POST.getlist('senators'):
PersonFollow.objects.create(user=user, person_id=senator)
for representative in request.POST.getlist('representatives'):
PersonFollow.objects.create(user=user, person_id=representitive)
return render(
request,
'preferences/preferences.html',
{'user': user, 'senators': senators, 'representatives': representatives}
)
|
21858e2137d3b15089c5d036cd99d4a3be4e3dbe
|
python/sanitytest.py
|
python/sanitytest.py
|
#!/usr/bin/python
import libvirt
globals = dir(libvirt)
# Sanity test that the generator hasn't gone wrong
# Look for core classes
assert("virConnect" in globals)
assert("virDomain" in globals)
assert("virDomainSnapshot" in globals)
assert("virInterface" in globals)
assert("virNWFilter" in globals)
assert("virNodeDevice" in globals)
assert("virNetwork" in globals)
assert("virSecret" in globals)
assert("virStoragePool" in globals)
assert("virStorageVol" in globals)
assert("virStream" in globals)
assert("VIR_CONNECT_RO" in globals)
# Error related bits
assert("libvirtError" in globals)
assert("VIR_ERR_AUTH_FAILED" in globals)
assert("virGetLastError" in globals)
# Some misc methods
assert("virInitialize" in globals)
assert("virEventAddHandle" in globals)
assert("virEventRegisterDefaultImpl" in globals)
|
#!/usr/bin/python
import libvirt
globals = dir(libvirt)
# Sanity test that the generator hasn't gone wrong
# Look for core classes
for clsname in ["virConnect",
"virDomain",
"virDomainSnapshot",
"virInterface",
"virNWFilter",
"virNodeDevice",
"virNetwork",
"virSecret",
"virStoragePool",
"virStorageVol",
"virStream",
]:
assert(clsname in globals)
assert(object in getattr(libvirt, clsname).__bases__)
# Constants
assert("VIR_CONNECT_RO" in globals)
# Error related bits
assert("libvirtError" in globals)
assert("VIR_ERR_AUTH_FAILED" in globals)
assert("virGetLastError" in globals)
# Some misc methods
assert("virInitialize" in globals)
assert("virEventAddHandle" in globals)
assert("virEventRegisterDefaultImpl" in globals)
|
Check if classes are derived from object
|
Check if classes are derived from object
This makes sure we don't regress to old style classes
|
Python
|
lgpl-2.1
|
trainstack/libvirt,siboulet/libvirt-openvz,elmarco/libvirt,crobinso/libvirt,eskultety/libvirt,crobinso/libvirt,shugaoye/libvirt,libvirt/libvirt,fabianfreyer/libvirt,iam-TJ/libvirt,eskultety/libvirt,olafhering/libvirt,shugaoye/libvirt,shugaoye/libvirt,rlaager/libvirt,cbosdo/libvirt,rlaager/libvirt,nertpinx/libvirt,andreabolognani/libvirt,taget/libvirt,iam-TJ/libvirt,trainstack/libvirt,iam-TJ/libvirt,cbosdo/libvirt,olafhering/libvirt,olafhering/libvirt,VenkatDatta/libvirt,zhlcindy/libvirt-1.1.4-maintain,agx/libvirt,zippy2/libvirt,cbosdo/libvirt,siboulet/libvirt-openvz,andreabolognani/libvirt,olafhering/libvirt,trainstack/libvirt,agx/libvirt,trainstack/libvirt,datto/libvirt,VenkatDatta/libvirt,zippy2/libvirt,elmarco/libvirt,cbosdo/libvirt,VenkatDatta/libvirt,crobinso/libvirt,VenkatDatta/libvirt,jardasgit/libvirt,eskultety/libvirt,nertpinx/libvirt,datto/libvirt,elmarco/libvirt,fabianfreyer/libvirt,agx/libvirt,fabianfreyer/libvirt,shugaoye/libvirt,libvirt/libvirt,siboulet/libvirt-openvz,elmarco/libvirt,datto/libvirt,fabianfreyer/libvirt,rlaager/libvirt,zippy2/libvirt,taget/libvirt,iam-TJ/libvirt,zippy2/libvirt,andreabolognani/libvirt,fabianfreyer/libvirt,crobinso/libvirt,siboulet/libvirt-openvz,rlaager/libvirt,agx/libvirt,nertpinx/libvirt,andreabolognani/libvirt,jardasgit/libvirt,taget/libvirt,eskultety/libvirt,jfehlig/libvirt,agx/libvirt,zhlcindy/libvirt-1.1.4-maintain,rlaager/libvirt,zhlcindy/libvirt-1.1.4-maintain,libvirt/libvirt,iam-TJ/libvirt,andreabolognani/libvirt,eskultety/libvirt,VenkatDatta/libvirt,jfehlig/libvirt,elmarco/libvirt,jardasgit/libvirt,jfehlig/libvirt,nertpinx/libvirt,iam-TJ/libvirt,zhlcindy/libvirt-1.1.4-maintain,shugaoye/libvirt,jardasgit/libvirt,trainstack/libvirt,iam-TJ/libvirt,libvirt/libvirt,taget/libvirt,taget/libvirt,zhlcindy/libvirt-1.1.4-maintain,trainstack/libvirt,jfehlig/libvirt,nertpinx/libvirt,trainstack/libvirt,datto/libvirt,datto/libvirt,siboulet/libvirt-openvz,jardasgit/libvirt,cbosdo/libvirt
|
#!/usr/bin/python
import libvirt
globals = dir(libvirt)
# Sanity test that the generator hasn't gone wrong
# Look for core classes
assert("virConnect" in globals)
assert("virDomain" in globals)
assert("virDomainSnapshot" in globals)
assert("virInterface" in globals)
assert("virNWFilter" in globals)
assert("virNodeDevice" in globals)
assert("virNetwork" in globals)
assert("virSecret" in globals)
assert("virStoragePool" in globals)
assert("virStorageVol" in globals)
assert("virStream" in globals)
assert("VIR_CONNECT_RO" in globals)
# Error related bits
assert("libvirtError" in globals)
assert("VIR_ERR_AUTH_FAILED" in globals)
assert("virGetLastError" in globals)
# Some misc methods
assert("virInitialize" in globals)
assert("virEventAddHandle" in globals)
assert("virEventRegisterDefaultImpl" in globals)
Check if classes are derived from object
This makes sure we don't regress to old style classes
|
#!/usr/bin/python
import libvirt
globals = dir(libvirt)
# Sanity test that the generator hasn't gone wrong
# Look for core classes
for clsname in ["virConnect",
"virDomain",
"virDomainSnapshot",
"virInterface",
"virNWFilter",
"virNodeDevice",
"virNetwork",
"virSecret",
"virStoragePool",
"virStorageVol",
"virStream",
]:
assert(clsname in globals)
assert(object in getattr(libvirt, clsname).__bases__)
# Constants
assert("VIR_CONNECT_RO" in globals)
# Error related bits
assert("libvirtError" in globals)
assert("VIR_ERR_AUTH_FAILED" in globals)
assert("virGetLastError" in globals)
# Some misc methods
assert("virInitialize" in globals)
assert("virEventAddHandle" in globals)
assert("virEventRegisterDefaultImpl" in globals)
|
<commit_before>#!/usr/bin/python
import libvirt
globals = dir(libvirt)
# Sanity test that the generator hasn't gone wrong
# Look for core classes
assert("virConnect" in globals)
assert("virDomain" in globals)
assert("virDomainSnapshot" in globals)
assert("virInterface" in globals)
assert("virNWFilter" in globals)
assert("virNodeDevice" in globals)
assert("virNetwork" in globals)
assert("virSecret" in globals)
assert("virStoragePool" in globals)
assert("virStorageVol" in globals)
assert("virStream" in globals)
assert("VIR_CONNECT_RO" in globals)
# Error related bits
assert("libvirtError" in globals)
assert("VIR_ERR_AUTH_FAILED" in globals)
assert("virGetLastError" in globals)
# Some misc methods
assert("virInitialize" in globals)
assert("virEventAddHandle" in globals)
assert("virEventRegisterDefaultImpl" in globals)
<commit_msg>Check if classes are derived from object
This makes sure we don't regress to old style classes<commit_after>
|
#!/usr/bin/python
import libvirt
globals = dir(libvirt)
# Sanity test that the generator hasn't gone wrong
# Look for core classes
for clsname in ["virConnect",
"virDomain",
"virDomainSnapshot",
"virInterface",
"virNWFilter",
"virNodeDevice",
"virNetwork",
"virSecret",
"virStoragePool",
"virStorageVol",
"virStream",
]:
assert(clsname in globals)
assert(object in getattr(libvirt, clsname).__bases__)
# Constants
assert("VIR_CONNECT_RO" in globals)
# Error related bits
assert("libvirtError" in globals)
assert("VIR_ERR_AUTH_FAILED" in globals)
assert("virGetLastError" in globals)
# Some misc methods
assert("virInitialize" in globals)
assert("virEventAddHandle" in globals)
assert("virEventRegisterDefaultImpl" in globals)
|
#!/usr/bin/python
import libvirt
globals = dir(libvirt)
# Sanity test that the generator hasn't gone wrong
# Look for core classes
assert("virConnect" in globals)
assert("virDomain" in globals)
assert("virDomainSnapshot" in globals)
assert("virInterface" in globals)
assert("virNWFilter" in globals)
assert("virNodeDevice" in globals)
assert("virNetwork" in globals)
assert("virSecret" in globals)
assert("virStoragePool" in globals)
assert("virStorageVol" in globals)
assert("virStream" in globals)
assert("VIR_CONNECT_RO" in globals)
# Error related bits
assert("libvirtError" in globals)
assert("VIR_ERR_AUTH_FAILED" in globals)
assert("virGetLastError" in globals)
# Some misc methods
assert("virInitialize" in globals)
assert("virEventAddHandle" in globals)
assert("virEventRegisterDefaultImpl" in globals)
Check if classes are derived from object
This makes sure we don't regress to old style classes#!/usr/bin/python
import libvirt
globals = dir(libvirt)
# Sanity test that the generator hasn't gone wrong
# Look for core classes
for clsname in ["virConnect",
"virDomain",
"virDomainSnapshot",
"virInterface",
"virNWFilter",
"virNodeDevice",
"virNetwork",
"virSecret",
"virStoragePool",
"virStorageVol",
"virStream",
]:
assert(clsname in globals)
assert(object in getattr(libvirt, clsname).__bases__)
# Constants
assert("VIR_CONNECT_RO" in globals)
# Error related bits
assert("libvirtError" in globals)
assert("VIR_ERR_AUTH_FAILED" in globals)
assert("virGetLastError" in globals)
# Some misc methods
assert("virInitialize" in globals)
assert("virEventAddHandle" in globals)
assert("virEventRegisterDefaultImpl" in globals)
|
<commit_before>#!/usr/bin/python
import libvirt
globals = dir(libvirt)
# Sanity test that the generator hasn't gone wrong
# Look for core classes
assert("virConnect" in globals)
assert("virDomain" in globals)
assert("virDomainSnapshot" in globals)
assert("virInterface" in globals)
assert("virNWFilter" in globals)
assert("virNodeDevice" in globals)
assert("virNetwork" in globals)
assert("virSecret" in globals)
assert("virStoragePool" in globals)
assert("virStorageVol" in globals)
assert("virStream" in globals)
assert("VIR_CONNECT_RO" in globals)
# Error related bits
assert("libvirtError" in globals)
assert("VIR_ERR_AUTH_FAILED" in globals)
assert("virGetLastError" in globals)
# Some misc methods
assert("virInitialize" in globals)
assert("virEventAddHandle" in globals)
assert("virEventRegisterDefaultImpl" in globals)
<commit_msg>Check if classes are derived from object
This makes sure we don't regress to old style classes<commit_after>#!/usr/bin/python
import libvirt
globals = dir(libvirt)
# Sanity test that the generator hasn't gone wrong
# Look for core classes
for clsname in ["virConnect",
"virDomain",
"virDomainSnapshot",
"virInterface",
"virNWFilter",
"virNodeDevice",
"virNetwork",
"virSecret",
"virStoragePool",
"virStorageVol",
"virStream",
]:
assert(clsname in globals)
assert(object in getattr(libvirt, clsname).__bases__)
# Constants
assert("VIR_CONNECT_RO" in globals)
# Error related bits
assert("libvirtError" in globals)
assert("VIR_ERR_AUTH_FAILED" in globals)
assert("virGetLastError" in globals)
# Some misc methods
assert("virInitialize" in globals)
assert("virEventAddHandle" in globals)
assert("virEventRegisterDefaultImpl" in globals)
|
2d018f4cff87f5f94e949d36201edd83019c336d
|
rabbitpy/__init__.py
|
rabbitpy/__init__.py
|
"""
rabbitpy, a pythonic RabbitMQ client
"""
__version__ = '0.14.0'
version = __version__
DEBUG = False
import logging
try:
from logging import NullHandler
except ImportError:
class NullHandler(logging.Handler):
"""Python 2.6 does not have a NullHandler"""
def emit(self, record):
"""Emit a record
:param record record: The record to emit
"""
pass
logging.getLogger('rabbitpy').addHandler(NullHandler())
from rabbitpy.connection import Connection
from rabbitpy.exchange import Exchange
from rabbitpy.message import Message
from rabbitpy.amqp_queue import Queue
from rabbitpy.tx import Tx
from rabbitpy.simple import consume
from rabbitpy.simple import get
from rabbitpy.simple import publish
from rabbitpy.simple import create_queue
from rabbitpy.simple import delete_queue
from rabbitpy.simple import create_direct_exchange
from rabbitpy.simple import create_fanout_exchange
from rabbitpy.simple import create_topic_exchange
from rabbitpy.simple import delete_exchange
|
"""
rabbitpy, a pythonic RabbitMQ client
"""
__version__ = '0.14.0'
version = __version__
DEBUG = False
import logging
try:
from logging import NullHandler
except ImportError:
class NullHandler(logging.Handler):
"""Python 2.6 does not have a NullHandler"""
def emit(self, record):
"""Emit a record
:param record record: The record to emit
"""
pass
logging.getLogger('rabbitpy').addHandler(NullHandler())
from rabbitpy.connection import Connection
from rabbitpy.channel import Channel
from rabbitpy.exchange import Exchange
from rabbitpy.exchange import DirectExchange
from rabbitpy.exchange import FanoutExchange
from rabbitpy.exchange import HeadersExchange
from rabbitpy.exchange import TopicExchange
from rabbitpy.message import Message
from rabbitpy.amqp_queue import Queue
from rabbitpy.tx import Tx
from rabbitpy.simple import consume
from rabbitpy.simple import get
from rabbitpy.simple import publish
from rabbitpy.simple import create_queue
from rabbitpy.simple import delete_queue
from rabbitpy.simple import create_direct_exchange
from rabbitpy.simple import create_fanout_exchange
from rabbitpy.simple import create_topic_exchange
from rabbitpy.simple import delete_exchange
|
Add Channel and the convenience exchange classes
|
Add Channel and the convenience exchange classes
|
Python
|
bsd-3-clause
|
gmr/rabbitpy,jonahbull/rabbitpy,gmr/rabbitpy
|
"""
rabbitpy, a pythonic RabbitMQ client
"""
__version__ = '0.14.0'
version = __version__
DEBUG = False
import logging
try:
from logging import NullHandler
except ImportError:
class NullHandler(logging.Handler):
"""Python 2.6 does not have a NullHandler"""
def emit(self, record):
"""Emit a record
:param record record: The record to emit
"""
pass
logging.getLogger('rabbitpy').addHandler(NullHandler())
from rabbitpy.connection import Connection
from rabbitpy.exchange import Exchange
from rabbitpy.message import Message
from rabbitpy.amqp_queue import Queue
from rabbitpy.tx import Tx
from rabbitpy.simple import consume
from rabbitpy.simple import get
from rabbitpy.simple import publish
from rabbitpy.simple import create_queue
from rabbitpy.simple import delete_queue
from rabbitpy.simple import create_direct_exchange
from rabbitpy.simple import create_fanout_exchange
from rabbitpy.simple import create_topic_exchange
from rabbitpy.simple import delete_exchange
Add Channel and the convenience exchange classes
|
"""
rabbitpy, a pythonic RabbitMQ client
"""
__version__ = '0.14.0'
version = __version__
DEBUG = False
import logging
try:
from logging import NullHandler
except ImportError:
class NullHandler(logging.Handler):
"""Python 2.6 does not have a NullHandler"""
def emit(self, record):
"""Emit a record
:param record record: The record to emit
"""
pass
logging.getLogger('rabbitpy').addHandler(NullHandler())
from rabbitpy.connection import Connection
from rabbitpy.channel import Channel
from rabbitpy.exchange import Exchange
from rabbitpy.exchange import DirectExchange
from rabbitpy.exchange import FanoutExchange
from rabbitpy.exchange import HeadersExchange
from rabbitpy.exchange import TopicExchange
from rabbitpy.message import Message
from rabbitpy.amqp_queue import Queue
from rabbitpy.tx import Tx
from rabbitpy.simple import consume
from rabbitpy.simple import get
from rabbitpy.simple import publish
from rabbitpy.simple import create_queue
from rabbitpy.simple import delete_queue
from rabbitpy.simple import create_direct_exchange
from rabbitpy.simple import create_fanout_exchange
from rabbitpy.simple import create_topic_exchange
from rabbitpy.simple import delete_exchange
|
<commit_before>"""
rabbitpy, a pythonic RabbitMQ client
"""
__version__ = '0.14.0'
version = __version__
DEBUG = False
import logging
try:
from logging import NullHandler
except ImportError:
class NullHandler(logging.Handler):
"""Python 2.6 does not have a NullHandler"""
def emit(self, record):
"""Emit a record
:param record record: The record to emit
"""
pass
logging.getLogger('rabbitpy').addHandler(NullHandler())
from rabbitpy.connection import Connection
from rabbitpy.exchange import Exchange
from rabbitpy.message import Message
from rabbitpy.amqp_queue import Queue
from rabbitpy.tx import Tx
from rabbitpy.simple import consume
from rabbitpy.simple import get
from rabbitpy.simple import publish
from rabbitpy.simple import create_queue
from rabbitpy.simple import delete_queue
from rabbitpy.simple import create_direct_exchange
from rabbitpy.simple import create_fanout_exchange
from rabbitpy.simple import create_topic_exchange
from rabbitpy.simple import delete_exchange
<commit_msg>Add Channel and the convenience exchange classes<commit_after>
|
"""
rabbitpy, a pythonic RabbitMQ client
"""
__version__ = '0.14.0'
version = __version__
DEBUG = False
import logging
try:
from logging import NullHandler
except ImportError:
class NullHandler(logging.Handler):
"""Python 2.6 does not have a NullHandler"""
def emit(self, record):
"""Emit a record
:param record record: The record to emit
"""
pass
logging.getLogger('rabbitpy').addHandler(NullHandler())
from rabbitpy.connection import Connection
from rabbitpy.channel import Channel
from rabbitpy.exchange import Exchange
from rabbitpy.exchange import DirectExchange
from rabbitpy.exchange import FanoutExchange
from rabbitpy.exchange import HeadersExchange
from rabbitpy.exchange import TopicExchange
from rabbitpy.message import Message
from rabbitpy.amqp_queue import Queue
from rabbitpy.tx import Tx
from rabbitpy.simple import consume
from rabbitpy.simple import get
from rabbitpy.simple import publish
from rabbitpy.simple import create_queue
from rabbitpy.simple import delete_queue
from rabbitpy.simple import create_direct_exchange
from rabbitpy.simple import create_fanout_exchange
from rabbitpy.simple import create_topic_exchange
from rabbitpy.simple import delete_exchange
|
"""
rabbitpy, a pythonic RabbitMQ client
"""
__version__ = '0.14.0'
version = __version__
DEBUG = False
import logging
try:
from logging import NullHandler
except ImportError:
class NullHandler(logging.Handler):
"""Python 2.6 does not have a NullHandler"""
def emit(self, record):
"""Emit a record
:param record record: The record to emit
"""
pass
logging.getLogger('rabbitpy').addHandler(NullHandler())
from rabbitpy.connection import Connection
from rabbitpy.exchange import Exchange
from rabbitpy.message import Message
from rabbitpy.amqp_queue import Queue
from rabbitpy.tx import Tx
from rabbitpy.simple import consume
from rabbitpy.simple import get
from rabbitpy.simple import publish
from rabbitpy.simple import create_queue
from rabbitpy.simple import delete_queue
from rabbitpy.simple import create_direct_exchange
from rabbitpy.simple import create_fanout_exchange
from rabbitpy.simple import create_topic_exchange
from rabbitpy.simple import delete_exchange
Add Channel and the convenience exchange classes"""
rabbitpy, a pythonic RabbitMQ client
"""
__version__ = '0.14.0'
version = __version__
DEBUG = False
import logging
try:
from logging import NullHandler
except ImportError:
class NullHandler(logging.Handler):
"""Python 2.6 does not have a NullHandler"""
def emit(self, record):
"""Emit a record
:param record record: The record to emit
"""
pass
logging.getLogger('rabbitpy').addHandler(NullHandler())
from rabbitpy.connection import Connection
from rabbitpy.channel import Channel
from rabbitpy.exchange import Exchange
from rabbitpy.exchange import DirectExchange
from rabbitpy.exchange import FanoutExchange
from rabbitpy.exchange import HeadersExchange
from rabbitpy.exchange import TopicExchange
from rabbitpy.message import Message
from rabbitpy.amqp_queue import Queue
from rabbitpy.tx import Tx
from rabbitpy.simple import consume
from rabbitpy.simple import get
from rabbitpy.simple import publish
from rabbitpy.simple import create_queue
from rabbitpy.simple import delete_queue
from rabbitpy.simple import create_direct_exchange
from rabbitpy.simple import create_fanout_exchange
from rabbitpy.simple import create_topic_exchange
from rabbitpy.simple import delete_exchange
|
<commit_before>"""
rabbitpy, a pythonic RabbitMQ client
"""
__version__ = '0.14.0'
version = __version__
DEBUG = False
import logging
try:
from logging import NullHandler
except ImportError:
class NullHandler(logging.Handler):
"""Python 2.6 does not have a NullHandler"""
def emit(self, record):
"""Emit a record
:param record record: The record to emit
"""
pass
logging.getLogger('rabbitpy').addHandler(NullHandler())
from rabbitpy.connection import Connection
from rabbitpy.exchange import Exchange
from rabbitpy.message import Message
from rabbitpy.amqp_queue import Queue
from rabbitpy.tx import Tx
from rabbitpy.simple import consume
from rabbitpy.simple import get
from rabbitpy.simple import publish
from rabbitpy.simple import create_queue
from rabbitpy.simple import delete_queue
from rabbitpy.simple import create_direct_exchange
from rabbitpy.simple import create_fanout_exchange
from rabbitpy.simple import create_topic_exchange
from rabbitpy.simple import delete_exchange
<commit_msg>Add Channel and the convenience exchange classes<commit_after>"""
rabbitpy, a pythonic RabbitMQ client
"""
__version__ = '0.14.0'
version = __version__
DEBUG = False
import logging
try:
from logging import NullHandler
except ImportError:
class NullHandler(logging.Handler):
"""Python 2.6 does not have a NullHandler"""
def emit(self, record):
"""Emit a record
:param record record: The record to emit
"""
pass
logging.getLogger('rabbitpy').addHandler(NullHandler())
from rabbitpy.connection import Connection
from rabbitpy.channel import Channel
from rabbitpy.exchange import Exchange
from rabbitpy.exchange import DirectExchange
from rabbitpy.exchange import FanoutExchange
from rabbitpy.exchange import HeadersExchange
from rabbitpy.exchange import TopicExchange
from rabbitpy.message import Message
from rabbitpy.amqp_queue import Queue
from rabbitpy.tx import Tx
from rabbitpy.simple import consume
from rabbitpy.simple import get
from rabbitpy.simple import publish
from rabbitpy.simple import create_queue
from rabbitpy.simple import delete_queue
from rabbitpy.simple import create_direct_exchange
from rabbitpy.simple import create_fanout_exchange
from rabbitpy.simple import create_topic_exchange
from rabbitpy.simple import delete_exchange
|
d4cb09e9ffa645c97976c524a3d084172f091a16
|
p560m/subarray_sum.py
|
p560m/subarray_sum.py
|
from typing import List
from collections import defaultdict
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
sum_count = defaultdict(int)
sum_count[0] = 1
s, ans = 0, 0
for n in nums:
s += n
if s - k in sum_count:
ans += sum_count[s - k]
sum_count[s] += 1
return ans
# TESTS
tests = [
([1], 0, 0),
([1, 1, 1], 2, 2),
([1, 2, 3, 4, 5], 11, 0),
([3, 4, 7, 2, -3, 1, 4, 2], 7, 4),
]
for t in tests:
sol = Solution()
act = sol.subarraySum(t[0], t[1])
print("# of subarrays of", t[0], "sum to", t[1], "=>", act)
assert act == t[2]
|
from typing import List
from collections import defaultdict
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
sum_count = defaultdict(int)
sum_count[0] = 1
s, ans = 0, 0
for n in nums:
s += n
ans += sum_count[s - k]
sum_count[s] += 1
return ans
# TESTS
tests = [
([1], 0, 0),
([1, 1, 1], 2, 2),
([1, 2, 3, 4, 5], 11, 0),
([3, 4, 7, 2, -3, 1, 4, 2], 7, 4),
]
for t in tests:
sol = Solution()
act = sol.subarraySum(t[0], t[1])
print("# of subarrays of", t[0], "sum to", t[1], "=>", act)
assert act == t[2]
|
Update p560m subarray sum in Python
|
Update p560m subarray sum in Python
|
Python
|
mit
|
l33tdaima/l33tdaima,l33tdaima/l33tdaima,l33tdaima/l33tdaima,l33tdaima/l33tdaima,l33tdaima/l33tdaima
|
from typing import List
from collections import defaultdict
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
sum_count = defaultdict(int)
sum_count[0] = 1
s, ans = 0, 0
for n in nums:
s += n
if s - k in sum_count:
ans += sum_count[s - k]
sum_count[s] += 1
return ans
# TESTS
tests = [
([1], 0, 0),
([1, 1, 1], 2, 2),
([1, 2, 3, 4, 5], 11, 0),
([3, 4, 7, 2, -3, 1, 4, 2], 7, 4),
]
for t in tests:
sol = Solution()
act = sol.subarraySum(t[0], t[1])
print("# of subarrays of", t[0], "sum to", t[1], "=>", act)
assert act == t[2]
Update p560m subarray sum in Python
|
from typing import List
from collections import defaultdict
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
sum_count = defaultdict(int)
sum_count[0] = 1
s, ans = 0, 0
for n in nums:
s += n
ans += sum_count[s - k]
sum_count[s] += 1
return ans
# TESTS
tests = [
([1], 0, 0),
([1, 1, 1], 2, 2),
([1, 2, 3, 4, 5], 11, 0),
([3, 4, 7, 2, -3, 1, 4, 2], 7, 4),
]
for t in tests:
sol = Solution()
act = sol.subarraySum(t[0], t[1])
print("# of subarrays of", t[0], "sum to", t[1], "=>", act)
assert act == t[2]
|
<commit_before>from typing import List
from collections import defaultdict
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
sum_count = defaultdict(int)
sum_count[0] = 1
s, ans = 0, 0
for n in nums:
s += n
if s - k in sum_count:
ans += sum_count[s - k]
sum_count[s] += 1
return ans
# TESTS
tests = [
([1], 0, 0),
([1, 1, 1], 2, 2),
([1, 2, 3, 4, 5], 11, 0),
([3, 4, 7, 2, -3, 1, 4, 2], 7, 4),
]
for t in tests:
sol = Solution()
act = sol.subarraySum(t[0], t[1])
print("# of subarrays of", t[0], "sum to", t[1], "=>", act)
assert act == t[2]
<commit_msg>Update p560m subarray sum in Python<commit_after>
|
from typing import List
from collections import defaultdict
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
sum_count = defaultdict(int)
sum_count[0] = 1
s, ans = 0, 0
for n in nums:
s += n
ans += sum_count[s - k]
sum_count[s] += 1
return ans
# TESTS
tests = [
([1], 0, 0),
([1, 1, 1], 2, 2),
([1, 2, 3, 4, 5], 11, 0),
([3, 4, 7, 2, -3, 1, 4, 2], 7, 4),
]
for t in tests:
sol = Solution()
act = sol.subarraySum(t[0], t[1])
print("# of subarrays of", t[0], "sum to", t[1], "=>", act)
assert act == t[2]
|
from typing import List
from collections import defaultdict
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
sum_count = defaultdict(int)
sum_count[0] = 1
s, ans = 0, 0
for n in nums:
s += n
if s - k in sum_count:
ans += sum_count[s - k]
sum_count[s] += 1
return ans
# TESTS
tests = [
([1], 0, 0),
([1, 1, 1], 2, 2),
([1, 2, 3, 4, 5], 11, 0),
([3, 4, 7, 2, -3, 1, 4, 2], 7, 4),
]
for t in tests:
sol = Solution()
act = sol.subarraySum(t[0], t[1])
print("# of subarrays of", t[0], "sum to", t[1], "=>", act)
assert act == t[2]
Update p560m subarray sum in Pythonfrom typing import List
from collections import defaultdict
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
sum_count = defaultdict(int)
sum_count[0] = 1
s, ans = 0, 0
for n in nums:
s += n
ans += sum_count[s - k]
sum_count[s] += 1
return ans
# TESTS
tests = [
([1], 0, 0),
([1, 1, 1], 2, 2),
([1, 2, 3, 4, 5], 11, 0),
([3, 4, 7, 2, -3, 1, 4, 2], 7, 4),
]
for t in tests:
sol = Solution()
act = sol.subarraySum(t[0], t[1])
print("# of subarrays of", t[0], "sum to", t[1], "=>", act)
assert act == t[2]
|
<commit_before>from typing import List
from collections import defaultdict
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
sum_count = defaultdict(int)
sum_count[0] = 1
s, ans = 0, 0
for n in nums:
s += n
if s - k in sum_count:
ans += sum_count[s - k]
sum_count[s] += 1
return ans
# TESTS
tests = [
([1], 0, 0),
([1, 1, 1], 2, 2),
([1, 2, 3, 4, 5], 11, 0),
([3, 4, 7, 2, -3, 1, 4, 2], 7, 4),
]
for t in tests:
sol = Solution()
act = sol.subarraySum(t[0], t[1])
print("# of subarrays of", t[0], "sum to", t[1], "=>", act)
assert act == t[2]
<commit_msg>Update p560m subarray sum in Python<commit_after>from typing import List
from collections import defaultdict
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
sum_count = defaultdict(int)
sum_count[0] = 1
s, ans = 0, 0
for n in nums:
s += n
ans += sum_count[s - k]
sum_count[s] += 1
return ans
# TESTS
tests = [
([1], 0, 0),
([1, 1, 1], 2, 2),
([1, 2, 3, 4, 5], 11, 0),
([3, 4, 7, 2, -3, 1, 4, 2], 7, 4),
]
for t in tests:
sol = Solution()
act = sol.subarraySum(t[0], t[1])
print("# of subarrays of", t[0], "sum to", t[1], "=>", act)
assert act == t[2]
|
ffd39111a7b76e2cdec4e27501d0f5bfaba269d9
|
actor/app_logging.py
|
actor/app_logging.py
|
import errno
import os
import logging
def _mkdir_p(path):
try:
os.mkdir(path)
except OSError as exc:
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
def log_file_handler(app_name, log_level, log_dir):
app_log_dir = os.path.join(log_dir, app_name.lower())
_mkdir_p(app_log_dir)
log_name = "{}.log".format(log_level)
log_path = os.path.join(app_log_dir, log_name)
file_handler = logging.FileHandler(log_path)
file_handler.setLevel(logging.ERROR)
formatter = logging.Formatter(
fmt="%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]",
datefmt="%Y-%m-%d %H:%M:%S")
file_handler.setFormatter(formatter)
return file_handler
|
import errno
import os
import logging
def _mkdir_p(path):
ab_path = path
if not os.path.isabs(ab_path):
curr_dir = os.getcwd()
ab_path = os.path.join(curr_dir, path)
try:
os.makedirs(ab_path)
except OSError as exc:
if exc.errno == errno.EEXIST and os.path.isdir(ab_path):
pass
else:
raise
def log_file_handler(app_name, log_level, log_dir):
app_log_dir = os.path.join(log_dir, app_name.lower())
_mkdir_p(app_log_dir)
log_name = "{}.log".format(log_level)
log_path = os.path.join(app_log_dir, log_name)
file_handler = logging.FileHandler(log_path)
file_handler.setLevel(logging.ERROR)
formatter = logging.Formatter(
fmt="%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]",
datefmt="%Y-%m-%d %H:%M:%S")
file_handler.setFormatter(formatter)
return file_handler
|
Fix logging bug: mkdir -> makedirs.
|
Fix logging bug: mkdir -> makedirs.
|
Python
|
mit
|
cqumirrors/actor
|
import errno
import os
import logging
def _mkdir_p(path):
try:
os.mkdir(path)
except OSError as exc:
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
def log_file_handler(app_name, log_level, log_dir):
app_log_dir = os.path.join(log_dir, app_name.lower())
_mkdir_p(app_log_dir)
log_name = "{}.log".format(log_level)
log_path = os.path.join(app_log_dir, log_name)
file_handler = logging.FileHandler(log_path)
file_handler.setLevel(logging.ERROR)
formatter = logging.Formatter(
fmt="%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]",
datefmt="%Y-%m-%d %H:%M:%S")
file_handler.setFormatter(formatter)
return file_handler
Fix logging bug: mkdir -> makedirs.
|
import errno
import os
import logging
def _mkdir_p(path):
ab_path = path
if not os.path.isabs(ab_path):
curr_dir = os.getcwd()
ab_path = os.path.join(curr_dir, path)
try:
os.makedirs(ab_path)
except OSError as exc:
if exc.errno == errno.EEXIST and os.path.isdir(ab_path):
pass
else:
raise
def log_file_handler(app_name, log_level, log_dir):
app_log_dir = os.path.join(log_dir, app_name.lower())
_mkdir_p(app_log_dir)
log_name = "{}.log".format(log_level)
log_path = os.path.join(app_log_dir, log_name)
file_handler = logging.FileHandler(log_path)
file_handler.setLevel(logging.ERROR)
formatter = logging.Formatter(
fmt="%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]",
datefmt="%Y-%m-%d %H:%M:%S")
file_handler.setFormatter(formatter)
return file_handler
|
<commit_before>import errno
import os
import logging
def _mkdir_p(path):
try:
os.mkdir(path)
except OSError as exc:
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
def log_file_handler(app_name, log_level, log_dir):
app_log_dir = os.path.join(log_dir, app_name.lower())
_mkdir_p(app_log_dir)
log_name = "{}.log".format(log_level)
log_path = os.path.join(app_log_dir, log_name)
file_handler = logging.FileHandler(log_path)
file_handler.setLevel(logging.ERROR)
formatter = logging.Formatter(
fmt="%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]",
datefmt="%Y-%m-%d %H:%M:%S")
file_handler.setFormatter(formatter)
return file_handler
<commit_msg>Fix logging bug: mkdir -> makedirs.<commit_after>
|
import errno
import os
import logging
def _mkdir_p(path):
ab_path = path
if not os.path.isabs(ab_path):
curr_dir = os.getcwd()
ab_path = os.path.join(curr_dir, path)
try:
os.makedirs(ab_path)
except OSError as exc:
if exc.errno == errno.EEXIST and os.path.isdir(ab_path):
pass
else:
raise
def log_file_handler(app_name, log_level, log_dir):
app_log_dir = os.path.join(log_dir, app_name.lower())
_mkdir_p(app_log_dir)
log_name = "{}.log".format(log_level)
log_path = os.path.join(app_log_dir, log_name)
file_handler = logging.FileHandler(log_path)
file_handler.setLevel(logging.ERROR)
formatter = logging.Formatter(
fmt="%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]",
datefmt="%Y-%m-%d %H:%M:%S")
file_handler.setFormatter(formatter)
return file_handler
|
import errno
import os
import logging
def _mkdir_p(path):
try:
os.mkdir(path)
except OSError as exc:
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
def log_file_handler(app_name, log_level, log_dir):
app_log_dir = os.path.join(log_dir, app_name.lower())
_mkdir_p(app_log_dir)
log_name = "{}.log".format(log_level)
log_path = os.path.join(app_log_dir, log_name)
file_handler = logging.FileHandler(log_path)
file_handler.setLevel(logging.ERROR)
formatter = logging.Formatter(
fmt="%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]",
datefmt="%Y-%m-%d %H:%M:%S")
file_handler.setFormatter(formatter)
return file_handler
Fix logging bug: mkdir -> makedirs.import errno
import os
import logging
def _mkdir_p(path):
ab_path = path
if not os.path.isabs(ab_path):
curr_dir = os.getcwd()
ab_path = os.path.join(curr_dir, path)
try:
os.makedirs(ab_path)
except OSError as exc:
if exc.errno == errno.EEXIST and os.path.isdir(ab_path):
pass
else:
raise
def log_file_handler(app_name, log_level, log_dir):
app_log_dir = os.path.join(log_dir, app_name.lower())
_mkdir_p(app_log_dir)
log_name = "{}.log".format(log_level)
log_path = os.path.join(app_log_dir, log_name)
file_handler = logging.FileHandler(log_path)
file_handler.setLevel(logging.ERROR)
formatter = logging.Formatter(
fmt="%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]",
datefmt="%Y-%m-%d %H:%M:%S")
file_handler.setFormatter(formatter)
return file_handler
|
<commit_before>import errno
import os
import logging
def _mkdir_p(path):
try:
os.mkdir(path)
except OSError as exc:
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
def log_file_handler(app_name, log_level, log_dir):
app_log_dir = os.path.join(log_dir, app_name.lower())
_mkdir_p(app_log_dir)
log_name = "{}.log".format(log_level)
log_path = os.path.join(app_log_dir, log_name)
file_handler = logging.FileHandler(log_path)
file_handler.setLevel(logging.ERROR)
formatter = logging.Formatter(
fmt="%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]",
datefmt="%Y-%m-%d %H:%M:%S")
file_handler.setFormatter(formatter)
return file_handler
<commit_msg>Fix logging bug: mkdir -> makedirs.<commit_after>import errno
import os
import logging
def _mkdir_p(path):
ab_path = path
if not os.path.isabs(ab_path):
curr_dir = os.getcwd()
ab_path = os.path.join(curr_dir, path)
try:
os.makedirs(ab_path)
except OSError as exc:
if exc.errno == errno.EEXIST and os.path.isdir(ab_path):
pass
else:
raise
def log_file_handler(app_name, log_level, log_dir):
app_log_dir = os.path.join(log_dir, app_name.lower())
_mkdir_p(app_log_dir)
log_name = "{}.log".format(log_level)
log_path = os.path.join(app_log_dir, log_name)
file_handler = logging.FileHandler(log_path)
file_handler.setLevel(logging.ERROR)
formatter = logging.Formatter(
fmt="%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]",
datefmt="%Y-%m-%d %H:%M:%S")
file_handler.setFormatter(formatter)
return file_handler
|
9877bf47e3cd11070bac6377ea734ca20ff364ba
|
testing/python/setup_plan.py
|
testing/python/setup_plan.py
|
def test_show_fixtures_and_test(testdir):
p = testdir.makepyfile('''
import pytest
@pytest.fixture
def arg():
assert False
def test_arg(arg):
assert False
''')
result = testdir.runpytest("--setup-plan", p)
assert result.ret == 0
result.stdout.fnmatch_lines([
'*SETUP F arg*',
'*test_arg (fixtures used: arg)',
'*TEARDOWN F arg*',
])
|
def test_show_fixtures_and_test(testdir):
""" Verifies that fixtures are not executed. """
p = testdir.makepyfile('''
import pytest
@pytest.fixture
def arg():
assert False
def test_arg(arg):
assert False
''')
result = testdir.runpytest("--setup-plan", p)
assert result.ret == 0
result.stdout.fnmatch_lines([
'*SETUP F arg*',
'*test_arg (fixtures used: arg)',
'*TEARDOWN F arg*',
])
|
Improve commenting for setupplan unittest.
|
Improve commenting for setupplan unittest.
|
Python
|
mit
|
etataurov/pytest,pytest-dev/pytest,hpk42/pytest,skylarjhdownes/pytest,rmfitzpatrick/pytest,jaraco/pytest,MichaelAquilina/pytest,tomviner/pytest,ddboline/pytest,Akasurde/pytest,nicoddemus/pytest,The-Compiler/pytest,tgoodlet/pytest,hackebrot/pytest,nicoddemus/pytest,tareqalayan/pytest,txomon/pytest,eli-b/pytest,markshao/pytest,hpk42/pytest,tomviner/pytest,pfctdayelise/pytest,RonnyPfannschmidt/pytest,malinoff/pytest,alfredodeza/pytest,davidszotten/pytest,vmalloc/dessert,The-Compiler/pytest,flub/pytest
|
def test_show_fixtures_and_test(testdir):
p = testdir.makepyfile('''
import pytest
@pytest.fixture
def arg():
assert False
def test_arg(arg):
assert False
''')
result = testdir.runpytest("--setup-plan", p)
assert result.ret == 0
result.stdout.fnmatch_lines([
'*SETUP F arg*',
'*test_arg (fixtures used: arg)',
'*TEARDOWN F arg*',
])
Improve commenting for setupplan unittest.
|
def test_show_fixtures_and_test(testdir):
""" Verifies that fixtures are not executed. """
p = testdir.makepyfile('''
import pytest
@pytest.fixture
def arg():
assert False
def test_arg(arg):
assert False
''')
result = testdir.runpytest("--setup-plan", p)
assert result.ret == 0
result.stdout.fnmatch_lines([
'*SETUP F arg*',
'*test_arg (fixtures used: arg)',
'*TEARDOWN F arg*',
])
|
<commit_before>def test_show_fixtures_and_test(testdir):
p = testdir.makepyfile('''
import pytest
@pytest.fixture
def arg():
assert False
def test_arg(arg):
assert False
''')
result = testdir.runpytest("--setup-plan", p)
assert result.ret == 0
result.stdout.fnmatch_lines([
'*SETUP F arg*',
'*test_arg (fixtures used: arg)',
'*TEARDOWN F arg*',
])
<commit_msg>Improve commenting for setupplan unittest.<commit_after>
|
def test_show_fixtures_and_test(testdir):
""" Verifies that fixtures are not executed. """
p = testdir.makepyfile('''
import pytest
@pytest.fixture
def arg():
assert False
def test_arg(arg):
assert False
''')
result = testdir.runpytest("--setup-plan", p)
assert result.ret == 0
result.stdout.fnmatch_lines([
'*SETUP F arg*',
'*test_arg (fixtures used: arg)',
'*TEARDOWN F arg*',
])
|
def test_show_fixtures_and_test(testdir):
p = testdir.makepyfile('''
import pytest
@pytest.fixture
def arg():
assert False
def test_arg(arg):
assert False
''')
result = testdir.runpytest("--setup-plan", p)
assert result.ret == 0
result.stdout.fnmatch_lines([
'*SETUP F arg*',
'*test_arg (fixtures used: arg)',
'*TEARDOWN F arg*',
])
Improve commenting for setupplan unittest.def test_show_fixtures_and_test(testdir):
""" Verifies that fixtures are not executed. """
p = testdir.makepyfile('''
import pytest
@pytest.fixture
def arg():
assert False
def test_arg(arg):
assert False
''')
result = testdir.runpytest("--setup-plan", p)
assert result.ret == 0
result.stdout.fnmatch_lines([
'*SETUP F arg*',
'*test_arg (fixtures used: arg)',
'*TEARDOWN F arg*',
])
|
<commit_before>def test_show_fixtures_and_test(testdir):
p = testdir.makepyfile('''
import pytest
@pytest.fixture
def arg():
assert False
def test_arg(arg):
assert False
''')
result = testdir.runpytest("--setup-plan", p)
assert result.ret == 0
result.stdout.fnmatch_lines([
'*SETUP F arg*',
'*test_arg (fixtures used: arg)',
'*TEARDOWN F arg*',
])
<commit_msg>Improve commenting for setupplan unittest.<commit_after>def test_show_fixtures_and_test(testdir):
""" Verifies that fixtures are not executed. """
p = testdir.makepyfile('''
import pytest
@pytest.fixture
def arg():
assert False
def test_arg(arg):
assert False
''')
result = testdir.runpytest("--setup-plan", p)
assert result.ret == 0
result.stdout.fnmatch_lines([
'*SETUP F arg*',
'*test_arg (fixtures used: arg)',
'*TEARDOWN F arg*',
])
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.