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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
656780b827202fc08992321ec2a98e91cb02da3b
|
utilities/__init__.py
|
utilities/__init__.py
|
#! /usr/bin/env python
from subprocess import Popen, PIPE
def _popen(cmd):
"""
Fork the specified command, returning a tuple of (stdout, stderr)
"""
return Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE).communicate()
|
#! /usr/bin/env python
from subprocess import Popen, PIPE
def launch(cmd):
"""
Fork the specified command, returning a tuple of (stdout, stderr)
"""
return Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE).communicate()
def get_stdout(cmd):
"""
Fork the specified command, returning stdout
"""
return launch(cmd)[0]
|
Add a wrapper to get just stdout back
|
Add a wrapper to get just stdout back
|
Python
|
mit
|
IanLee1521/utilities
|
#! /usr/bin/env python
from subprocess import Popen, PIPE
def _popen(cmd):
"""
Fork the specified command, returning a tuple of (stdout, stderr)
"""
return Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE).communicate()
Add a wrapper to get just stdout back
|
#! /usr/bin/env python
from subprocess import Popen, PIPE
def launch(cmd):
"""
Fork the specified command, returning a tuple of (stdout, stderr)
"""
return Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE).communicate()
def get_stdout(cmd):
"""
Fork the specified command, returning stdout
"""
return launch(cmd)[0]
|
<commit_before>#! /usr/bin/env python
from subprocess import Popen, PIPE
def _popen(cmd):
"""
Fork the specified command, returning a tuple of (stdout, stderr)
"""
return Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE).communicate()
<commit_msg>Add a wrapper to get just stdout back<commit_after>
|
#! /usr/bin/env python
from subprocess import Popen, PIPE
def launch(cmd):
"""
Fork the specified command, returning a tuple of (stdout, stderr)
"""
return Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE).communicate()
def get_stdout(cmd):
"""
Fork the specified command, returning stdout
"""
return launch(cmd)[0]
|
#! /usr/bin/env python
from subprocess import Popen, PIPE
def _popen(cmd):
"""
Fork the specified command, returning a tuple of (stdout, stderr)
"""
return Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE).communicate()
Add a wrapper to get just stdout back#! /usr/bin/env python
from subprocess import Popen, PIPE
def launch(cmd):
"""
Fork the specified command, returning a tuple of (stdout, stderr)
"""
return Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE).communicate()
def get_stdout(cmd):
"""
Fork the specified command, returning stdout
"""
return launch(cmd)[0]
|
<commit_before>#! /usr/bin/env python
from subprocess import Popen, PIPE
def _popen(cmd):
"""
Fork the specified command, returning a tuple of (stdout, stderr)
"""
return Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE).communicate()
<commit_msg>Add a wrapper to get just stdout back<commit_after>#! /usr/bin/env python
from subprocess import Popen, PIPE
def launch(cmd):
"""
Fork the specified command, returning a tuple of (stdout, stderr)
"""
return Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE).communicate()
def get_stdout(cmd):
"""
Fork the specified command, returning stdout
"""
return launch(cmd)[0]
|
de3809a00703c5eaaaec856b152a2418debbb6c6
|
plugins/Tools/MirrorTool/__init__.py
|
plugins/Tools/MirrorTool/__init__.py
|
from . import MirrorTool
def getMetaData():
return {
'type': 'tool',
'plugin': {
'name': 'Mirror Tool'
},
'tool': {
'name': 'Mirror',
'description': 'Mirror Object'
},
}
def register(app):
return MirrorTool.MirrorTool()
|
from . import MirrorTool
def getMetaData():
return {
'type': 'tool',
'plugin': {
'name': 'Mirror Tool'
},
'tool': {
'name': 'Mirror',
'description': 'Mirror Object',
'icon': 'mirror.png'
},
}
def register(app):
return MirrorTool.MirrorTool()
|
Use the right icon for the mirror tool
|
Use the right icon for the mirror tool
|
Python
|
agpl-3.0
|
onitake/Uranium,onitake/Uranium
|
from . import MirrorTool
def getMetaData():
return {
'type': 'tool',
'plugin': {
'name': 'Mirror Tool'
},
'tool': {
'name': 'Mirror',
'description': 'Mirror Object'
},
}
def register(app):
return MirrorTool.MirrorTool()
Use the right icon for the mirror tool
|
from . import MirrorTool
def getMetaData():
return {
'type': 'tool',
'plugin': {
'name': 'Mirror Tool'
},
'tool': {
'name': 'Mirror',
'description': 'Mirror Object',
'icon': 'mirror.png'
},
}
def register(app):
return MirrorTool.MirrorTool()
|
<commit_before>from . import MirrorTool
def getMetaData():
return {
'type': 'tool',
'plugin': {
'name': 'Mirror Tool'
},
'tool': {
'name': 'Mirror',
'description': 'Mirror Object'
},
}
def register(app):
return MirrorTool.MirrorTool()
<commit_msg>Use the right icon for the mirror tool<commit_after>
|
from . import MirrorTool
def getMetaData():
return {
'type': 'tool',
'plugin': {
'name': 'Mirror Tool'
},
'tool': {
'name': 'Mirror',
'description': 'Mirror Object',
'icon': 'mirror.png'
},
}
def register(app):
return MirrorTool.MirrorTool()
|
from . import MirrorTool
def getMetaData():
return {
'type': 'tool',
'plugin': {
'name': 'Mirror Tool'
},
'tool': {
'name': 'Mirror',
'description': 'Mirror Object'
},
}
def register(app):
return MirrorTool.MirrorTool()
Use the right icon for the mirror toolfrom . import MirrorTool
def getMetaData():
return {
'type': 'tool',
'plugin': {
'name': 'Mirror Tool'
},
'tool': {
'name': 'Mirror',
'description': 'Mirror Object',
'icon': 'mirror.png'
},
}
def register(app):
return MirrorTool.MirrorTool()
|
<commit_before>from . import MirrorTool
def getMetaData():
return {
'type': 'tool',
'plugin': {
'name': 'Mirror Tool'
},
'tool': {
'name': 'Mirror',
'description': 'Mirror Object'
},
}
def register(app):
return MirrorTool.MirrorTool()
<commit_msg>Use the right icon for the mirror tool<commit_after>from . import MirrorTool
def getMetaData():
return {
'type': 'tool',
'plugin': {
'name': 'Mirror Tool'
},
'tool': {
'name': 'Mirror',
'description': 'Mirror Object',
'icon': 'mirror.png'
},
}
def register(app):
return MirrorTool.MirrorTool()
|
1724d05226a301bcedfebe963006818461c1b457
|
vispy/app/__init__.py
|
vispy/app/__init__.py
|
# -*- coding: utf-8 -*-
# Copyright (c) 2014, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
"""
The app module defines three classes: Application, Canvas, and Timer.
On loading, vispy creates a default Application instance which can be used
via functions in the module's namespace.
"""
from __future__ import division
from .application import Application # noqa
from ._default_app import use_app, create, run, quit, process_events # noqa
from .canvas import Canvas, MouseEvent, KeyEvent # noqa
from .inputhook import set_interactive
from .timer import Timer # noqa
from . import base # noqa
|
# -*- coding: utf-8 -*-
# Copyright (c) 2014, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
"""
The app module defines three classes: Application, Canvas, and Timer.
On loading, vispy creates a default Application instance which can be used
via functions in the module's namespace.
"""
from __future__ import division
from .application import Application # noqa
from ._default_app import use_app, create, run, quit, process_events # noqa
from .canvas import Canvas, MouseEvent, KeyEvent # noqa
from .inputhook import set_interactive #noqa
from .timer import Timer # noqa
from . import base # noqa
|
Fix for the tests, not complaining allowed about set_interactive not being used.
|
Fix for the tests, not complaining allowed about set_interactive not being used.
|
Python
|
bsd-3-clause
|
bollu/vispy,sbtlaarzc/vispy,michaelaye/vispy,jay3sh/vispy,ghisvail/vispy,dchilds7/Deysha-Star-Formation,Eric89GXL/vispy,QuLogic/vispy,dchilds7/Deysha-Star-Formation,jdreaver/vispy,RebeccaWPerry/vispy,hronoses/vispy,bollu/vispy,jdreaver/vispy,inclement/vispy,sbtlaarzc/vispy,QuLogic/vispy,julienr/vispy,michaelaye/vispy,Eric89GXL/vispy,ghisvail/vispy,drufat/vispy,julienr/vispy,jay3sh/vispy,RebeccaWPerry/vispy,sh4wn/vispy,sh4wn/vispy,dchilds7/Deysha-Star-Formation,srinathv/vispy,QuLogic/vispy,ghisvail/vispy,sbtlaarzc/vispy,inclement/vispy,jdreaver/vispy,srinathv/vispy,Eric89GXL/vispy,kkuunnddaannkk/vispy,bollu/vispy,srinathv/vispy,drufat/vispy,RebeccaWPerry/vispy,drufat/vispy,kkuunnddaannkk/vispy,michaelaye/vispy,hronoses/vispy,kkuunnddaannkk/vispy,julienr/vispy,hronoses/vispy,jay3sh/vispy,inclement/vispy,sh4wn/vispy
|
# -*- coding: utf-8 -*-
# Copyright (c) 2014, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
"""
The app module defines three classes: Application, Canvas, and Timer.
On loading, vispy creates a default Application instance which can be used
via functions in the module's namespace.
"""
from __future__ import division
from .application import Application # noqa
from ._default_app import use_app, create, run, quit, process_events # noqa
from .canvas import Canvas, MouseEvent, KeyEvent # noqa
from .inputhook import set_interactive
from .timer import Timer # noqa
from . import base # noqa
Fix for the tests, not complaining allowed about set_interactive not being used.
|
# -*- coding: utf-8 -*-
# Copyright (c) 2014, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
"""
The app module defines three classes: Application, Canvas, and Timer.
On loading, vispy creates a default Application instance which can be used
via functions in the module's namespace.
"""
from __future__ import division
from .application import Application # noqa
from ._default_app import use_app, create, run, quit, process_events # noqa
from .canvas import Canvas, MouseEvent, KeyEvent # noqa
from .inputhook import set_interactive #noqa
from .timer import Timer # noqa
from . import base # noqa
|
<commit_before># -*- coding: utf-8 -*-
# Copyright (c) 2014, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
"""
The app module defines three classes: Application, Canvas, and Timer.
On loading, vispy creates a default Application instance which can be used
via functions in the module's namespace.
"""
from __future__ import division
from .application import Application # noqa
from ._default_app import use_app, create, run, quit, process_events # noqa
from .canvas import Canvas, MouseEvent, KeyEvent # noqa
from .inputhook import set_interactive
from .timer import Timer # noqa
from . import base # noqa
<commit_msg>Fix for the tests, not complaining allowed about set_interactive not being used.<commit_after>
|
# -*- coding: utf-8 -*-
# Copyright (c) 2014, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
"""
The app module defines three classes: Application, Canvas, and Timer.
On loading, vispy creates a default Application instance which can be used
via functions in the module's namespace.
"""
from __future__ import division
from .application import Application # noqa
from ._default_app import use_app, create, run, quit, process_events # noqa
from .canvas import Canvas, MouseEvent, KeyEvent # noqa
from .inputhook import set_interactive #noqa
from .timer import Timer # noqa
from . import base # noqa
|
# -*- coding: utf-8 -*-
# Copyright (c) 2014, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
"""
The app module defines three classes: Application, Canvas, and Timer.
On loading, vispy creates a default Application instance which can be used
via functions in the module's namespace.
"""
from __future__ import division
from .application import Application # noqa
from ._default_app import use_app, create, run, quit, process_events # noqa
from .canvas import Canvas, MouseEvent, KeyEvent # noqa
from .inputhook import set_interactive
from .timer import Timer # noqa
from . import base # noqa
Fix for the tests, not complaining allowed about set_interactive not being used.# -*- coding: utf-8 -*-
# Copyright (c) 2014, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
"""
The app module defines three classes: Application, Canvas, and Timer.
On loading, vispy creates a default Application instance which can be used
via functions in the module's namespace.
"""
from __future__ import division
from .application import Application # noqa
from ._default_app import use_app, create, run, quit, process_events # noqa
from .canvas import Canvas, MouseEvent, KeyEvent # noqa
from .inputhook import set_interactive #noqa
from .timer import Timer # noqa
from . import base # noqa
|
<commit_before># -*- coding: utf-8 -*-
# Copyright (c) 2014, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
"""
The app module defines three classes: Application, Canvas, and Timer.
On loading, vispy creates a default Application instance which can be used
via functions in the module's namespace.
"""
from __future__ import division
from .application import Application # noqa
from ._default_app import use_app, create, run, quit, process_events # noqa
from .canvas import Canvas, MouseEvent, KeyEvent # noqa
from .inputhook import set_interactive
from .timer import Timer # noqa
from . import base # noqa
<commit_msg>Fix for the tests, not complaining allowed about set_interactive not being used.<commit_after># -*- coding: utf-8 -*-
# Copyright (c) 2014, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
"""
The app module defines three classes: Application, Canvas, and Timer.
On loading, vispy creates a default Application instance which can be used
via functions in the module's namespace.
"""
from __future__ import division
from .application import Application # noqa
from ._default_app import use_app, create, run, quit, process_events # noqa
from .canvas import Canvas, MouseEvent, KeyEvent # noqa
from .inputhook import set_interactive #noqa
from .timer import Timer # noqa
from . import base # noqa
|
0daa2132c071cb667aca5dbc416872a278e91a2b
|
pycoin/coins/groestlcoin/hash.py
|
pycoin/coins/groestlcoin/hash.py
|
import hashlib
import groestlcoin_hash
from pycoin.encoding.hexbytes import bytes_as_revhex
def sha256(data):
return bytes_as_revhex(hashlib.sha256(data).digest())
def groestlHash(data):
"""Groestl-512 compound hash."""
return bytes_as_revhex(groestlcoin_hash.getHash(data, len(data)))
|
import hashlib
from pycoin.encoding.hexbytes import bytes_as_revhex
def sha256(data):
return bytes_as_revhex(hashlib.sha256(data).digest())
def groestlHash(data):
"""Groestl-512 compound hash."""
try:
import groestlcoin_hash
except ImportError:
t = 'Groestlcoin requires the groestlcoin_hash package ("pip install groestlcoin_hash").'
print(t)
raise ImportError(t)
return bytes_as_revhex(groestlcoin_hash.getHash(data, len(data)))
|
Raise ImportError when GRS is used without dependency
|
Raise ImportError when GRS is used without dependency
|
Python
|
mit
|
richardkiss/pycoin,richardkiss/pycoin
|
import hashlib
import groestlcoin_hash
from pycoin.encoding.hexbytes import bytes_as_revhex
def sha256(data):
return bytes_as_revhex(hashlib.sha256(data).digest())
def groestlHash(data):
"""Groestl-512 compound hash."""
return bytes_as_revhex(groestlcoin_hash.getHash(data, len(data)))
Raise ImportError when GRS is used without dependency
|
import hashlib
from pycoin.encoding.hexbytes import bytes_as_revhex
def sha256(data):
return bytes_as_revhex(hashlib.sha256(data).digest())
def groestlHash(data):
"""Groestl-512 compound hash."""
try:
import groestlcoin_hash
except ImportError:
t = 'Groestlcoin requires the groestlcoin_hash package ("pip install groestlcoin_hash").'
print(t)
raise ImportError(t)
return bytes_as_revhex(groestlcoin_hash.getHash(data, len(data)))
|
<commit_before>import hashlib
import groestlcoin_hash
from pycoin.encoding.hexbytes import bytes_as_revhex
def sha256(data):
return bytes_as_revhex(hashlib.sha256(data).digest())
def groestlHash(data):
"""Groestl-512 compound hash."""
return bytes_as_revhex(groestlcoin_hash.getHash(data, len(data)))
<commit_msg>Raise ImportError when GRS is used without dependency<commit_after>
|
import hashlib
from pycoin.encoding.hexbytes import bytes_as_revhex
def sha256(data):
return bytes_as_revhex(hashlib.sha256(data).digest())
def groestlHash(data):
"""Groestl-512 compound hash."""
try:
import groestlcoin_hash
except ImportError:
t = 'Groestlcoin requires the groestlcoin_hash package ("pip install groestlcoin_hash").'
print(t)
raise ImportError(t)
return bytes_as_revhex(groestlcoin_hash.getHash(data, len(data)))
|
import hashlib
import groestlcoin_hash
from pycoin.encoding.hexbytes import bytes_as_revhex
def sha256(data):
return bytes_as_revhex(hashlib.sha256(data).digest())
def groestlHash(data):
"""Groestl-512 compound hash."""
return bytes_as_revhex(groestlcoin_hash.getHash(data, len(data)))
Raise ImportError when GRS is used without dependencyimport hashlib
from pycoin.encoding.hexbytes import bytes_as_revhex
def sha256(data):
return bytes_as_revhex(hashlib.sha256(data).digest())
def groestlHash(data):
"""Groestl-512 compound hash."""
try:
import groestlcoin_hash
except ImportError:
t = 'Groestlcoin requires the groestlcoin_hash package ("pip install groestlcoin_hash").'
print(t)
raise ImportError(t)
return bytes_as_revhex(groestlcoin_hash.getHash(data, len(data)))
|
<commit_before>import hashlib
import groestlcoin_hash
from pycoin.encoding.hexbytes import bytes_as_revhex
def sha256(data):
return bytes_as_revhex(hashlib.sha256(data).digest())
def groestlHash(data):
"""Groestl-512 compound hash."""
return bytes_as_revhex(groestlcoin_hash.getHash(data, len(data)))
<commit_msg>Raise ImportError when GRS is used without dependency<commit_after>import hashlib
from pycoin.encoding.hexbytes import bytes_as_revhex
def sha256(data):
return bytes_as_revhex(hashlib.sha256(data).digest())
def groestlHash(data):
"""Groestl-512 compound hash."""
try:
import groestlcoin_hash
except ImportError:
t = 'Groestlcoin requires the groestlcoin_hash package ("pip install groestlcoin_hash").'
print(t)
raise ImportError(t)
return bytes_as_revhex(groestlcoin_hash.getHash(data, len(data)))
|
b1b8e06b2b0ae6c79b94bd8e7b0b49721b7bdc13
|
web/attempts/tests.py
|
web/attempts/tests.py
|
from django.test import TestCase
# Create your tests here.
|
from django.test import TestCase
from rest_framework.test import APIClient
from users.models import User
# Create your tests here.
class TokenLoginTestCase(TestCase):
fixtures = ['users.json']
def testAttemptSubmit(self):
user = User.objects.get(username='matija')
client = APIClient()
client.credentials(HTTP_AUTHORIZATION='Token ' + user.auth_token.key)
response = client.post('/api/attempts/submit/',
[
{
"solution": "\ndef linearna(a, b):\\n return -b / a\\n",
"valid": True,
"feedback": ["prvi", "drugi feedbk"],
"secret": [], "part": 1
},
{
"solution": "\\nimport math\\n\\ndef ploscina(n, a):\\n"
"return 0.25 a**2 n / math.tan(math.pi / n)",
"valid": True,
"feedback": [],
"secret": [],
"part": 2
}
],
format='json'
)
self.assertEqual(response.status_code, 200)
|
Add simple Attempt submit test
|
Add simple Attempt submit test
|
Python
|
agpl-3.0
|
matijapretnar/projekt-tomo,ul-fmf/projekt-tomo,matijapretnar/projekt-tomo,ul-fmf/projekt-tomo,ul-fmf/projekt-tomo,ul-fmf/projekt-tomo,matijapretnar/projekt-tomo,matijapretnar/projekt-tomo,ul-fmf/projekt-tomo,ul-fmf/projekt-tomo,matijapretnar/projekt-tomo
|
from django.test import TestCase
# Create your tests here.
Add simple Attempt submit test
|
from django.test import TestCase
from rest_framework.test import APIClient
from users.models import User
# Create your tests here.
class TokenLoginTestCase(TestCase):
fixtures = ['users.json']
def testAttemptSubmit(self):
user = User.objects.get(username='matija')
client = APIClient()
client.credentials(HTTP_AUTHORIZATION='Token ' + user.auth_token.key)
response = client.post('/api/attempts/submit/',
[
{
"solution": "\ndef linearna(a, b):\\n return -b / a\\n",
"valid": True,
"feedback": ["prvi", "drugi feedbk"],
"secret": [], "part": 1
},
{
"solution": "\\nimport math\\n\\ndef ploscina(n, a):\\n"
"return 0.25 a**2 n / math.tan(math.pi / n)",
"valid": True,
"feedback": [],
"secret": [],
"part": 2
}
],
format='json'
)
self.assertEqual(response.status_code, 200)
|
<commit_before>from django.test import TestCase
# Create your tests here.
<commit_msg>Add simple Attempt submit test<commit_after>
|
from django.test import TestCase
from rest_framework.test import APIClient
from users.models import User
# Create your tests here.
class TokenLoginTestCase(TestCase):
fixtures = ['users.json']
def testAttemptSubmit(self):
user = User.objects.get(username='matija')
client = APIClient()
client.credentials(HTTP_AUTHORIZATION='Token ' + user.auth_token.key)
response = client.post('/api/attempts/submit/',
[
{
"solution": "\ndef linearna(a, b):\\n return -b / a\\n",
"valid": True,
"feedback": ["prvi", "drugi feedbk"],
"secret": [], "part": 1
},
{
"solution": "\\nimport math\\n\\ndef ploscina(n, a):\\n"
"return 0.25 a**2 n / math.tan(math.pi / n)",
"valid": True,
"feedback": [],
"secret": [],
"part": 2
}
],
format='json'
)
self.assertEqual(response.status_code, 200)
|
from django.test import TestCase
# Create your tests here.
Add simple Attempt submit testfrom django.test import TestCase
from rest_framework.test import APIClient
from users.models import User
# Create your tests here.
class TokenLoginTestCase(TestCase):
fixtures = ['users.json']
def testAttemptSubmit(self):
user = User.objects.get(username='matija')
client = APIClient()
client.credentials(HTTP_AUTHORIZATION='Token ' + user.auth_token.key)
response = client.post('/api/attempts/submit/',
[
{
"solution": "\ndef linearna(a, b):\\n return -b / a\\n",
"valid": True,
"feedback": ["prvi", "drugi feedbk"],
"secret": [], "part": 1
},
{
"solution": "\\nimport math\\n\\ndef ploscina(n, a):\\n"
"return 0.25 a**2 n / math.tan(math.pi / n)",
"valid": True,
"feedback": [],
"secret": [],
"part": 2
}
],
format='json'
)
self.assertEqual(response.status_code, 200)
|
<commit_before>from django.test import TestCase
# Create your tests here.
<commit_msg>Add simple Attempt submit test<commit_after>from django.test import TestCase
from rest_framework.test import APIClient
from users.models import User
# Create your tests here.
class TokenLoginTestCase(TestCase):
fixtures = ['users.json']
def testAttemptSubmit(self):
user = User.objects.get(username='matija')
client = APIClient()
client.credentials(HTTP_AUTHORIZATION='Token ' + user.auth_token.key)
response = client.post('/api/attempts/submit/',
[
{
"solution": "\ndef linearna(a, b):\\n return -b / a\\n",
"valid": True,
"feedback": ["prvi", "drugi feedbk"],
"secret": [], "part": 1
},
{
"solution": "\\nimport math\\n\\ndef ploscina(n, a):\\n"
"return 0.25 a**2 n / math.tan(math.pi / n)",
"valid": True,
"feedback": [],
"secret": [],
"part": 2
}
],
format='json'
)
self.assertEqual(response.status_code, 200)
|
4ed701a7afad4c8c3c04097e449e930cc4545e0d
|
mendel/admin.py
|
mendel/admin.py
|
from django.contrib import admin
from import_export import resources
from import_export.admin import ImportExportModelAdmin
from mendel.models import Keyword, Category, Document, Context, Review
class KeywordAdmin(ImportExportModelAdmin):
pass
class CategoryAdmin(ImportExportModelAdmin):
pass
class DocumentAdmin(ImportExportModelAdmin):
pass
class ContextAdmin(ImportExportModelAdmin):
pass
class ReviewAdmin(ImportExportModelAdmin):
pass
admin.site.register(Keyword, KeywordAdmin)
admin.site.register(Category, CategoryAdmin)
admin.site.register(Document, DocumentAdmin)
admin.site.register(Context, ContextAdmin)
admin.site.register(Review, ReviewAdmin)
|
from django.contrib import admin
from import_export import resources
from import_export.admin import ImportExportModelAdmin
from mendel.models import Keyword, Category, Document, Context, Review
class KeywordAdmin(ImportExportModelAdmin):
list_display = ('id', 'name')
pass
class CategoryAdmin(ImportExportModelAdmin):
list_display = ('id', 'name')
pass
class DocumentAdmin(ImportExportModelAdmin):
list_display = ('id', 'title', 'description')
pass
class ContextAdmin(ImportExportModelAdmin):
list_display = ('keyword', 'text', 'document')
pass
class ReviewAdmin(ImportExportModelAdmin):
list_display = ('keyword', 'category', 'user', 'status')
pass
admin.site.register(Keyword, KeywordAdmin)
admin.site.register(Category, CategoryAdmin)
admin.site.register(Document, DocumentAdmin)
admin.site.register(Context, ContextAdmin)
admin.site.register(Review, ReviewAdmin)
|
Add list_displays for Admin views
|
Add list_displays for Admin views
|
Python
|
agpl-3.0
|
Architizer/mendel,Architizer/mendel,Architizer/mendel,Architizer/mendel
|
from django.contrib import admin
from import_export import resources
from import_export.admin import ImportExportModelAdmin
from mendel.models import Keyword, Category, Document, Context, Review
class KeywordAdmin(ImportExportModelAdmin):
pass
class CategoryAdmin(ImportExportModelAdmin):
pass
class DocumentAdmin(ImportExportModelAdmin):
pass
class ContextAdmin(ImportExportModelAdmin):
pass
class ReviewAdmin(ImportExportModelAdmin):
pass
admin.site.register(Keyword, KeywordAdmin)
admin.site.register(Category, CategoryAdmin)
admin.site.register(Document, DocumentAdmin)
admin.site.register(Context, ContextAdmin)
admin.site.register(Review, ReviewAdmin)Add list_displays for Admin views
|
from django.contrib import admin
from import_export import resources
from import_export.admin import ImportExportModelAdmin
from mendel.models import Keyword, Category, Document, Context, Review
class KeywordAdmin(ImportExportModelAdmin):
list_display = ('id', 'name')
pass
class CategoryAdmin(ImportExportModelAdmin):
list_display = ('id', 'name')
pass
class DocumentAdmin(ImportExportModelAdmin):
list_display = ('id', 'title', 'description')
pass
class ContextAdmin(ImportExportModelAdmin):
list_display = ('keyword', 'text', 'document')
pass
class ReviewAdmin(ImportExportModelAdmin):
list_display = ('keyword', 'category', 'user', 'status')
pass
admin.site.register(Keyword, KeywordAdmin)
admin.site.register(Category, CategoryAdmin)
admin.site.register(Document, DocumentAdmin)
admin.site.register(Context, ContextAdmin)
admin.site.register(Review, ReviewAdmin)
|
<commit_before>from django.contrib import admin
from import_export import resources
from import_export.admin import ImportExportModelAdmin
from mendel.models import Keyword, Category, Document, Context, Review
class KeywordAdmin(ImportExportModelAdmin):
pass
class CategoryAdmin(ImportExportModelAdmin):
pass
class DocumentAdmin(ImportExportModelAdmin):
pass
class ContextAdmin(ImportExportModelAdmin):
pass
class ReviewAdmin(ImportExportModelAdmin):
pass
admin.site.register(Keyword, KeywordAdmin)
admin.site.register(Category, CategoryAdmin)
admin.site.register(Document, DocumentAdmin)
admin.site.register(Context, ContextAdmin)
admin.site.register(Review, ReviewAdmin)<commit_msg>Add list_displays for Admin views<commit_after>
|
from django.contrib import admin
from import_export import resources
from import_export.admin import ImportExportModelAdmin
from mendel.models import Keyword, Category, Document, Context, Review
class KeywordAdmin(ImportExportModelAdmin):
list_display = ('id', 'name')
pass
class CategoryAdmin(ImportExportModelAdmin):
list_display = ('id', 'name')
pass
class DocumentAdmin(ImportExportModelAdmin):
list_display = ('id', 'title', 'description')
pass
class ContextAdmin(ImportExportModelAdmin):
list_display = ('keyword', 'text', 'document')
pass
class ReviewAdmin(ImportExportModelAdmin):
list_display = ('keyword', 'category', 'user', 'status')
pass
admin.site.register(Keyword, KeywordAdmin)
admin.site.register(Category, CategoryAdmin)
admin.site.register(Document, DocumentAdmin)
admin.site.register(Context, ContextAdmin)
admin.site.register(Review, ReviewAdmin)
|
from django.contrib import admin
from import_export import resources
from import_export.admin import ImportExportModelAdmin
from mendel.models import Keyword, Category, Document, Context, Review
class KeywordAdmin(ImportExportModelAdmin):
pass
class CategoryAdmin(ImportExportModelAdmin):
pass
class DocumentAdmin(ImportExportModelAdmin):
pass
class ContextAdmin(ImportExportModelAdmin):
pass
class ReviewAdmin(ImportExportModelAdmin):
pass
admin.site.register(Keyword, KeywordAdmin)
admin.site.register(Category, CategoryAdmin)
admin.site.register(Document, DocumentAdmin)
admin.site.register(Context, ContextAdmin)
admin.site.register(Review, ReviewAdmin)Add list_displays for Admin viewsfrom django.contrib import admin
from import_export import resources
from import_export.admin import ImportExportModelAdmin
from mendel.models import Keyword, Category, Document, Context, Review
class KeywordAdmin(ImportExportModelAdmin):
list_display = ('id', 'name')
pass
class CategoryAdmin(ImportExportModelAdmin):
list_display = ('id', 'name')
pass
class DocumentAdmin(ImportExportModelAdmin):
list_display = ('id', 'title', 'description')
pass
class ContextAdmin(ImportExportModelAdmin):
list_display = ('keyword', 'text', 'document')
pass
class ReviewAdmin(ImportExportModelAdmin):
list_display = ('keyword', 'category', 'user', 'status')
pass
admin.site.register(Keyword, KeywordAdmin)
admin.site.register(Category, CategoryAdmin)
admin.site.register(Document, DocumentAdmin)
admin.site.register(Context, ContextAdmin)
admin.site.register(Review, ReviewAdmin)
|
<commit_before>from django.contrib import admin
from import_export import resources
from import_export.admin import ImportExportModelAdmin
from mendel.models import Keyword, Category, Document, Context, Review
class KeywordAdmin(ImportExportModelAdmin):
pass
class CategoryAdmin(ImportExportModelAdmin):
pass
class DocumentAdmin(ImportExportModelAdmin):
pass
class ContextAdmin(ImportExportModelAdmin):
pass
class ReviewAdmin(ImportExportModelAdmin):
pass
admin.site.register(Keyword, KeywordAdmin)
admin.site.register(Category, CategoryAdmin)
admin.site.register(Document, DocumentAdmin)
admin.site.register(Context, ContextAdmin)
admin.site.register(Review, ReviewAdmin)<commit_msg>Add list_displays for Admin views<commit_after>from django.contrib import admin
from import_export import resources
from import_export.admin import ImportExportModelAdmin
from mendel.models import Keyword, Category, Document, Context, Review
class KeywordAdmin(ImportExportModelAdmin):
list_display = ('id', 'name')
pass
class CategoryAdmin(ImportExportModelAdmin):
list_display = ('id', 'name')
pass
class DocumentAdmin(ImportExportModelAdmin):
list_display = ('id', 'title', 'description')
pass
class ContextAdmin(ImportExportModelAdmin):
list_display = ('keyword', 'text', 'document')
pass
class ReviewAdmin(ImportExportModelAdmin):
list_display = ('keyword', 'category', 'user', 'status')
pass
admin.site.register(Keyword, KeywordAdmin)
admin.site.register(Category, CategoryAdmin)
admin.site.register(Document, DocumentAdmin)
admin.site.register(Context, ContextAdmin)
admin.site.register(Review, ReviewAdmin)
|
d879c6338449cd0c2f3c9a84162b3de688a55105
|
webdiff/gitwebdiff.py
|
webdiff/gitwebdiff.py
|
#!/usr/bin/env python
'''This lets you run "git webdiff" instead of "git difftool".'''
import os
import subprocess
import sys
def any_nonflag_args(args):
"""Do any args not start with '-'? If so, this isn't a HEAD diff."""
return len([x for x in args if not x.startswith('-')]) > 0
def run():
if not any_nonflag_args(sys.argv[1:]):
# This tells webdiff that it was invoked as a simple "git webdiff", not
# "git webdiff <sha>". This allows special treatment (e.g. for
# staging diffhunks).
os.environ['WEBDIFF_FROM_HEAD'] = 'yes'
sys.exit(subprocess.call(
'git difftool -d -x webdiff'.split(' ') + sys.argv[1:]))
if __name__ == '__main__':
run()
|
#!/usr/bin/env python
'''This lets you run "git webdiff" instead of "git difftool".'''
import os
import subprocess
import sys
def any_nonflag_args(args):
"""Do any args not start with '-'? If so, this isn't a HEAD diff."""
return len([x for x in args if not x.startswith('-')]) > 0
def run():
if not any_nonflag_args(sys.argv[1:]):
# This tells webdiff that it was invoked as a simple "git webdiff", not
# "git webdiff <sha>". This allows special treatment (e.g. for
# staging diffhunks).
os.environ['WEBDIFF_FROM_HEAD'] = 'yes'
try:
subprocess.call('git difftool -d -x webdiff'.split(' ') + sys.argv[1:])
except KeyboardInterrupt:
# Don't raise an exception to the user when sigint is received
pass
if __name__ == '__main__':
run()
|
Exit cleanly from 'git webdiff'
|
Exit cleanly from 'git webdiff'
- Don't allow a KeyboardInterrupt/sigint exception propagate up
to the user when exiting webdiff with Ctrl-C
|
Python
|
apache-2.0
|
daytonb/webdiff,danvk/webdiff,daytonb/webdiff,daytonb/webdiff,danvk/webdiff,danvk/webdiff,danvk/webdiff,daytonb/webdiff,danvk/webdiff
|
#!/usr/bin/env python
'''This lets you run "git webdiff" instead of "git difftool".'''
import os
import subprocess
import sys
def any_nonflag_args(args):
"""Do any args not start with '-'? If so, this isn't a HEAD diff."""
return len([x for x in args if not x.startswith('-')]) > 0
def run():
if not any_nonflag_args(sys.argv[1:]):
# This tells webdiff that it was invoked as a simple "git webdiff", not
# "git webdiff <sha>". This allows special treatment (e.g. for
# staging diffhunks).
os.environ['WEBDIFF_FROM_HEAD'] = 'yes'
sys.exit(subprocess.call(
'git difftool -d -x webdiff'.split(' ') + sys.argv[1:]))
if __name__ == '__main__':
run()
Exit cleanly from 'git webdiff'
- Don't allow a KeyboardInterrupt/sigint exception propagate up
to the user when exiting webdiff with Ctrl-C
|
#!/usr/bin/env python
'''This lets you run "git webdiff" instead of "git difftool".'''
import os
import subprocess
import sys
def any_nonflag_args(args):
"""Do any args not start with '-'? If so, this isn't a HEAD diff."""
return len([x for x in args if not x.startswith('-')]) > 0
def run():
if not any_nonflag_args(sys.argv[1:]):
# This tells webdiff that it was invoked as a simple "git webdiff", not
# "git webdiff <sha>". This allows special treatment (e.g. for
# staging diffhunks).
os.environ['WEBDIFF_FROM_HEAD'] = 'yes'
try:
subprocess.call('git difftool -d -x webdiff'.split(' ') + sys.argv[1:])
except KeyboardInterrupt:
# Don't raise an exception to the user when sigint is received
pass
if __name__ == '__main__':
run()
|
<commit_before>#!/usr/bin/env python
'''This lets you run "git webdiff" instead of "git difftool".'''
import os
import subprocess
import sys
def any_nonflag_args(args):
"""Do any args not start with '-'? If so, this isn't a HEAD diff."""
return len([x for x in args if not x.startswith('-')]) > 0
def run():
if not any_nonflag_args(sys.argv[1:]):
# This tells webdiff that it was invoked as a simple "git webdiff", not
# "git webdiff <sha>". This allows special treatment (e.g. for
# staging diffhunks).
os.environ['WEBDIFF_FROM_HEAD'] = 'yes'
sys.exit(subprocess.call(
'git difftool -d -x webdiff'.split(' ') + sys.argv[1:]))
if __name__ == '__main__':
run()
<commit_msg>Exit cleanly from 'git webdiff'
- Don't allow a KeyboardInterrupt/sigint exception propagate up
to the user when exiting webdiff with Ctrl-C<commit_after>
|
#!/usr/bin/env python
'''This lets you run "git webdiff" instead of "git difftool".'''
import os
import subprocess
import sys
def any_nonflag_args(args):
"""Do any args not start with '-'? If so, this isn't a HEAD diff."""
return len([x for x in args if not x.startswith('-')]) > 0
def run():
if not any_nonflag_args(sys.argv[1:]):
# This tells webdiff that it was invoked as a simple "git webdiff", not
# "git webdiff <sha>". This allows special treatment (e.g. for
# staging diffhunks).
os.environ['WEBDIFF_FROM_HEAD'] = 'yes'
try:
subprocess.call('git difftool -d -x webdiff'.split(' ') + sys.argv[1:])
except KeyboardInterrupt:
# Don't raise an exception to the user when sigint is received
pass
if __name__ == '__main__':
run()
|
#!/usr/bin/env python
'''This lets you run "git webdiff" instead of "git difftool".'''
import os
import subprocess
import sys
def any_nonflag_args(args):
"""Do any args not start with '-'? If so, this isn't a HEAD diff."""
return len([x for x in args if not x.startswith('-')]) > 0
def run():
if not any_nonflag_args(sys.argv[1:]):
# This tells webdiff that it was invoked as a simple "git webdiff", not
# "git webdiff <sha>". This allows special treatment (e.g. for
# staging diffhunks).
os.environ['WEBDIFF_FROM_HEAD'] = 'yes'
sys.exit(subprocess.call(
'git difftool -d -x webdiff'.split(' ') + sys.argv[1:]))
if __name__ == '__main__':
run()
Exit cleanly from 'git webdiff'
- Don't allow a KeyboardInterrupt/sigint exception propagate up
to the user when exiting webdiff with Ctrl-C#!/usr/bin/env python
'''This lets you run "git webdiff" instead of "git difftool".'''
import os
import subprocess
import sys
def any_nonflag_args(args):
"""Do any args not start with '-'? If so, this isn't a HEAD diff."""
return len([x for x in args if not x.startswith('-')]) > 0
def run():
if not any_nonflag_args(sys.argv[1:]):
# This tells webdiff that it was invoked as a simple "git webdiff", not
# "git webdiff <sha>". This allows special treatment (e.g. for
# staging diffhunks).
os.environ['WEBDIFF_FROM_HEAD'] = 'yes'
try:
subprocess.call('git difftool -d -x webdiff'.split(' ') + sys.argv[1:])
except KeyboardInterrupt:
# Don't raise an exception to the user when sigint is received
pass
if __name__ == '__main__':
run()
|
<commit_before>#!/usr/bin/env python
'''This lets you run "git webdiff" instead of "git difftool".'''
import os
import subprocess
import sys
def any_nonflag_args(args):
"""Do any args not start with '-'? If so, this isn't a HEAD diff."""
return len([x for x in args if not x.startswith('-')]) > 0
def run():
if not any_nonflag_args(sys.argv[1:]):
# This tells webdiff that it was invoked as a simple "git webdiff", not
# "git webdiff <sha>". This allows special treatment (e.g. for
# staging diffhunks).
os.environ['WEBDIFF_FROM_HEAD'] = 'yes'
sys.exit(subprocess.call(
'git difftool -d -x webdiff'.split(' ') + sys.argv[1:]))
if __name__ == '__main__':
run()
<commit_msg>Exit cleanly from 'git webdiff'
- Don't allow a KeyboardInterrupt/sigint exception propagate up
to the user when exiting webdiff with Ctrl-C<commit_after>#!/usr/bin/env python
'''This lets you run "git webdiff" instead of "git difftool".'''
import os
import subprocess
import sys
def any_nonflag_args(args):
"""Do any args not start with '-'? If so, this isn't a HEAD diff."""
return len([x for x in args if not x.startswith('-')]) > 0
def run():
if not any_nonflag_args(sys.argv[1:]):
# This tells webdiff that it was invoked as a simple "git webdiff", not
# "git webdiff <sha>". This allows special treatment (e.g. for
# staging diffhunks).
os.environ['WEBDIFF_FROM_HEAD'] = 'yes'
try:
subprocess.call('git difftool -d -x webdiff'.split(' ') + sys.argv[1:])
except KeyboardInterrupt:
# Don't raise an exception to the user when sigint is received
pass
if __name__ == '__main__':
run()
|
a06f586ba95148643561122f051087db7b63fecb
|
registries/views.py
|
registries/views.py
|
from django.shortcuts import render
from django.conf import settings
from django.http import HttpResponse
from rest_framework.generics import ListAPIView
from registries.models import Organization
from registries.serializers import DrillerListSerializer
class APIDrillerListView(ListAPIView):
queryset = Organization.objects.all()
serializer_class = DrillerListSerializer
# Create your views here.
def index(request):
return HttpResponse("TEST: Driller Register app home index.")
|
from django.shortcuts import render
from django.conf import settings
from django.http import HttpResponse
from rest_framework.generics import ListAPIView
from registries.models import Organization
from registries.serializers import DrillerListSerializer
class APIDrillerListView(ListAPIView):
queryset = Organization.objects.all().select_related('province_state')
serializer_class = DrillerListSerializer
# Create your views here.
def index(request):
return HttpResponse("TEST: Driller Register app home index.")
|
Add prefetch to reduce queries on province_state
|
Add prefetch to reduce queries on province_state
|
Python
|
apache-2.0
|
rstens/gwells,rstens/gwells,rstens/gwells,bcgov/gwells,bcgov/gwells,rstens/gwells,bcgov/gwells,bcgov/gwells
|
from django.shortcuts import render
from django.conf import settings
from django.http import HttpResponse
from rest_framework.generics import ListAPIView
from registries.models import Organization
from registries.serializers import DrillerListSerializer
class APIDrillerListView(ListAPIView):
queryset = Organization.objects.all()
serializer_class = DrillerListSerializer
# Create your views here.
def index(request):
return HttpResponse("TEST: Driller Register app home index.")Add prefetch to reduce queries on province_state
|
from django.shortcuts import render
from django.conf import settings
from django.http import HttpResponse
from rest_framework.generics import ListAPIView
from registries.models import Organization
from registries.serializers import DrillerListSerializer
class APIDrillerListView(ListAPIView):
queryset = Organization.objects.all().select_related('province_state')
serializer_class = DrillerListSerializer
# Create your views here.
def index(request):
return HttpResponse("TEST: Driller Register app home index.")
|
<commit_before>from django.shortcuts import render
from django.conf import settings
from django.http import HttpResponse
from rest_framework.generics import ListAPIView
from registries.models import Organization
from registries.serializers import DrillerListSerializer
class APIDrillerListView(ListAPIView):
queryset = Organization.objects.all()
serializer_class = DrillerListSerializer
# Create your views here.
def index(request):
return HttpResponse("TEST: Driller Register app home index.")<commit_msg>Add prefetch to reduce queries on province_state<commit_after>
|
from django.shortcuts import render
from django.conf import settings
from django.http import HttpResponse
from rest_framework.generics import ListAPIView
from registries.models import Organization
from registries.serializers import DrillerListSerializer
class APIDrillerListView(ListAPIView):
queryset = Organization.objects.all().select_related('province_state')
serializer_class = DrillerListSerializer
# Create your views here.
def index(request):
return HttpResponse("TEST: Driller Register app home index.")
|
from django.shortcuts import render
from django.conf import settings
from django.http import HttpResponse
from rest_framework.generics import ListAPIView
from registries.models import Organization
from registries.serializers import DrillerListSerializer
class APIDrillerListView(ListAPIView):
queryset = Organization.objects.all()
serializer_class = DrillerListSerializer
# Create your views here.
def index(request):
return HttpResponse("TEST: Driller Register app home index.")Add prefetch to reduce queries on province_statefrom django.shortcuts import render
from django.conf import settings
from django.http import HttpResponse
from rest_framework.generics import ListAPIView
from registries.models import Organization
from registries.serializers import DrillerListSerializer
class APIDrillerListView(ListAPIView):
queryset = Organization.objects.all().select_related('province_state')
serializer_class = DrillerListSerializer
# Create your views here.
def index(request):
return HttpResponse("TEST: Driller Register app home index.")
|
<commit_before>from django.shortcuts import render
from django.conf import settings
from django.http import HttpResponse
from rest_framework.generics import ListAPIView
from registries.models import Organization
from registries.serializers import DrillerListSerializer
class APIDrillerListView(ListAPIView):
queryset = Organization.objects.all()
serializer_class = DrillerListSerializer
# Create your views here.
def index(request):
return HttpResponse("TEST: Driller Register app home index.")<commit_msg>Add prefetch to reduce queries on province_state<commit_after>from django.shortcuts import render
from django.conf import settings
from django.http import HttpResponse
from rest_framework.generics import ListAPIView
from registries.models import Organization
from registries.serializers import DrillerListSerializer
class APIDrillerListView(ListAPIView):
queryset = Organization.objects.all().select_related('province_state')
serializer_class = DrillerListSerializer
# Create your views here.
def index(request):
return HttpResponse("TEST: Driller Register app home index.")
|
67fb6076b98a25f22a343f0c6ec62193ed86125a
|
bmi_ilamb/bmi_ilamb.py
|
bmi_ilamb/bmi_ilamb.py
|
#! /usr/bin/env python
import sys
import subprocess
from basic_modeling_interface import Bmi
class BmiIlamb(Bmi):
_command = 'ilamb-run'
_args = None
_env = None
def __init__(self):
self._time = self.get_start_time()
@property
def args(self):
return [self._command] + (self._args or [])
def get_component_name(self):
return 'ILAMB'
def initialize(self, filename):
self._args = [filename or 'ilamb.cfg']
def update(self):
subprocess.check_call(self.args, shell=False, env=self._env)
self._time = self.get_end_time()
def update_until(self, time):
self.update(time)
def finalize(self):
pass
def get_input_var_names(self):
return ()
def get_output_var_names(self):
return ()
def get_start_time(self):
return 0.0
def get_end_time(self):
return 1.0
def get_current_time(self):
return self._time
def get_time_step(self):
return 1.0
def get_time_units(self):
return 's'
|
"""Basic Model Interface (BMI) for the ILAMB benchmarking system."""
import os
import subprocess
from basic_modeling_interface import Bmi
from .config import Configuration
class BmiIlamb(Bmi):
_component_name = 'ILAMB'
_command = 'ilamb-run'
_args = None
def __init__(self):
self._time = self.get_start_time()
self.config = Configuration()
@property
def args(self):
return [self._command] + (self._args or [])
def get_component_name(self):
return self._component_name
def initialize(self, filename):
self.config.load(filename)
os.environ['ILAMB_ROOT'] = self.config.get_ilamb_root()
os.environ['MPLBACKEND'] = 'Agg'
self._args = self.config.get_arguments()
def update(self):
with open('stdout', 'w') as fp:
subprocess.check_call(self.args, stdout=fp)
self._time = self.get_end_time()
def update_until(self, time):
self.update()
def finalize(self):
pass
def get_input_var_names(self):
return ()
def get_output_var_names(self):
return ()
def get_start_time(self):
return 0.0
def get_end_time(self):
return 1.0
def get_current_time(self):
return self._time
def get_time_step(self):
return 1.0
def get_time_units(self):
return 's'
|
Update ILAMB BMI to use Configuration
|
Update ILAMB BMI to use Configuration
I also set ILAMB_ROOT and MPLBACKEND at `initialize`. Not sure if
there's a better location.
|
Python
|
mit
|
permamodel/bmi-ilamb
|
#! /usr/bin/env python
import sys
import subprocess
from basic_modeling_interface import Bmi
class BmiIlamb(Bmi):
_command = 'ilamb-run'
_args = None
_env = None
def __init__(self):
self._time = self.get_start_time()
@property
def args(self):
return [self._command] + (self._args or [])
def get_component_name(self):
return 'ILAMB'
def initialize(self, filename):
self._args = [filename or 'ilamb.cfg']
def update(self):
subprocess.check_call(self.args, shell=False, env=self._env)
self._time = self.get_end_time()
def update_until(self, time):
self.update(time)
def finalize(self):
pass
def get_input_var_names(self):
return ()
def get_output_var_names(self):
return ()
def get_start_time(self):
return 0.0
def get_end_time(self):
return 1.0
def get_current_time(self):
return self._time
def get_time_step(self):
return 1.0
def get_time_units(self):
return 's'
Update ILAMB BMI to use Configuration
I also set ILAMB_ROOT and MPLBACKEND at `initialize`. Not sure if
there's a better location.
|
"""Basic Model Interface (BMI) for the ILAMB benchmarking system."""
import os
import subprocess
from basic_modeling_interface import Bmi
from .config import Configuration
class BmiIlamb(Bmi):
_component_name = 'ILAMB'
_command = 'ilamb-run'
_args = None
def __init__(self):
self._time = self.get_start_time()
self.config = Configuration()
@property
def args(self):
return [self._command] + (self._args or [])
def get_component_name(self):
return self._component_name
def initialize(self, filename):
self.config.load(filename)
os.environ['ILAMB_ROOT'] = self.config.get_ilamb_root()
os.environ['MPLBACKEND'] = 'Agg'
self._args = self.config.get_arguments()
def update(self):
with open('stdout', 'w') as fp:
subprocess.check_call(self.args, stdout=fp)
self._time = self.get_end_time()
def update_until(self, time):
self.update()
def finalize(self):
pass
def get_input_var_names(self):
return ()
def get_output_var_names(self):
return ()
def get_start_time(self):
return 0.0
def get_end_time(self):
return 1.0
def get_current_time(self):
return self._time
def get_time_step(self):
return 1.0
def get_time_units(self):
return 's'
|
<commit_before>#! /usr/bin/env python
import sys
import subprocess
from basic_modeling_interface import Bmi
class BmiIlamb(Bmi):
_command = 'ilamb-run'
_args = None
_env = None
def __init__(self):
self._time = self.get_start_time()
@property
def args(self):
return [self._command] + (self._args or [])
def get_component_name(self):
return 'ILAMB'
def initialize(self, filename):
self._args = [filename or 'ilamb.cfg']
def update(self):
subprocess.check_call(self.args, shell=False, env=self._env)
self._time = self.get_end_time()
def update_until(self, time):
self.update(time)
def finalize(self):
pass
def get_input_var_names(self):
return ()
def get_output_var_names(self):
return ()
def get_start_time(self):
return 0.0
def get_end_time(self):
return 1.0
def get_current_time(self):
return self._time
def get_time_step(self):
return 1.0
def get_time_units(self):
return 's'
<commit_msg>Update ILAMB BMI to use Configuration
I also set ILAMB_ROOT and MPLBACKEND at `initialize`. Not sure if
there's a better location.<commit_after>
|
"""Basic Model Interface (BMI) for the ILAMB benchmarking system."""
import os
import subprocess
from basic_modeling_interface import Bmi
from .config import Configuration
class BmiIlamb(Bmi):
_component_name = 'ILAMB'
_command = 'ilamb-run'
_args = None
def __init__(self):
self._time = self.get_start_time()
self.config = Configuration()
@property
def args(self):
return [self._command] + (self._args or [])
def get_component_name(self):
return self._component_name
def initialize(self, filename):
self.config.load(filename)
os.environ['ILAMB_ROOT'] = self.config.get_ilamb_root()
os.environ['MPLBACKEND'] = 'Agg'
self._args = self.config.get_arguments()
def update(self):
with open('stdout', 'w') as fp:
subprocess.check_call(self.args, stdout=fp)
self._time = self.get_end_time()
def update_until(self, time):
self.update()
def finalize(self):
pass
def get_input_var_names(self):
return ()
def get_output_var_names(self):
return ()
def get_start_time(self):
return 0.0
def get_end_time(self):
return 1.0
def get_current_time(self):
return self._time
def get_time_step(self):
return 1.0
def get_time_units(self):
return 's'
|
#! /usr/bin/env python
import sys
import subprocess
from basic_modeling_interface import Bmi
class BmiIlamb(Bmi):
_command = 'ilamb-run'
_args = None
_env = None
def __init__(self):
self._time = self.get_start_time()
@property
def args(self):
return [self._command] + (self._args or [])
def get_component_name(self):
return 'ILAMB'
def initialize(self, filename):
self._args = [filename or 'ilamb.cfg']
def update(self):
subprocess.check_call(self.args, shell=False, env=self._env)
self._time = self.get_end_time()
def update_until(self, time):
self.update(time)
def finalize(self):
pass
def get_input_var_names(self):
return ()
def get_output_var_names(self):
return ()
def get_start_time(self):
return 0.0
def get_end_time(self):
return 1.0
def get_current_time(self):
return self._time
def get_time_step(self):
return 1.0
def get_time_units(self):
return 's'
Update ILAMB BMI to use Configuration
I also set ILAMB_ROOT and MPLBACKEND at `initialize`. Not sure if
there's a better location."""Basic Model Interface (BMI) for the ILAMB benchmarking system."""
import os
import subprocess
from basic_modeling_interface import Bmi
from .config import Configuration
class BmiIlamb(Bmi):
_component_name = 'ILAMB'
_command = 'ilamb-run'
_args = None
def __init__(self):
self._time = self.get_start_time()
self.config = Configuration()
@property
def args(self):
return [self._command] + (self._args or [])
def get_component_name(self):
return self._component_name
def initialize(self, filename):
self.config.load(filename)
os.environ['ILAMB_ROOT'] = self.config.get_ilamb_root()
os.environ['MPLBACKEND'] = 'Agg'
self._args = self.config.get_arguments()
def update(self):
with open('stdout', 'w') as fp:
subprocess.check_call(self.args, stdout=fp)
self._time = self.get_end_time()
def update_until(self, time):
self.update()
def finalize(self):
pass
def get_input_var_names(self):
return ()
def get_output_var_names(self):
return ()
def get_start_time(self):
return 0.0
def get_end_time(self):
return 1.0
def get_current_time(self):
return self._time
def get_time_step(self):
return 1.0
def get_time_units(self):
return 's'
|
<commit_before>#! /usr/bin/env python
import sys
import subprocess
from basic_modeling_interface import Bmi
class BmiIlamb(Bmi):
_command = 'ilamb-run'
_args = None
_env = None
def __init__(self):
self._time = self.get_start_time()
@property
def args(self):
return [self._command] + (self._args or [])
def get_component_name(self):
return 'ILAMB'
def initialize(self, filename):
self._args = [filename or 'ilamb.cfg']
def update(self):
subprocess.check_call(self.args, shell=False, env=self._env)
self._time = self.get_end_time()
def update_until(self, time):
self.update(time)
def finalize(self):
pass
def get_input_var_names(self):
return ()
def get_output_var_names(self):
return ()
def get_start_time(self):
return 0.0
def get_end_time(self):
return 1.0
def get_current_time(self):
return self._time
def get_time_step(self):
return 1.0
def get_time_units(self):
return 's'
<commit_msg>Update ILAMB BMI to use Configuration
I also set ILAMB_ROOT and MPLBACKEND at `initialize`. Not sure if
there's a better location.<commit_after>"""Basic Model Interface (BMI) for the ILAMB benchmarking system."""
import os
import subprocess
from basic_modeling_interface import Bmi
from .config import Configuration
class BmiIlamb(Bmi):
_component_name = 'ILAMB'
_command = 'ilamb-run'
_args = None
def __init__(self):
self._time = self.get_start_time()
self.config = Configuration()
@property
def args(self):
return [self._command] + (self._args or [])
def get_component_name(self):
return self._component_name
def initialize(self, filename):
self.config.load(filename)
os.environ['ILAMB_ROOT'] = self.config.get_ilamb_root()
os.environ['MPLBACKEND'] = 'Agg'
self._args = self.config.get_arguments()
def update(self):
with open('stdout', 'w') as fp:
subprocess.check_call(self.args, stdout=fp)
self._time = self.get_end_time()
def update_until(self, time):
self.update()
def finalize(self):
pass
def get_input_var_names(self):
return ()
def get_output_var_names(self):
return ()
def get_start_time(self):
return 0.0
def get_end_time(self):
return 1.0
def get_current_time(self):
return self._time
def get_time_step(self):
return 1.0
def get_time_units(self):
return 's'
|
b8df411dc6cbbad981c98d918627143ffd1c9ef3
|
kmeldb/AlbumIndexEntry.py
|
kmeldb/AlbumIndexEntry.py
|
from .BaseIndexEntry import BaseIndexEntry
class AlbumIndexEntry(BaseIndexEntry):
def __init__(self, name, titles, number):
super(AlbumIndexEntry, self).__init__(name, titles, number)
self._title_numbers = []
self._discs_and_tracks = {}
for title in self._titles:
# Set the album number on each of the titles
title.album_number = self._number
# Append the title index to the list
self._title_numbers.append(title.index)
# Store titles according to disc and track number
if title.discnumber not in self._discs_and_tracks:
self._discs_and_tracks[title.discnumber] = {}
if title.tracknumber in self._discs_and_tracks[title.discnumber]:
print ("Duplicate track number", title.tracknumber, title.title)
self._discs_and_tracks[title.discnumber][title.tracknumber] = title
self._freeze()
# Getters
@property
def title_numbers(self):
return self._title_numbers
@property
def tracks(self):
'''Return titles in album disc and track order'''
return [self._discs_and_tracks[d][t] for d in sorted(self._discs_and_tracks) for t in sorted(self._discs_and_tracks[d])]
|
from .BaseIndexEntry import BaseIndexEntry
class AlbumIndexEntry(BaseIndexEntry):
def __init__(self, name, titles, number):
super(AlbumIndexEntry, self).__init__(name, titles, number)
self._discs_and_tracks = {}
for title in self._titles:
# Set the album number on each of the titles
title.album_number = self._number
# Store titles according to disc and track number
# TODO: Cope with more than two discs
discnumber = title.discnumber
if discnumber not in self._discs_and_tracks:
self._discs_and_tracks[discnumber] = {}
if title.tracknumber in self._discs_and_tracks[discnumber]:
print ("Duplicate track numbers:")
print ("\tFirst", title.tracknumber, self._discs_and_tracks[discnumber][title.tracknumber].title)
print ("\tSecond", title.tracknumber, title.title)
discnumber = title.discnumber + 1
if discnumber not in self._discs_and_tracks:
self._discs_and_tracks[discnumber] = {}
print ("\tSetting disc number to: {} - you may want to edit the file and set disc number yourself.".format(discnumber))
self._discs_and_tracks[discnumber][title.tracknumber] = title
self._freeze()
# Getters
@property
def title_numbers(self):
return [self._discs_and_tracks[d][t].index for d in sorted(self._discs_and_tracks) for t in sorted(self._discs_and_tracks[d])]
@property
def tracks(self):
'''Return titles in album disc and track order'''
return [self._discs_and_tracks[d][t] for d in sorted(self._discs_and_tracks) for t in sorted(self._discs_and_tracks[d])]
|
Return title numbers in disc and track order, increment disc number if duplicated track number
|
Return title numbers in disc and track order, increment disc number if duplicated track number
|
Python
|
apache-2.0
|
chrrrisw/kmel_db,chrrrisw/kmel_db
|
from .BaseIndexEntry import BaseIndexEntry
class AlbumIndexEntry(BaseIndexEntry):
def __init__(self, name, titles, number):
super(AlbumIndexEntry, self).__init__(name, titles, number)
self._title_numbers = []
self._discs_and_tracks = {}
for title in self._titles:
# Set the album number on each of the titles
title.album_number = self._number
# Append the title index to the list
self._title_numbers.append(title.index)
# Store titles according to disc and track number
if title.discnumber not in self._discs_and_tracks:
self._discs_and_tracks[title.discnumber] = {}
if title.tracknumber in self._discs_and_tracks[title.discnumber]:
print ("Duplicate track number", title.tracknumber, title.title)
self._discs_and_tracks[title.discnumber][title.tracknumber] = title
self._freeze()
# Getters
@property
def title_numbers(self):
return self._title_numbers
@property
def tracks(self):
'''Return titles in album disc and track order'''
return [self._discs_and_tracks[d][t] for d in sorted(self._discs_and_tracks) for t in sorted(self._discs_and_tracks[d])]
Return title numbers in disc and track order, increment disc number if duplicated track number
|
from .BaseIndexEntry import BaseIndexEntry
class AlbumIndexEntry(BaseIndexEntry):
def __init__(self, name, titles, number):
super(AlbumIndexEntry, self).__init__(name, titles, number)
self._discs_and_tracks = {}
for title in self._titles:
# Set the album number on each of the titles
title.album_number = self._number
# Store titles according to disc and track number
# TODO: Cope with more than two discs
discnumber = title.discnumber
if discnumber not in self._discs_and_tracks:
self._discs_and_tracks[discnumber] = {}
if title.tracknumber in self._discs_and_tracks[discnumber]:
print ("Duplicate track numbers:")
print ("\tFirst", title.tracknumber, self._discs_and_tracks[discnumber][title.tracknumber].title)
print ("\tSecond", title.tracknumber, title.title)
discnumber = title.discnumber + 1
if discnumber not in self._discs_and_tracks:
self._discs_and_tracks[discnumber] = {}
print ("\tSetting disc number to: {} - you may want to edit the file and set disc number yourself.".format(discnumber))
self._discs_and_tracks[discnumber][title.tracknumber] = title
self._freeze()
# Getters
@property
def title_numbers(self):
return [self._discs_and_tracks[d][t].index for d in sorted(self._discs_and_tracks) for t in sorted(self._discs_and_tracks[d])]
@property
def tracks(self):
'''Return titles in album disc and track order'''
return [self._discs_and_tracks[d][t] for d in sorted(self._discs_and_tracks) for t in sorted(self._discs_and_tracks[d])]
|
<commit_before>from .BaseIndexEntry import BaseIndexEntry
class AlbumIndexEntry(BaseIndexEntry):
def __init__(self, name, titles, number):
super(AlbumIndexEntry, self).__init__(name, titles, number)
self._title_numbers = []
self._discs_and_tracks = {}
for title in self._titles:
# Set the album number on each of the titles
title.album_number = self._number
# Append the title index to the list
self._title_numbers.append(title.index)
# Store titles according to disc and track number
if title.discnumber not in self._discs_and_tracks:
self._discs_and_tracks[title.discnumber] = {}
if title.tracknumber in self._discs_and_tracks[title.discnumber]:
print ("Duplicate track number", title.tracknumber, title.title)
self._discs_and_tracks[title.discnumber][title.tracknumber] = title
self._freeze()
# Getters
@property
def title_numbers(self):
return self._title_numbers
@property
def tracks(self):
'''Return titles in album disc and track order'''
return [self._discs_and_tracks[d][t] for d in sorted(self._discs_and_tracks) for t in sorted(self._discs_and_tracks[d])]
<commit_msg>Return title numbers in disc and track order, increment disc number if duplicated track number<commit_after>
|
from .BaseIndexEntry import BaseIndexEntry
class AlbumIndexEntry(BaseIndexEntry):
def __init__(self, name, titles, number):
super(AlbumIndexEntry, self).__init__(name, titles, number)
self._discs_and_tracks = {}
for title in self._titles:
# Set the album number on each of the titles
title.album_number = self._number
# Store titles according to disc and track number
# TODO: Cope with more than two discs
discnumber = title.discnumber
if discnumber not in self._discs_and_tracks:
self._discs_and_tracks[discnumber] = {}
if title.tracknumber in self._discs_and_tracks[discnumber]:
print ("Duplicate track numbers:")
print ("\tFirst", title.tracknumber, self._discs_and_tracks[discnumber][title.tracknumber].title)
print ("\tSecond", title.tracknumber, title.title)
discnumber = title.discnumber + 1
if discnumber not in self._discs_and_tracks:
self._discs_and_tracks[discnumber] = {}
print ("\tSetting disc number to: {} - you may want to edit the file and set disc number yourself.".format(discnumber))
self._discs_and_tracks[discnumber][title.tracknumber] = title
self._freeze()
# Getters
@property
def title_numbers(self):
return [self._discs_and_tracks[d][t].index for d in sorted(self._discs_and_tracks) for t in sorted(self._discs_and_tracks[d])]
@property
def tracks(self):
'''Return titles in album disc and track order'''
return [self._discs_and_tracks[d][t] for d in sorted(self._discs_and_tracks) for t in sorted(self._discs_and_tracks[d])]
|
from .BaseIndexEntry import BaseIndexEntry
class AlbumIndexEntry(BaseIndexEntry):
def __init__(self, name, titles, number):
super(AlbumIndexEntry, self).__init__(name, titles, number)
self._title_numbers = []
self._discs_and_tracks = {}
for title in self._titles:
# Set the album number on each of the titles
title.album_number = self._number
# Append the title index to the list
self._title_numbers.append(title.index)
# Store titles according to disc and track number
if title.discnumber not in self._discs_and_tracks:
self._discs_and_tracks[title.discnumber] = {}
if title.tracknumber in self._discs_and_tracks[title.discnumber]:
print ("Duplicate track number", title.tracknumber, title.title)
self._discs_and_tracks[title.discnumber][title.tracknumber] = title
self._freeze()
# Getters
@property
def title_numbers(self):
return self._title_numbers
@property
def tracks(self):
'''Return titles in album disc and track order'''
return [self._discs_and_tracks[d][t] for d in sorted(self._discs_and_tracks) for t in sorted(self._discs_and_tracks[d])]
Return title numbers in disc and track order, increment disc number if duplicated track numberfrom .BaseIndexEntry import BaseIndexEntry
class AlbumIndexEntry(BaseIndexEntry):
def __init__(self, name, titles, number):
super(AlbumIndexEntry, self).__init__(name, titles, number)
self._discs_and_tracks = {}
for title in self._titles:
# Set the album number on each of the titles
title.album_number = self._number
# Store titles according to disc and track number
# TODO: Cope with more than two discs
discnumber = title.discnumber
if discnumber not in self._discs_and_tracks:
self._discs_and_tracks[discnumber] = {}
if title.tracknumber in self._discs_and_tracks[discnumber]:
print ("Duplicate track numbers:")
print ("\tFirst", title.tracknumber, self._discs_and_tracks[discnumber][title.tracknumber].title)
print ("\tSecond", title.tracknumber, title.title)
discnumber = title.discnumber + 1
if discnumber not in self._discs_and_tracks:
self._discs_and_tracks[discnumber] = {}
print ("\tSetting disc number to: {} - you may want to edit the file and set disc number yourself.".format(discnumber))
self._discs_and_tracks[discnumber][title.tracknumber] = title
self._freeze()
# Getters
@property
def title_numbers(self):
return [self._discs_and_tracks[d][t].index for d in sorted(self._discs_and_tracks) for t in sorted(self._discs_and_tracks[d])]
@property
def tracks(self):
'''Return titles in album disc and track order'''
return [self._discs_and_tracks[d][t] for d in sorted(self._discs_and_tracks) for t in sorted(self._discs_and_tracks[d])]
|
<commit_before>from .BaseIndexEntry import BaseIndexEntry
class AlbumIndexEntry(BaseIndexEntry):
def __init__(self, name, titles, number):
super(AlbumIndexEntry, self).__init__(name, titles, number)
self._title_numbers = []
self._discs_and_tracks = {}
for title in self._titles:
# Set the album number on each of the titles
title.album_number = self._number
# Append the title index to the list
self._title_numbers.append(title.index)
# Store titles according to disc and track number
if title.discnumber not in self._discs_and_tracks:
self._discs_and_tracks[title.discnumber] = {}
if title.tracknumber in self._discs_and_tracks[title.discnumber]:
print ("Duplicate track number", title.tracknumber, title.title)
self._discs_and_tracks[title.discnumber][title.tracknumber] = title
self._freeze()
# Getters
@property
def title_numbers(self):
return self._title_numbers
@property
def tracks(self):
'''Return titles in album disc and track order'''
return [self._discs_and_tracks[d][t] for d in sorted(self._discs_and_tracks) for t in sorted(self._discs_and_tracks[d])]
<commit_msg>Return title numbers in disc and track order, increment disc number if duplicated track number<commit_after>from .BaseIndexEntry import BaseIndexEntry
class AlbumIndexEntry(BaseIndexEntry):
def __init__(self, name, titles, number):
super(AlbumIndexEntry, self).__init__(name, titles, number)
self._discs_and_tracks = {}
for title in self._titles:
# Set the album number on each of the titles
title.album_number = self._number
# Store titles according to disc and track number
# TODO: Cope with more than two discs
discnumber = title.discnumber
if discnumber not in self._discs_and_tracks:
self._discs_and_tracks[discnumber] = {}
if title.tracknumber in self._discs_and_tracks[discnumber]:
print ("Duplicate track numbers:")
print ("\tFirst", title.tracknumber, self._discs_and_tracks[discnumber][title.tracknumber].title)
print ("\tSecond", title.tracknumber, title.title)
discnumber = title.discnumber + 1
if discnumber not in self._discs_and_tracks:
self._discs_and_tracks[discnumber] = {}
print ("\tSetting disc number to: {} - you may want to edit the file and set disc number yourself.".format(discnumber))
self._discs_and_tracks[discnumber][title.tracknumber] = title
self._freeze()
# Getters
@property
def title_numbers(self):
return [self._discs_and_tracks[d][t].index for d in sorted(self._discs_and_tracks) for t in sorted(self._discs_and_tracks[d])]
@property
def tracks(self):
'''Return titles in album disc and track order'''
return [self._discs_and_tracks[d][t] for d in sorted(self._discs_and_tracks) for t in sorted(self._discs_and_tracks[d])]
|
a657792c10f59ed94af3039807ef92318b5c23f9
|
src/graphql/pyutils/is_iterable.py
|
src/graphql/pyutils/is_iterable.py
|
from array import array
from typing import Any, ByteString, Collection, Iterable, Mapping, Text, ValuesView
__all__ = ["is_collection", "is_iterable"]
collection_types: Any = [Collection]
if not isinstance({}.values(), Collection): # Python < 3.7.2
collection_types.append(ValuesView)
if not isinstance(array, Collection): # PyPy issue 3820
collection_types.append(array)
collection_types = (
collection_types[0] if len(collection_types) == 1 else tuple(collection_types)
)
iterable_types: Any = Iterable
not_iterable_types: Any = (ByteString, Mapping, Text)
def is_collection(value: Any) -> bool:
"""Check if value is a collection, but not a string or a mapping."""
return isinstance(value, collection_types) and not isinstance(
value, not_iterable_types
)
def is_iterable(value: Any) -> bool:
"""Check if value is an iterable, but not a string or a mapping."""
return isinstance(value, iterable_types) and not isinstance(
value, not_iterable_types
)
|
from array import array
from typing import Any, ByteString, Collection, Iterable, Mapping, Text, ValuesView
__all__ = ["is_collection", "is_iterable"]
collection_types: Any = [Collection]
if not isinstance({}.values(), Collection): # Python < 3.7.2
collection_types.append(ValuesView)
if not issubclass(array, Collection): # PyPy <= 7.3.9
collection_types.append(array)
collection_types = (
collection_types[0] if len(collection_types) == 1 else tuple(collection_types)
)
iterable_types: Any = Iterable
not_iterable_types: Any = (ByteString, Mapping, Text)
def is_collection(value: Any) -> bool:
"""Check if value is a collection, but not a string or a mapping."""
return isinstance(value, collection_types) and not isinstance(
value, not_iterable_types
)
def is_iterable(value: Any) -> bool:
"""Check if value is an iterable, but not a string or a mapping."""
return isinstance(value, iterable_types) and not isinstance(
value, not_iterable_types
)
|
Correct a workaround for PyPy
|
Correct a workaround for PyPy
|
Python
|
mit
|
graphql-python/graphql-core
|
from array import array
from typing import Any, ByteString, Collection, Iterable, Mapping, Text, ValuesView
__all__ = ["is_collection", "is_iterable"]
collection_types: Any = [Collection]
if not isinstance({}.values(), Collection): # Python < 3.7.2
collection_types.append(ValuesView)
if not isinstance(array, Collection): # PyPy issue 3820
collection_types.append(array)
collection_types = (
collection_types[0] if len(collection_types) == 1 else tuple(collection_types)
)
iterable_types: Any = Iterable
not_iterable_types: Any = (ByteString, Mapping, Text)
def is_collection(value: Any) -> bool:
"""Check if value is a collection, but not a string or a mapping."""
return isinstance(value, collection_types) and not isinstance(
value, not_iterable_types
)
def is_iterable(value: Any) -> bool:
"""Check if value is an iterable, but not a string or a mapping."""
return isinstance(value, iterable_types) and not isinstance(
value, not_iterable_types
)
Correct a workaround for PyPy
|
from array import array
from typing import Any, ByteString, Collection, Iterable, Mapping, Text, ValuesView
__all__ = ["is_collection", "is_iterable"]
collection_types: Any = [Collection]
if not isinstance({}.values(), Collection): # Python < 3.7.2
collection_types.append(ValuesView)
if not issubclass(array, Collection): # PyPy <= 7.3.9
collection_types.append(array)
collection_types = (
collection_types[0] if len(collection_types) == 1 else tuple(collection_types)
)
iterable_types: Any = Iterable
not_iterable_types: Any = (ByteString, Mapping, Text)
def is_collection(value: Any) -> bool:
"""Check if value is a collection, but not a string or a mapping."""
return isinstance(value, collection_types) and not isinstance(
value, not_iterable_types
)
def is_iterable(value: Any) -> bool:
"""Check if value is an iterable, but not a string or a mapping."""
return isinstance(value, iterable_types) and not isinstance(
value, not_iterable_types
)
|
<commit_before>from array import array
from typing import Any, ByteString, Collection, Iterable, Mapping, Text, ValuesView
__all__ = ["is_collection", "is_iterable"]
collection_types: Any = [Collection]
if not isinstance({}.values(), Collection): # Python < 3.7.2
collection_types.append(ValuesView)
if not isinstance(array, Collection): # PyPy issue 3820
collection_types.append(array)
collection_types = (
collection_types[0] if len(collection_types) == 1 else tuple(collection_types)
)
iterable_types: Any = Iterable
not_iterable_types: Any = (ByteString, Mapping, Text)
def is_collection(value: Any) -> bool:
"""Check if value is a collection, but not a string or a mapping."""
return isinstance(value, collection_types) and not isinstance(
value, not_iterable_types
)
def is_iterable(value: Any) -> bool:
"""Check if value is an iterable, but not a string or a mapping."""
return isinstance(value, iterable_types) and not isinstance(
value, not_iterable_types
)
<commit_msg>Correct a workaround for PyPy<commit_after>
|
from array import array
from typing import Any, ByteString, Collection, Iterable, Mapping, Text, ValuesView
__all__ = ["is_collection", "is_iterable"]
collection_types: Any = [Collection]
if not isinstance({}.values(), Collection): # Python < 3.7.2
collection_types.append(ValuesView)
if not issubclass(array, Collection): # PyPy <= 7.3.9
collection_types.append(array)
collection_types = (
collection_types[0] if len(collection_types) == 1 else tuple(collection_types)
)
iterable_types: Any = Iterable
not_iterable_types: Any = (ByteString, Mapping, Text)
def is_collection(value: Any) -> bool:
"""Check if value is a collection, but not a string or a mapping."""
return isinstance(value, collection_types) and not isinstance(
value, not_iterable_types
)
def is_iterable(value: Any) -> bool:
"""Check if value is an iterable, but not a string or a mapping."""
return isinstance(value, iterable_types) and not isinstance(
value, not_iterable_types
)
|
from array import array
from typing import Any, ByteString, Collection, Iterable, Mapping, Text, ValuesView
__all__ = ["is_collection", "is_iterable"]
collection_types: Any = [Collection]
if not isinstance({}.values(), Collection): # Python < 3.7.2
collection_types.append(ValuesView)
if not isinstance(array, Collection): # PyPy issue 3820
collection_types.append(array)
collection_types = (
collection_types[0] if len(collection_types) == 1 else tuple(collection_types)
)
iterable_types: Any = Iterable
not_iterable_types: Any = (ByteString, Mapping, Text)
def is_collection(value: Any) -> bool:
"""Check if value is a collection, but not a string or a mapping."""
return isinstance(value, collection_types) and not isinstance(
value, not_iterable_types
)
def is_iterable(value: Any) -> bool:
"""Check if value is an iterable, but not a string or a mapping."""
return isinstance(value, iterable_types) and not isinstance(
value, not_iterable_types
)
Correct a workaround for PyPyfrom array import array
from typing import Any, ByteString, Collection, Iterable, Mapping, Text, ValuesView
__all__ = ["is_collection", "is_iterable"]
collection_types: Any = [Collection]
if not isinstance({}.values(), Collection): # Python < 3.7.2
collection_types.append(ValuesView)
if not issubclass(array, Collection): # PyPy <= 7.3.9
collection_types.append(array)
collection_types = (
collection_types[0] if len(collection_types) == 1 else tuple(collection_types)
)
iterable_types: Any = Iterable
not_iterable_types: Any = (ByteString, Mapping, Text)
def is_collection(value: Any) -> bool:
"""Check if value is a collection, but not a string or a mapping."""
return isinstance(value, collection_types) and not isinstance(
value, not_iterable_types
)
def is_iterable(value: Any) -> bool:
"""Check if value is an iterable, but not a string or a mapping."""
return isinstance(value, iterable_types) and not isinstance(
value, not_iterable_types
)
|
<commit_before>from array import array
from typing import Any, ByteString, Collection, Iterable, Mapping, Text, ValuesView
__all__ = ["is_collection", "is_iterable"]
collection_types: Any = [Collection]
if not isinstance({}.values(), Collection): # Python < 3.7.2
collection_types.append(ValuesView)
if not isinstance(array, Collection): # PyPy issue 3820
collection_types.append(array)
collection_types = (
collection_types[0] if len(collection_types) == 1 else tuple(collection_types)
)
iterable_types: Any = Iterable
not_iterable_types: Any = (ByteString, Mapping, Text)
def is_collection(value: Any) -> bool:
"""Check if value is a collection, but not a string or a mapping."""
return isinstance(value, collection_types) and not isinstance(
value, not_iterable_types
)
def is_iterable(value: Any) -> bool:
"""Check if value is an iterable, but not a string or a mapping."""
return isinstance(value, iterable_types) and not isinstance(
value, not_iterable_types
)
<commit_msg>Correct a workaround for PyPy<commit_after>from array import array
from typing import Any, ByteString, Collection, Iterable, Mapping, Text, ValuesView
__all__ = ["is_collection", "is_iterable"]
collection_types: Any = [Collection]
if not isinstance({}.values(), Collection): # Python < 3.7.2
collection_types.append(ValuesView)
if not issubclass(array, Collection): # PyPy <= 7.3.9
collection_types.append(array)
collection_types = (
collection_types[0] if len(collection_types) == 1 else tuple(collection_types)
)
iterable_types: Any = Iterable
not_iterable_types: Any = (ByteString, Mapping, Text)
def is_collection(value: Any) -> bool:
"""Check if value is a collection, but not a string or a mapping."""
return isinstance(value, collection_types) and not isinstance(
value, not_iterable_types
)
def is_iterable(value: Any) -> bool:
"""Check if value is an iterable, but not a string or a mapping."""
return isinstance(value, iterable_types) and not isinstance(
value, not_iterable_types
)
|
3749acbad597974ef2507b2e7e27240937658c0b
|
nilmtk/plots.py
|
nilmtk/plots.py
|
from __future__ import print_function, division
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np
_to_ordinalf_np_vectorized = np.vectorize(mdates._to_ordinalf)
def plot_series(series, ax=None, label=None, date_format='%d/%m/%y %H:%M:%S', **kwargs):
"""Plot function for series which is about 5 times faster than
pd.Series.plot().
Parameters
----------
ax : matplotlib Axes, optional
If not provided then will generate our own axes.
label : str, optional
The label for the plotted line. The
caller is responsible for enabling the legend.
date_format : str, optional, default='%d/%m/%y %H:%M:%S'
"""
if ax is None:
ax = plt.gca()
ax.xaxis.axis_date(tz=series.index.tzinfo)
ax.xaxis.set_major_formatter(mdates.DateFormatter(date_format))
x = _to_ordinalf_np_vectorized(series.index.to_pydatetime())
ax.plot(x, series, label=label, **kwargs)
ax.set_ylabel('watts')
return ax
|
from __future__ import print_function, division
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np
_to_ordinalf_np_vectorized = np.vectorize(mdates._to_ordinalf)
def plot_series(series, ax=None, label=None, date_format='%d/%m/%y %H:%M:%S', **kwargs):
"""Plot function for series which is about 5 times faster than
pd.Series.plot().
Parameters
----------
ax : matplotlib Axes, optional
If not provided then will generate our own axes.
label : str, optional
The label for the plotted line. The
caller is responsible for enabling the legend.
date_format : str, optional, default='%d/%m/%y %H:%M:%S'
"""
if ax is None:
fig, ax = plt.subplots(1)
x = _to_ordinalf_np_vectorized(series.index.to_pydatetime())
ax.plot(x, series, label=label, **kwargs)
ax.xaxis.set_major_formatter(mdates.DateFormatter(date_format,
tz=series.index.tzinfo))
ax.set_ylabel('watts')
fig.autofmt_xdate()
plt.draw()
return ax
|
Fix bug where timezone was not used for xaxis.
|
Fix bug where timezone was not used for xaxis.
|
Python
|
apache-2.0
|
jaduimstra/nilmtk,josemao/nilmtk,pauldeng/nilmtk,AlexRobson/nilmtk,mmottahedi/nilmtk,nilmtk/nilmtk,nilmtk/nilmtk,HarllanAndrye/nilmtk
|
from __future__ import print_function, division
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np
_to_ordinalf_np_vectorized = np.vectorize(mdates._to_ordinalf)
def plot_series(series, ax=None, label=None, date_format='%d/%m/%y %H:%M:%S', **kwargs):
"""Plot function for series which is about 5 times faster than
pd.Series.plot().
Parameters
----------
ax : matplotlib Axes, optional
If not provided then will generate our own axes.
label : str, optional
The label for the plotted line. The
caller is responsible for enabling the legend.
date_format : str, optional, default='%d/%m/%y %H:%M:%S'
"""
if ax is None:
ax = plt.gca()
ax.xaxis.axis_date(tz=series.index.tzinfo)
ax.xaxis.set_major_formatter(mdates.DateFormatter(date_format))
x = _to_ordinalf_np_vectorized(series.index.to_pydatetime())
ax.plot(x, series, label=label, **kwargs)
ax.set_ylabel('watts')
return ax
Fix bug where timezone was not used for xaxis.
|
from __future__ import print_function, division
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np
_to_ordinalf_np_vectorized = np.vectorize(mdates._to_ordinalf)
def plot_series(series, ax=None, label=None, date_format='%d/%m/%y %H:%M:%S', **kwargs):
"""Plot function for series which is about 5 times faster than
pd.Series.plot().
Parameters
----------
ax : matplotlib Axes, optional
If not provided then will generate our own axes.
label : str, optional
The label for the plotted line. The
caller is responsible for enabling the legend.
date_format : str, optional, default='%d/%m/%y %H:%M:%S'
"""
if ax is None:
fig, ax = plt.subplots(1)
x = _to_ordinalf_np_vectorized(series.index.to_pydatetime())
ax.plot(x, series, label=label, **kwargs)
ax.xaxis.set_major_formatter(mdates.DateFormatter(date_format,
tz=series.index.tzinfo))
ax.set_ylabel('watts')
fig.autofmt_xdate()
plt.draw()
return ax
|
<commit_before>from __future__ import print_function, division
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np
_to_ordinalf_np_vectorized = np.vectorize(mdates._to_ordinalf)
def plot_series(series, ax=None, label=None, date_format='%d/%m/%y %H:%M:%S', **kwargs):
"""Plot function for series which is about 5 times faster than
pd.Series.plot().
Parameters
----------
ax : matplotlib Axes, optional
If not provided then will generate our own axes.
label : str, optional
The label for the plotted line. The
caller is responsible for enabling the legend.
date_format : str, optional, default='%d/%m/%y %H:%M:%S'
"""
if ax is None:
ax = plt.gca()
ax.xaxis.axis_date(tz=series.index.tzinfo)
ax.xaxis.set_major_formatter(mdates.DateFormatter(date_format))
x = _to_ordinalf_np_vectorized(series.index.to_pydatetime())
ax.plot(x, series, label=label, **kwargs)
ax.set_ylabel('watts')
return ax
<commit_msg>Fix bug where timezone was not used for xaxis.<commit_after>
|
from __future__ import print_function, division
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np
_to_ordinalf_np_vectorized = np.vectorize(mdates._to_ordinalf)
def plot_series(series, ax=None, label=None, date_format='%d/%m/%y %H:%M:%S', **kwargs):
"""Plot function for series which is about 5 times faster than
pd.Series.plot().
Parameters
----------
ax : matplotlib Axes, optional
If not provided then will generate our own axes.
label : str, optional
The label for the plotted line. The
caller is responsible for enabling the legend.
date_format : str, optional, default='%d/%m/%y %H:%M:%S'
"""
if ax is None:
fig, ax = plt.subplots(1)
x = _to_ordinalf_np_vectorized(series.index.to_pydatetime())
ax.plot(x, series, label=label, **kwargs)
ax.xaxis.set_major_formatter(mdates.DateFormatter(date_format,
tz=series.index.tzinfo))
ax.set_ylabel('watts')
fig.autofmt_xdate()
plt.draw()
return ax
|
from __future__ import print_function, division
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np
_to_ordinalf_np_vectorized = np.vectorize(mdates._to_ordinalf)
def plot_series(series, ax=None, label=None, date_format='%d/%m/%y %H:%M:%S', **kwargs):
"""Plot function for series which is about 5 times faster than
pd.Series.plot().
Parameters
----------
ax : matplotlib Axes, optional
If not provided then will generate our own axes.
label : str, optional
The label for the plotted line. The
caller is responsible for enabling the legend.
date_format : str, optional, default='%d/%m/%y %H:%M:%S'
"""
if ax is None:
ax = plt.gca()
ax.xaxis.axis_date(tz=series.index.tzinfo)
ax.xaxis.set_major_formatter(mdates.DateFormatter(date_format))
x = _to_ordinalf_np_vectorized(series.index.to_pydatetime())
ax.plot(x, series, label=label, **kwargs)
ax.set_ylabel('watts')
return ax
Fix bug where timezone was not used for xaxis.from __future__ import print_function, division
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np
_to_ordinalf_np_vectorized = np.vectorize(mdates._to_ordinalf)
def plot_series(series, ax=None, label=None, date_format='%d/%m/%y %H:%M:%S', **kwargs):
"""Plot function for series which is about 5 times faster than
pd.Series.plot().
Parameters
----------
ax : matplotlib Axes, optional
If not provided then will generate our own axes.
label : str, optional
The label for the plotted line. The
caller is responsible for enabling the legend.
date_format : str, optional, default='%d/%m/%y %H:%M:%S'
"""
if ax is None:
fig, ax = plt.subplots(1)
x = _to_ordinalf_np_vectorized(series.index.to_pydatetime())
ax.plot(x, series, label=label, **kwargs)
ax.xaxis.set_major_formatter(mdates.DateFormatter(date_format,
tz=series.index.tzinfo))
ax.set_ylabel('watts')
fig.autofmt_xdate()
plt.draw()
return ax
|
<commit_before>from __future__ import print_function, division
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np
_to_ordinalf_np_vectorized = np.vectorize(mdates._to_ordinalf)
def plot_series(series, ax=None, label=None, date_format='%d/%m/%y %H:%M:%S', **kwargs):
"""Plot function for series which is about 5 times faster than
pd.Series.plot().
Parameters
----------
ax : matplotlib Axes, optional
If not provided then will generate our own axes.
label : str, optional
The label for the plotted line. The
caller is responsible for enabling the legend.
date_format : str, optional, default='%d/%m/%y %H:%M:%S'
"""
if ax is None:
ax = plt.gca()
ax.xaxis.axis_date(tz=series.index.tzinfo)
ax.xaxis.set_major_formatter(mdates.DateFormatter(date_format))
x = _to_ordinalf_np_vectorized(series.index.to_pydatetime())
ax.plot(x, series, label=label, **kwargs)
ax.set_ylabel('watts')
return ax
<commit_msg>Fix bug where timezone was not used for xaxis.<commit_after>from __future__ import print_function, division
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np
_to_ordinalf_np_vectorized = np.vectorize(mdates._to_ordinalf)
def plot_series(series, ax=None, label=None, date_format='%d/%m/%y %H:%M:%S', **kwargs):
"""Plot function for series which is about 5 times faster than
pd.Series.plot().
Parameters
----------
ax : matplotlib Axes, optional
If not provided then will generate our own axes.
label : str, optional
The label for the plotted line. The
caller is responsible for enabling the legend.
date_format : str, optional, default='%d/%m/%y %H:%M:%S'
"""
if ax is None:
fig, ax = plt.subplots(1)
x = _to_ordinalf_np_vectorized(series.index.to_pydatetime())
ax.plot(x, series, label=label, **kwargs)
ax.xaxis.set_major_formatter(mdates.DateFormatter(date_format,
tz=series.index.tzinfo))
ax.set_ylabel('watts')
fig.autofmt_xdate()
plt.draw()
return ax
|
6d2d9088797aace5698a0e44ac3ed725148dd60b
|
decorators.py
|
decorators.py
|
from functools import update_wrapper
from flask import session, redirect, flash
import auth
def login_required(permission=None):
'''
Login required decorator. Requires user to be logged in. If a permission
is provided, then user must also have the appropriate permissions to
access the page.
'''
def decorator(fn):
def wrapped_function(*args, **kwargs):
# User must be logged in.
if 'username' not in session:
flash("This page requires you to be logged in.")
# Store page to be loaded after login in session.
session['next'] = request.url
return redirect(url_for('login'))
# Check permissions.
if permission != None:
if not auth.check_permission(permission):
flash("You do have have permission to access this page.")
session['next'] = request.url
return redirect(url_for('login'))
return fn(*args, **kwargs)
return update_wrapper(wrapped_function, fn)
return decorator
|
from functools import update_wrapper
from flask import session, redirect, flash
import auth
def login_required(permission=None):
'''
Login required decorator. Requires user to be logged in. If a permission
is provided, then user must also have the appropriate permissions to
access the page.
'''
def decorator(fn):
def wrapped_function(*args, **kwargs):
# User must be logged in.
if 'username' not in session:
flash("This page requires you to be logged in.")
# Store page to be loaded after login in session.
session['next'] = request.url
return redirect(url_for('login'))
# Check permissions.
if permission != None:
if not auth.check_permission(permission):
flash("You do not have permission to access this page.")
session['next'] = request.url
return redirect(url_for('login'))
return fn(*args, **kwargs)
return update_wrapper(wrapped_function, fn)
return decorator
|
Fix typo in login_required decorator
|
Fix typo in login_required decorator
|
Python
|
mit
|
RuddockHouse/RuddockWebsite,RuddockHouse/RuddockWebsite,RuddockHouse/RuddockWebsite
|
from functools import update_wrapper
from flask import session, redirect, flash
import auth
def login_required(permission=None):
'''
Login required decorator. Requires user to be logged in. If a permission
is provided, then user must also have the appropriate permissions to
access the page.
'''
def decorator(fn):
def wrapped_function(*args, **kwargs):
# User must be logged in.
if 'username' not in session:
flash("This page requires you to be logged in.")
# Store page to be loaded after login in session.
session['next'] = request.url
return redirect(url_for('login'))
# Check permissions.
if permission != None:
if not auth.check_permission(permission):
flash("You do have have permission to access this page.")
session['next'] = request.url
return redirect(url_for('login'))
return fn(*args, **kwargs)
return update_wrapper(wrapped_function, fn)
return decorator
Fix typo in login_required decorator
|
from functools import update_wrapper
from flask import session, redirect, flash
import auth
def login_required(permission=None):
'''
Login required decorator. Requires user to be logged in. If a permission
is provided, then user must also have the appropriate permissions to
access the page.
'''
def decorator(fn):
def wrapped_function(*args, **kwargs):
# User must be logged in.
if 'username' not in session:
flash("This page requires you to be logged in.")
# Store page to be loaded after login in session.
session['next'] = request.url
return redirect(url_for('login'))
# Check permissions.
if permission != None:
if not auth.check_permission(permission):
flash("You do not have permission to access this page.")
session['next'] = request.url
return redirect(url_for('login'))
return fn(*args, **kwargs)
return update_wrapper(wrapped_function, fn)
return decorator
|
<commit_before>from functools import update_wrapper
from flask import session, redirect, flash
import auth
def login_required(permission=None):
'''
Login required decorator. Requires user to be logged in. If a permission
is provided, then user must also have the appropriate permissions to
access the page.
'''
def decorator(fn):
def wrapped_function(*args, **kwargs):
# User must be logged in.
if 'username' not in session:
flash("This page requires you to be logged in.")
# Store page to be loaded after login in session.
session['next'] = request.url
return redirect(url_for('login'))
# Check permissions.
if permission != None:
if not auth.check_permission(permission):
flash("You do have have permission to access this page.")
session['next'] = request.url
return redirect(url_for('login'))
return fn(*args, **kwargs)
return update_wrapper(wrapped_function, fn)
return decorator
<commit_msg>Fix typo in login_required decorator<commit_after>
|
from functools import update_wrapper
from flask import session, redirect, flash
import auth
def login_required(permission=None):
'''
Login required decorator. Requires user to be logged in. If a permission
is provided, then user must also have the appropriate permissions to
access the page.
'''
def decorator(fn):
def wrapped_function(*args, **kwargs):
# User must be logged in.
if 'username' not in session:
flash("This page requires you to be logged in.")
# Store page to be loaded after login in session.
session['next'] = request.url
return redirect(url_for('login'))
# Check permissions.
if permission != None:
if not auth.check_permission(permission):
flash("You do not have permission to access this page.")
session['next'] = request.url
return redirect(url_for('login'))
return fn(*args, **kwargs)
return update_wrapper(wrapped_function, fn)
return decorator
|
from functools import update_wrapper
from flask import session, redirect, flash
import auth
def login_required(permission=None):
'''
Login required decorator. Requires user to be logged in. If a permission
is provided, then user must also have the appropriate permissions to
access the page.
'''
def decorator(fn):
def wrapped_function(*args, **kwargs):
# User must be logged in.
if 'username' not in session:
flash("This page requires you to be logged in.")
# Store page to be loaded after login in session.
session['next'] = request.url
return redirect(url_for('login'))
# Check permissions.
if permission != None:
if not auth.check_permission(permission):
flash("You do have have permission to access this page.")
session['next'] = request.url
return redirect(url_for('login'))
return fn(*args, **kwargs)
return update_wrapper(wrapped_function, fn)
return decorator
Fix typo in login_required decoratorfrom functools import update_wrapper
from flask import session, redirect, flash
import auth
def login_required(permission=None):
'''
Login required decorator. Requires user to be logged in. If a permission
is provided, then user must also have the appropriate permissions to
access the page.
'''
def decorator(fn):
def wrapped_function(*args, **kwargs):
# User must be logged in.
if 'username' not in session:
flash("This page requires you to be logged in.")
# Store page to be loaded after login in session.
session['next'] = request.url
return redirect(url_for('login'))
# Check permissions.
if permission != None:
if not auth.check_permission(permission):
flash("You do not have permission to access this page.")
session['next'] = request.url
return redirect(url_for('login'))
return fn(*args, **kwargs)
return update_wrapper(wrapped_function, fn)
return decorator
|
<commit_before>from functools import update_wrapper
from flask import session, redirect, flash
import auth
def login_required(permission=None):
'''
Login required decorator. Requires user to be logged in. If a permission
is provided, then user must also have the appropriate permissions to
access the page.
'''
def decorator(fn):
def wrapped_function(*args, **kwargs):
# User must be logged in.
if 'username' not in session:
flash("This page requires you to be logged in.")
# Store page to be loaded after login in session.
session['next'] = request.url
return redirect(url_for('login'))
# Check permissions.
if permission != None:
if not auth.check_permission(permission):
flash("You do have have permission to access this page.")
session['next'] = request.url
return redirect(url_for('login'))
return fn(*args, **kwargs)
return update_wrapper(wrapped_function, fn)
return decorator
<commit_msg>Fix typo in login_required decorator<commit_after>from functools import update_wrapper
from flask import session, redirect, flash
import auth
def login_required(permission=None):
'''
Login required decorator. Requires user to be logged in. If a permission
is provided, then user must also have the appropriate permissions to
access the page.
'''
def decorator(fn):
def wrapped_function(*args, **kwargs):
# User must be logged in.
if 'username' not in session:
flash("This page requires you to be logged in.")
# Store page to be loaded after login in session.
session['next'] = request.url
return redirect(url_for('login'))
# Check permissions.
if permission != None:
if not auth.check_permission(permission):
flash("You do not have permission to access this page.")
session['next'] = request.url
return redirect(url_for('login'))
return fn(*args, **kwargs)
return update_wrapper(wrapped_function, fn)
return decorator
|
21ce1aeb0359ef760a7936ed4123041e29b4f0b1
|
scripts/maf_limit_to_species.py
|
scripts/maf_limit_to_species.py
|
#!/usr/bin/env python2.3
"""
Read a maf file from stdin and write out a new maf with only blocks having all
of the required in species, after dropping any other species and removing
columns containing only gaps.
usage: %prog species,species2,... < maf
"""
import psyco_full
import bx.align.maf
import copy
import sys
from itertools import *
def main():
species = sys.argv[1].split( ',' )
maf_reader = bx.align.maf.Reader( sys.stdin )
maf_writer = bx.align.maf.Writer( sys.stdout )
for m in maf_reader:
new_components = []
for comp in m.components:
if comp.src.split( '.' )[0] in species:
new_components.append( comp )
m.components = new_components
if len( m.components ) > 1:
maf_writer.write( m )
maf_reader.close()
maf_writer.close()
if __name__ == "__main__":
main()
|
#!/usr/bin/env python2.3
"""
Read a maf file from stdin and write out a new maf with only blocks having all
of the required in species, after dropping any other species and removing
columns containing only gaps.
usage: %prog species,species2,... < maf
"""
import psyco_full
import bx.align.maf
import copy
import sys
from itertools import *
def main():
species = sys.argv[1].split( ',' )
maf_reader = bx.align.maf.Reader( sys.stdin )
maf_writer = bx.align.maf.Writer( sys.stdout )
for m in maf_reader:
new_components = []
for comp in m.components:
if comp.src.split( '.' )[0] in species:
new_components.append( comp )
m.components = new_components
m.remove_all_gap_columns()
if len( m.components ) > 1:
maf_writer.write( m )
maf_reader.close()
maf_writer.close()
if __name__ == "__main__":
main()
|
Remove all-gap columns after removing rows of the alignment
|
Remove all-gap columns after removing rows of the alignment
|
Python
|
mit
|
bxlab/bx-python,bxlab/bx-python,bxlab/bx-python
|
#!/usr/bin/env python2.3
"""
Read a maf file from stdin and write out a new maf with only blocks having all
of the required in species, after dropping any other species and removing
columns containing only gaps.
usage: %prog species,species2,... < maf
"""
import psyco_full
import bx.align.maf
import copy
import sys
from itertools import *
def main():
species = sys.argv[1].split( ',' )
maf_reader = bx.align.maf.Reader( sys.stdin )
maf_writer = bx.align.maf.Writer( sys.stdout )
for m in maf_reader:
new_components = []
for comp in m.components:
if comp.src.split( '.' )[0] in species:
new_components.append( comp )
m.components = new_components
if len( m.components ) > 1:
maf_writer.write( m )
maf_reader.close()
maf_writer.close()
if __name__ == "__main__":
main()
Remove all-gap columns after removing rows of the alignment
|
#!/usr/bin/env python2.3
"""
Read a maf file from stdin and write out a new maf with only blocks having all
of the required in species, after dropping any other species and removing
columns containing only gaps.
usage: %prog species,species2,... < maf
"""
import psyco_full
import bx.align.maf
import copy
import sys
from itertools import *
def main():
species = sys.argv[1].split( ',' )
maf_reader = bx.align.maf.Reader( sys.stdin )
maf_writer = bx.align.maf.Writer( sys.stdout )
for m in maf_reader:
new_components = []
for comp in m.components:
if comp.src.split( '.' )[0] in species:
new_components.append( comp )
m.components = new_components
m.remove_all_gap_columns()
if len( m.components ) > 1:
maf_writer.write( m )
maf_reader.close()
maf_writer.close()
if __name__ == "__main__":
main()
|
<commit_before>#!/usr/bin/env python2.3
"""
Read a maf file from stdin and write out a new maf with only blocks having all
of the required in species, after dropping any other species and removing
columns containing only gaps.
usage: %prog species,species2,... < maf
"""
import psyco_full
import bx.align.maf
import copy
import sys
from itertools import *
def main():
species = sys.argv[1].split( ',' )
maf_reader = bx.align.maf.Reader( sys.stdin )
maf_writer = bx.align.maf.Writer( sys.stdout )
for m in maf_reader:
new_components = []
for comp in m.components:
if comp.src.split( '.' )[0] in species:
new_components.append( comp )
m.components = new_components
if len( m.components ) > 1:
maf_writer.write( m )
maf_reader.close()
maf_writer.close()
if __name__ == "__main__":
main()
<commit_msg>Remove all-gap columns after removing rows of the alignment<commit_after>
|
#!/usr/bin/env python2.3
"""
Read a maf file from stdin and write out a new maf with only blocks having all
of the required in species, after dropping any other species and removing
columns containing only gaps.
usage: %prog species,species2,... < maf
"""
import psyco_full
import bx.align.maf
import copy
import sys
from itertools import *
def main():
species = sys.argv[1].split( ',' )
maf_reader = bx.align.maf.Reader( sys.stdin )
maf_writer = bx.align.maf.Writer( sys.stdout )
for m in maf_reader:
new_components = []
for comp in m.components:
if comp.src.split( '.' )[0] in species:
new_components.append( comp )
m.components = new_components
m.remove_all_gap_columns()
if len( m.components ) > 1:
maf_writer.write( m )
maf_reader.close()
maf_writer.close()
if __name__ == "__main__":
main()
|
#!/usr/bin/env python2.3
"""
Read a maf file from stdin and write out a new maf with only blocks having all
of the required in species, after dropping any other species and removing
columns containing only gaps.
usage: %prog species,species2,... < maf
"""
import psyco_full
import bx.align.maf
import copy
import sys
from itertools import *
def main():
species = sys.argv[1].split( ',' )
maf_reader = bx.align.maf.Reader( sys.stdin )
maf_writer = bx.align.maf.Writer( sys.stdout )
for m in maf_reader:
new_components = []
for comp in m.components:
if comp.src.split( '.' )[0] in species:
new_components.append( comp )
m.components = new_components
if len( m.components ) > 1:
maf_writer.write( m )
maf_reader.close()
maf_writer.close()
if __name__ == "__main__":
main()
Remove all-gap columns after removing rows of the alignment#!/usr/bin/env python2.3
"""
Read a maf file from stdin and write out a new maf with only blocks having all
of the required in species, after dropping any other species and removing
columns containing only gaps.
usage: %prog species,species2,... < maf
"""
import psyco_full
import bx.align.maf
import copy
import sys
from itertools import *
def main():
species = sys.argv[1].split( ',' )
maf_reader = bx.align.maf.Reader( sys.stdin )
maf_writer = bx.align.maf.Writer( sys.stdout )
for m in maf_reader:
new_components = []
for comp in m.components:
if comp.src.split( '.' )[0] in species:
new_components.append( comp )
m.components = new_components
m.remove_all_gap_columns()
if len( m.components ) > 1:
maf_writer.write( m )
maf_reader.close()
maf_writer.close()
if __name__ == "__main__":
main()
|
<commit_before>#!/usr/bin/env python2.3
"""
Read a maf file from stdin and write out a new maf with only blocks having all
of the required in species, after dropping any other species and removing
columns containing only gaps.
usage: %prog species,species2,... < maf
"""
import psyco_full
import bx.align.maf
import copy
import sys
from itertools import *
def main():
species = sys.argv[1].split( ',' )
maf_reader = bx.align.maf.Reader( sys.stdin )
maf_writer = bx.align.maf.Writer( sys.stdout )
for m in maf_reader:
new_components = []
for comp in m.components:
if comp.src.split( '.' )[0] in species:
new_components.append( comp )
m.components = new_components
if len( m.components ) > 1:
maf_writer.write( m )
maf_reader.close()
maf_writer.close()
if __name__ == "__main__":
main()
<commit_msg>Remove all-gap columns after removing rows of the alignment<commit_after>#!/usr/bin/env python2.3
"""
Read a maf file from stdin and write out a new maf with only blocks having all
of the required in species, after dropping any other species and removing
columns containing only gaps.
usage: %prog species,species2,... < maf
"""
import psyco_full
import bx.align.maf
import copy
import sys
from itertools import *
def main():
species = sys.argv[1].split( ',' )
maf_reader = bx.align.maf.Reader( sys.stdin )
maf_writer = bx.align.maf.Writer( sys.stdout )
for m in maf_reader:
new_components = []
for comp in m.components:
if comp.src.split( '.' )[0] in species:
new_components.append( comp )
m.components = new_components
m.remove_all_gap_columns()
if len( m.components ) > 1:
maf_writer.write( m )
maf_reader.close()
maf_writer.close()
if __name__ == "__main__":
main()
|
9d44c515dbb253e214ac0cd1145bddacc2586380
|
example/urls.py
|
example/urls.py
|
from django.conf.urls.defaults import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^comments/', include('fluent_comments.urls')),
url(r'^articles/', include('article.urls')),
url(r'^$', 'django.views.generic.simple.redirect_to', {'url': 'articles/', 'permanent': False}),
)
|
from django.conf.urls.defaults import patterns, include, url
from django.contrib import admin
from django.views.generic import RedirectView
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^comments/', include('fluent_comments.urls')),
url(r'^articles/', include('article.urls')),
url(r'^$', RedirectView.as_view(url='articles/', permanent=False)),
)
|
Fix running the example project with Django 1.5
|
Fix running the example project with Django 1.5
|
Python
|
apache-2.0
|
django-fluent/django-fluent-comments,akszydelko/django-fluent-comments,akszydelko/django-fluent-comments,Afnarel/django-fluent-comments,Afnarel/django-fluent-comments,edoburu/django-fluent-comments,Afnarel/django-fluent-comments,PetrDlouhy/django-fluent-comments,django-fluent/django-fluent-comments,edoburu/django-fluent-comments,edoburu/django-fluent-comments,django-fluent/django-fluent-comments,BangorUniversity/django-fluent-comments,akszydelko/django-fluent-comments,mgpyh/django-fluent-comments,django-fluent/django-fluent-comments,BangorUniversity/django-fluent-comments,mgpyh/django-fluent-comments,mgpyh/django-fluent-comments,BangorUniversity/django-fluent-comments,PetrDlouhy/django-fluent-comments,PetrDlouhy/django-fluent-comments
|
from django.conf.urls.defaults import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^comments/', include('fluent_comments.urls')),
url(r'^articles/', include('article.urls')),
url(r'^$', 'django.views.generic.simple.redirect_to', {'url': 'articles/', 'permanent': False}),
)
Fix running the example project with Django 1.5
|
from django.conf.urls.defaults import patterns, include, url
from django.contrib import admin
from django.views.generic import RedirectView
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^comments/', include('fluent_comments.urls')),
url(r'^articles/', include('article.urls')),
url(r'^$', RedirectView.as_view(url='articles/', permanent=False)),
)
|
<commit_before>from django.conf.urls.defaults import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^comments/', include('fluent_comments.urls')),
url(r'^articles/', include('article.urls')),
url(r'^$', 'django.views.generic.simple.redirect_to', {'url': 'articles/', 'permanent': False}),
)
<commit_msg>Fix running the example project with Django 1.5<commit_after>
|
from django.conf.urls.defaults import patterns, include, url
from django.contrib import admin
from django.views.generic import RedirectView
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^comments/', include('fluent_comments.urls')),
url(r'^articles/', include('article.urls')),
url(r'^$', RedirectView.as_view(url='articles/', permanent=False)),
)
|
from django.conf.urls.defaults import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^comments/', include('fluent_comments.urls')),
url(r'^articles/', include('article.urls')),
url(r'^$', 'django.views.generic.simple.redirect_to', {'url': 'articles/', 'permanent': False}),
)
Fix running the example project with Django 1.5from django.conf.urls.defaults import patterns, include, url
from django.contrib import admin
from django.views.generic import RedirectView
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^comments/', include('fluent_comments.urls')),
url(r'^articles/', include('article.urls')),
url(r'^$', RedirectView.as_view(url='articles/', permanent=False)),
)
|
<commit_before>from django.conf.urls.defaults import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^comments/', include('fluent_comments.urls')),
url(r'^articles/', include('article.urls')),
url(r'^$', 'django.views.generic.simple.redirect_to', {'url': 'articles/', 'permanent': False}),
)
<commit_msg>Fix running the example project with Django 1.5<commit_after>from django.conf.urls.defaults import patterns, include, url
from django.contrib import admin
from django.views.generic import RedirectView
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^comments/', include('fluent_comments.urls')),
url(r'^articles/', include('article.urls')),
url(r'^$', RedirectView.as_view(url='articles/', permanent=False)),
)
|
c92a56dc937dc414139e2bff958190cfb18de5d9
|
tests/basics/try2.py
|
tests/basics/try2.py
|
# nested try's
try:
print("try 1")
try:
print("try 2")
foo()
except:
print("except 2")
bar()
except:
print("except 1")
try:
print("try 1")
try:
print("try 2")
foo()
except TypeError:
print("except 2")
bar()
except NameError:
print("except 1")
|
# nested try's
try:
print("try 1")
try:
print("try 2")
foo()
except:
print("except 2")
bar()
except:
print("except 1")
try:
print("try 1")
try:
print("try 2")
foo()
except TypeError:
print("except 2")
bar()
except NameError:
print("except 1")
# Check that exceptions across function boundaries work as expected
def func1():
try:
print("try func1")
func2()
except NameError:
print("except func1")
def func2():
try:
print("try func2")
foo()
except TypeError:
print("except func2")
func1()
|
Add testcase with exception handler spread across functions.
|
Add testcase with exception handler spread across functions.
|
Python
|
mit
|
SHA2017-badge/micropython-esp32,skybird6672/micropython,vriera/micropython,SHA2017-badge/micropython-esp32,jimkmc/micropython,cnoviello/micropython,cloudformdesign/micropython,emfcamp/micropython,dhylands/micropython,xuxiaoxin/micropython,AriZuu/micropython,cloudformdesign/micropython,selste/micropython,ryannathans/micropython,pramasoul/micropython,hiway/micropython,jmarcelino/pycom-micropython,galenhz/micropython,bvernoux/micropython,TDAbboud/micropython,danicampora/micropython,dhylands/micropython,xhat/micropython,suda/micropython,noahwilliamsson/micropython,jmarcelino/pycom-micropython,dinau/micropython,bvernoux/micropython,firstval/micropython,bvernoux/micropython,utopiaprince/micropython,rubencabrera/micropython,ryannathans/micropython,deshipu/micropython,paul-xxx/micropython,micropython/micropython-esp32,warner83/micropython,ruffy91/micropython,emfcamp/micropython,henriknelson/micropython,kerneltask/micropython,jimkmc/micropython,henriknelson/micropython,infinnovation/micropython,xuxiaoxin/micropython,noahwilliamsson/micropython,tobbad/micropython,redbear/micropython,xuxiaoxin/micropython,dmazzella/micropython,lowRISC/micropython,neilh10/micropython,adafruit/micropython,kostyll/micropython,firstval/micropython,stonegithubs/micropython,slzatz/micropython,henriknelson/micropython,suda/micropython,adafruit/circuitpython,slzatz/micropython,aethaniel/micropython,vriera/micropython,martinribelotta/micropython,hosaka/micropython,TDAbboud/micropython,blmorris/micropython,AriZuu/micropython,vriera/micropython,utopiaprince/micropython,Peetz0r/micropython-esp32,aethaniel/micropython,Vogtinator/micropython,cnoviello/micropython,kerneltask/micropython,mgyenik/micropython,supergis/micropython,firstval/micropython,dinau/micropython,emfcamp/micropython,lowRISC/micropython,ernesto-g/micropython,EcmaXp/micropython,stonegithubs/micropython,PappaPeppar/micropython,ahotam/micropython,Vogtinator/micropython,micropython/micropython-esp32,xyb/micropython,jmarcelino/pycom-micropython,aitjcize/micropython,warner83/micropython,noahchense/micropython,martinribelotta/micropython,infinnovation/micropython,trezor/micropython,HenrikSolver/micropython,jlillest/micropython,dhylands/micropython,SHA2017-badge/micropython-esp32,mhoffma/micropython,SungEun-Steve-Kim/test-mp,dhylands/micropython,torwag/micropython,praemdonck/micropython,adamkh/micropython,ChuckM/micropython,feilongfl/micropython,torwag/micropython,puuu/micropython,pramasoul/micropython,ericsnowcurrently/micropython,tdautc19841202/micropython,ruffy91/micropython,AriZuu/micropython,feilongfl/micropython,vitiral/micropython,methoxid/micropystat,oopy/micropython,mgyenik/micropython,mpalomer/micropython,suda/micropython,kerneltask/micropython,stonegithubs/micropython,suda/micropython,deshipu/micropython,PappaPeppar/micropython,adamkh/micropython,hosaka/micropython,orionrobots/micropython,hosaka/micropython,galenhz/micropython,jlillest/micropython,bvernoux/micropython,deshipu/micropython,jimkmc/micropython,ryannathans/micropython,ruffy91/micropython,mgyenik/micropython,pfalcon/micropython,EcmaXp/micropython,Vogtinator/micropython,pramasoul/micropython,misterdanb/micropython,tobbad/micropython,matthewelse/micropython,tuc-osg/micropython,xhat/micropython,cwyark/micropython,praemdonck/micropython,MrSurly/micropython,neilh10/micropython,toolmacher/micropython,aitjcize/micropython,matthewelse/micropython,infinnovation/micropython,ganshun666/micropython,noahwilliamsson/micropython,praemdonck/micropython,lbattraw/micropython,turbinenreiter/micropython,drrk/micropython,AriZuu/micropython,Timmenem/micropython,heisewangluo/micropython,vriera/micropython,puuu/micropython,HenrikSolver/micropython,drrk/micropython,blazewicz/micropython,adafruit/circuitpython,slzatz/micropython,tobbad/micropython,noahchense/micropython,adafruit/micropython,mhoffma/micropython,pozetroninc/micropython,mpalomer/micropython,dxxb/micropython,cwyark/micropython,danicampora/micropython,HenrikSolver/micropython,turbinenreiter/micropython,kostyll/micropython,danicampora/micropython,cwyark/micropython,cnoviello/micropython,dmazzella/micropython,trezor/micropython,lbattraw/micropython,misterdanb/micropython,jmarcelino/pycom-micropython,jmarcelino/pycom-micropython,supergis/micropython,TDAbboud/micropython,omtinez/micropython,feilongfl/micropython,selste/micropython,jlillest/micropython,alex-march/micropython,mianos/micropython,lowRISC/micropython,tralamazza/micropython,kostyll/micropython,swegener/micropython,methoxid/micropystat,swegener/micropython,pfalcon/micropython,rubencabrera/micropython,mianos/micropython,PappaPeppar/micropython,rubencabrera/micropython,Peetz0r/micropython-esp32,noahchense/micropython,alex-robbins/micropython,pozetroninc/micropython,ChuckM/micropython,matthewelse/micropython,trezor/micropython,emfcamp/micropython,ChuckM/micropython,omtinez/micropython,ahotam/micropython,warner83/micropython,mhoffma/micropython,KISSMonX/micropython,cloudformdesign/micropython,hiway/micropython,paul-xxx/micropython,xyb/micropython,galenhz/micropython,methoxid/micropystat,blazewicz/micropython,neilh10/micropython,ganshun666/micropython,torwag/micropython,skybird6672/micropython,supergis/micropython,aitjcize/micropython,firstval/micropython,noahwilliamsson/micropython,warner83/micropython,pfalcon/micropython,aitjcize/micropython,adafruit/micropython,bvernoux/micropython,EcmaXp/micropython,alex-march/micropython,HenrikSolver/micropython,Timmenem/micropython,torwag/micropython,chrisdearman/micropython,pozetroninc/micropython,tuc-osg/micropython,kostyll/micropython,micropython/micropython-esp32,MrSurly/micropython,xuxiaoxin/micropython,SHA2017-badge/micropython-esp32,hiway/micropython,drrk/micropython,xuxiaoxin/micropython,ganshun666/micropython,heisewangluo/micropython,toolmacher/micropython,dinau/micropython,Timmenem/micropython,AriZuu/micropython,lbattraw/micropython,chrisdearman/micropython,vriera/micropython,orionrobots/micropython,selste/micropython,omtinez/micropython,skybird6672/micropython,dinau/micropython,xhat/micropython,TDAbboud/micropython,adafruit/circuitpython,adafruit/circuitpython,praemdonck/micropython,torwag/micropython,orionrobots/micropython,paul-xxx/micropython,oopy/micropython,neilh10/micropython,xhat/micropython,ahotam/micropython,SungEun-Steve-Kim/test-mp,drrk/micropython,danicampora/micropython,utopiaprince/micropython,xyb/micropython,blmorris/micropython,Vogtinator/micropython,paul-xxx/micropython,selste/micropython,tdautc19841202/micropython,MrSurly/micropython,dxxb/micropython,cwyark/micropython,tdautc19841202/micropython,vitiral/micropython,toolmacher/micropython,pramasoul/micropython,deshipu/micropython,tralamazza/micropython,swegener/micropython,hosaka/micropython,paul-xxx/micropython,feilongfl/micropython,alex-march/micropython,mpalomer/micropython,tdautc19841202/micropython,Vogtinator/micropython,ericsnowcurrently/micropython,xyb/micropython,jlillest/micropython,alex-robbins/micropython,infinnovation/micropython,oopy/micropython,cnoviello/micropython,mpalomer/micropython,adafruit/circuitpython,neilh10/micropython,adamkh/micropython,toolmacher/micropython,emfcamp/micropython,ChuckM/micropython,mpalomer/micropython,warner83/micropython,SungEun-Steve-Kim/test-mp,methoxid/micropystat,ceramos/micropython,slzatz/micropython,MrSurly/micropython-esp32,skybird6672/micropython,ganshun666/micropython,KISSMonX/micropython,adamkh/micropython,pozetroninc/micropython,Peetz0r/micropython-esp32,kerneltask/micropython,micropython/micropython-esp32,ericsnowcurrently/micropython,ruffy91/micropython,KISSMonX/micropython,chrisdearman/micropython,dxxb/micropython,turbinenreiter/micropython,tdautc19841202/micropython,dhylands/micropython,deshipu/micropython,turbinenreiter/micropython,blazewicz/micropython,adamkh/micropython,PappaPeppar/micropython,infinnovation/micropython,xhat/micropython,hiway/micropython,MrSurly/micropython,SHA2017-badge/micropython-esp32,misterdanb/micropython,ericsnowcurrently/micropython,EcmaXp/micropython,galenhz/micropython,mianos/micropython,ernesto-g/micropython,ceramos/micropython,lbattraw/micropython,alex-march/micropython,cloudformdesign/micropython,adafruit/circuitpython,orionrobots/micropython,puuu/micropython,alex-robbins/micropython,tuc-osg/micropython,ChuckM/micropython,dmazzella/micropython,supergis/micropython,trezor/micropython,vitiral/micropython,redbear/micropython,utopiaprince/micropython,misterdanb/micropython,lowRISC/micropython,ryannathans/micropython,dinau/micropython,drrk/micropython,ernesto-g/micropython,hosaka/micropython,mhoffma/micropython,noahwilliamsson/micropython,ceramos/micropython,adafruit/micropython,MrSurly/micropython-esp32,tobbad/micropython,supergis/micropython,kerneltask/micropython,martinribelotta/micropython,ernesto-g/micropython,blmorris/micropython,EcmaXp/micropython,ernesto-g/micropython,alex-robbins/micropython,alex-march/micropython,mhoffma/micropython,ericsnowcurrently/micropython,ceramos/micropython,noahchense/micropython,TDAbboud/micropython,pozetroninc/micropython,MrSurly/micropython-esp32,KISSMonX/micropython,Peetz0r/micropython-esp32,martinribelotta/micropython,blmorris/micropython,noahchense/micropython,jimkmc/micropython,skybird6672/micropython,Peetz0r/micropython-esp32,matthewelse/micropython,dxxb/micropython,SungEun-Steve-Kim/test-mp,aethaniel/micropython,aethaniel/micropython,heisewangluo/micropython,lowRISC/micropython,tuc-osg/micropython,blazewicz/micropython,omtinez/micropython,MrSurly/micropython-esp32,vitiral/micropython,misterdanb/micropython,PappaPeppar/micropython,selste/micropython,lbattraw/micropython,ahotam/micropython,turbinenreiter/micropython,rubencabrera/micropython,suda/micropython,aethaniel/micropython,cnoviello/micropython,cloudformdesign/micropython,tralamazza/micropython,trezor/micropython,danicampora/micropython,mgyenik/micropython,tobbad/micropython,mianos/micropython,MrSurly/micropython,SungEun-Steve-Kim/test-mp,HenrikSolver/micropython,vitiral/micropython,redbear/micropython,micropython/micropython-esp32,ganshun666/micropython,toolmacher/micropython,stonegithubs/micropython,swegener/micropython,mgyenik/micropython,puuu/micropython,martinribelotta/micropython,pfalcon/micropython,jlillest/micropython,chrisdearman/micropython,Timmenem/micropython,heisewangluo/micropython,Timmenem/micropython,alex-robbins/micropython,slzatz/micropython,ceramos/micropython,dxxb/micropython,puuu/micropython,pfalcon/micropython,henriknelson/micropython,praemdonck/micropython,KISSMonX/micropython,galenhz/micropython,matthewelse/micropython,utopiaprince/micropython,redbear/micropython,mianos/micropython,feilongfl/micropython,xyb/micropython,tuc-osg/micropython,MrSurly/micropython-esp32,redbear/micropython,swegener/micropython,firstval/micropython,stonegithubs/micropython,pramasoul/micropython,ryannathans/micropython,methoxid/micropystat,oopy/micropython,chrisdearman/micropython,rubencabrera/micropython,ruffy91/micropython,ahotam/micropython,adafruit/micropython,omtinez/micropython,blazewicz/micropython,heisewangluo/micropython,kostyll/micropython,matthewelse/micropython,tralamazza/micropython,hiway/micropython,blmorris/micropython,jimkmc/micropython,henriknelson/micropython,dmazzella/micropython,cwyark/micropython,oopy/micropython,orionrobots/micropython
|
# nested try's
try:
print("try 1")
try:
print("try 2")
foo()
except:
print("except 2")
bar()
except:
print("except 1")
try:
print("try 1")
try:
print("try 2")
foo()
except TypeError:
print("except 2")
bar()
except NameError:
print("except 1")
Add testcase with exception handler spread across functions.
|
# nested try's
try:
print("try 1")
try:
print("try 2")
foo()
except:
print("except 2")
bar()
except:
print("except 1")
try:
print("try 1")
try:
print("try 2")
foo()
except TypeError:
print("except 2")
bar()
except NameError:
print("except 1")
# Check that exceptions across function boundaries work as expected
def func1():
try:
print("try func1")
func2()
except NameError:
print("except func1")
def func2():
try:
print("try func2")
foo()
except TypeError:
print("except func2")
func1()
|
<commit_before># nested try's
try:
print("try 1")
try:
print("try 2")
foo()
except:
print("except 2")
bar()
except:
print("except 1")
try:
print("try 1")
try:
print("try 2")
foo()
except TypeError:
print("except 2")
bar()
except NameError:
print("except 1")
<commit_msg>Add testcase with exception handler spread across functions.<commit_after>
|
# nested try's
try:
print("try 1")
try:
print("try 2")
foo()
except:
print("except 2")
bar()
except:
print("except 1")
try:
print("try 1")
try:
print("try 2")
foo()
except TypeError:
print("except 2")
bar()
except NameError:
print("except 1")
# Check that exceptions across function boundaries work as expected
def func1():
try:
print("try func1")
func2()
except NameError:
print("except func1")
def func2():
try:
print("try func2")
foo()
except TypeError:
print("except func2")
func1()
|
# nested try's
try:
print("try 1")
try:
print("try 2")
foo()
except:
print("except 2")
bar()
except:
print("except 1")
try:
print("try 1")
try:
print("try 2")
foo()
except TypeError:
print("except 2")
bar()
except NameError:
print("except 1")
Add testcase with exception handler spread across functions.# nested try's
try:
print("try 1")
try:
print("try 2")
foo()
except:
print("except 2")
bar()
except:
print("except 1")
try:
print("try 1")
try:
print("try 2")
foo()
except TypeError:
print("except 2")
bar()
except NameError:
print("except 1")
# Check that exceptions across function boundaries work as expected
def func1():
try:
print("try func1")
func2()
except NameError:
print("except func1")
def func2():
try:
print("try func2")
foo()
except TypeError:
print("except func2")
func1()
|
<commit_before># nested try's
try:
print("try 1")
try:
print("try 2")
foo()
except:
print("except 2")
bar()
except:
print("except 1")
try:
print("try 1")
try:
print("try 2")
foo()
except TypeError:
print("except 2")
bar()
except NameError:
print("except 1")
<commit_msg>Add testcase with exception handler spread across functions.<commit_after># nested try's
try:
print("try 1")
try:
print("try 2")
foo()
except:
print("except 2")
bar()
except:
print("except 1")
try:
print("try 1")
try:
print("try 2")
foo()
except TypeError:
print("except 2")
bar()
except NameError:
print("except 1")
# Check that exceptions across function boundaries work as expected
def func1():
try:
print("try func1")
func2()
except NameError:
print("except func1")
def func2():
try:
print("try func2")
foo()
except TypeError:
print("except func2")
func1()
|
33c7bd546236497aae9b0c96d6ae4c41f317a00e
|
saau/sections/transportation/data.py
|
saau/sections/transportation/data.py
|
from operator import itemgetter
from itertools import chain
from typing import List
from ...utils.py3_hook import with_hook
with with_hook():
from arcrest import Catalog
import numpy as np
def get_layers(service):
layers = service.layers
return {
layer.name: layer
for layer in layers
}
def mend_extent(extent):
extent.wkid = extent.spatialReference.wkid
return extent
def get_data(requested_layers: List[str]):
catalog = Catalog('http://services.ga.gov.au/site_7/rest/services')
service = catalog['NM_Transport_Infrastructure']
layers = get_layers(service)
return chain.from_iterable(
layers[layer].QueryLayer(Geometry=mend_extent(layers[layer].extent))
for layer in requested_layers
)
def get_paths(request_layers: List[str]) -> np.array:
paths = get_data(request_layers)
paths = map(itemgetter('geometry'), paths)
paths = chain.from_iterable(
geometry.paths
for geometry in paths
if hasattr(geometry, 'paths')
)
return np.array([
tuple(
(part.x, part.y)
for part in path
)
for path in paths
])
|
from operator import itemgetter
from itertools import chain
from typing import List
import cgi
from urllib.parse import parse_qs
from ...utils.py3_hook import with_hook
with with_hook():
from arcrest import Catalog
import numpy as np
cgi.parse_qs = parse_qs
def get_layers(service):
layers = service.layers
return {
layer.name: layer
for layer in layers
}
def mend_extent(extent):
extent.wkid = extent.spatialReference.wkid
return extent
def get_data(requested_layers: List[str]):
catalog = Catalog('http://services.ga.gov.au/site_7/rest/services')
service = catalog['NM_Transport_Infrastructure']
layers = get_layers(service)
return chain.from_iterable(
layers[layer].QueryLayer(Geometry=mend_extent(layers[layer].extent))
for layer in requested_layers
)
def get_paths(request_layers: List[str]) -> np.array:
paths = get_data(request_layers)
paths = map(itemgetter('geometry'), paths)
paths = chain.from_iterable(
geometry.paths
for geometry in paths
if hasattr(geometry, 'paths')
)
return np.array([
tuple(
(part.x, part.y)
for part in path
)
for path in paths
])
|
Patch missing method on cgi package
|
Patch missing method on cgi package
|
Python
|
mit
|
Mause/statistical_atlas_of_au
|
from operator import itemgetter
from itertools import chain
from typing import List
from ...utils.py3_hook import with_hook
with with_hook():
from arcrest import Catalog
import numpy as np
def get_layers(service):
layers = service.layers
return {
layer.name: layer
for layer in layers
}
def mend_extent(extent):
extent.wkid = extent.spatialReference.wkid
return extent
def get_data(requested_layers: List[str]):
catalog = Catalog('http://services.ga.gov.au/site_7/rest/services')
service = catalog['NM_Transport_Infrastructure']
layers = get_layers(service)
return chain.from_iterable(
layers[layer].QueryLayer(Geometry=mend_extent(layers[layer].extent))
for layer in requested_layers
)
def get_paths(request_layers: List[str]) -> np.array:
paths = get_data(request_layers)
paths = map(itemgetter('geometry'), paths)
paths = chain.from_iterable(
geometry.paths
for geometry in paths
if hasattr(geometry, 'paths')
)
return np.array([
tuple(
(part.x, part.y)
for part in path
)
for path in paths
])
Patch missing method on cgi package
|
from operator import itemgetter
from itertools import chain
from typing import List
import cgi
from urllib.parse import parse_qs
from ...utils.py3_hook import with_hook
with with_hook():
from arcrest import Catalog
import numpy as np
cgi.parse_qs = parse_qs
def get_layers(service):
layers = service.layers
return {
layer.name: layer
for layer in layers
}
def mend_extent(extent):
extent.wkid = extent.spatialReference.wkid
return extent
def get_data(requested_layers: List[str]):
catalog = Catalog('http://services.ga.gov.au/site_7/rest/services')
service = catalog['NM_Transport_Infrastructure']
layers = get_layers(service)
return chain.from_iterable(
layers[layer].QueryLayer(Geometry=mend_extent(layers[layer].extent))
for layer in requested_layers
)
def get_paths(request_layers: List[str]) -> np.array:
paths = get_data(request_layers)
paths = map(itemgetter('geometry'), paths)
paths = chain.from_iterable(
geometry.paths
for geometry in paths
if hasattr(geometry, 'paths')
)
return np.array([
tuple(
(part.x, part.y)
for part in path
)
for path in paths
])
|
<commit_before>from operator import itemgetter
from itertools import chain
from typing import List
from ...utils.py3_hook import with_hook
with with_hook():
from arcrest import Catalog
import numpy as np
def get_layers(service):
layers = service.layers
return {
layer.name: layer
for layer in layers
}
def mend_extent(extent):
extent.wkid = extent.spatialReference.wkid
return extent
def get_data(requested_layers: List[str]):
catalog = Catalog('http://services.ga.gov.au/site_7/rest/services')
service = catalog['NM_Transport_Infrastructure']
layers = get_layers(service)
return chain.from_iterable(
layers[layer].QueryLayer(Geometry=mend_extent(layers[layer].extent))
for layer in requested_layers
)
def get_paths(request_layers: List[str]) -> np.array:
paths = get_data(request_layers)
paths = map(itemgetter('geometry'), paths)
paths = chain.from_iterable(
geometry.paths
for geometry in paths
if hasattr(geometry, 'paths')
)
return np.array([
tuple(
(part.x, part.y)
for part in path
)
for path in paths
])
<commit_msg>Patch missing method on cgi package<commit_after>
|
from operator import itemgetter
from itertools import chain
from typing import List
import cgi
from urllib.parse import parse_qs
from ...utils.py3_hook import with_hook
with with_hook():
from arcrest import Catalog
import numpy as np
cgi.parse_qs = parse_qs
def get_layers(service):
layers = service.layers
return {
layer.name: layer
for layer in layers
}
def mend_extent(extent):
extent.wkid = extent.spatialReference.wkid
return extent
def get_data(requested_layers: List[str]):
catalog = Catalog('http://services.ga.gov.au/site_7/rest/services')
service = catalog['NM_Transport_Infrastructure']
layers = get_layers(service)
return chain.from_iterable(
layers[layer].QueryLayer(Geometry=mend_extent(layers[layer].extent))
for layer in requested_layers
)
def get_paths(request_layers: List[str]) -> np.array:
paths = get_data(request_layers)
paths = map(itemgetter('geometry'), paths)
paths = chain.from_iterable(
geometry.paths
for geometry in paths
if hasattr(geometry, 'paths')
)
return np.array([
tuple(
(part.x, part.y)
for part in path
)
for path in paths
])
|
from operator import itemgetter
from itertools import chain
from typing import List
from ...utils.py3_hook import with_hook
with with_hook():
from arcrest import Catalog
import numpy as np
def get_layers(service):
layers = service.layers
return {
layer.name: layer
for layer in layers
}
def mend_extent(extent):
extent.wkid = extent.spatialReference.wkid
return extent
def get_data(requested_layers: List[str]):
catalog = Catalog('http://services.ga.gov.au/site_7/rest/services')
service = catalog['NM_Transport_Infrastructure']
layers = get_layers(service)
return chain.from_iterable(
layers[layer].QueryLayer(Geometry=mend_extent(layers[layer].extent))
for layer in requested_layers
)
def get_paths(request_layers: List[str]) -> np.array:
paths = get_data(request_layers)
paths = map(itemgetter('geometry'), paths)
paths = chain.from_iterable(
geometry.paths
for geometry in paths
if hasattr(geometry, 'paths')
)
return np.array([
tuple(
(part.x, part.y)
for part in path
)
for path in paths
])
Patch missing method on cgi packagefrom operator import itemgetter
from itertools import chain
from typing import List
import cgi
from urllib.parse import parse_qs
from ...utils.py3_hook import with_hook
with with_hook():
from arcrest import Catalog
import numpy as np
cgi.parse_qs = parse_qs
def get_layers(service):
layers = service.layers
return {
layer.name: layer
for layer in layers
}
def mend_extent(extent):
extent.wkid = extent.spatialReference.wkid
return extent
def get_data(requested_layers: List[str]):
catalog = Catalog('http://services.ga.gov.au/site_7/rest/services')
service = catalog['NM_Transport_Infrastructure']
layers = get_layers(service)
return chain.from_iterable(
layers[layer].QueryLayer(Geometry=mend_extent(layers[layer].extent))
for layer in requested_layers
)
def get_paths(request_layers: List[str]) -> np.array:
paths = get_data(request_layers)
paths = map(itemgetter('geometry'), paths)
paths = chain.from_iterable(
geometry.paths
for geometry in paths
if hasattr(geometry, 'paths')
)
return np.array([
tuple(
(part.x, part.y)
for part in path
)
for path in paths
])
|
<commit_before>from operator import itemgetter
from itertools import chain
from typing import List
from ...utils.py3_hook import with_hook
with with_hook():
from arcrest import Catalog
import numpy as np
def get_layers(service):
layers = service.layers
return {
layer.name: layer
for layer in layers
}
def mend_extent(extent):
extent.wkid = extent.spatialReference.wkid
return extent
def get_data(requested_layers: List[str]):
catalog = Catalog('http://services.ga.gov.au/site_7/rest/services')
service = catalog['NM_Transport_Infrastructure']
layers = get_layers(service)
return chain.from_iterable(
layers[layer].QueryLayer(Geometry=mend_extent(layers[layer].extent))
for layer in requested_layers
)
def get_paths(request_layers: List[str]) -> np.array:
paths = get_data(request_layers)
paths = map(itemgetter('geometry'), paths)
paths = chain.from_iterable(
geometry.paths
for geometry in paths
if hasattr(geometry, 'paths')
)
return np.array([
tuple(
(part.x, part.y)
for part in path
)
for path in paths
])
<commit_msg>Patch missing method on cgi package<commit_after>from operator import itemgetter
from itertools import chain
from typing import List
import cgi
from urllib.parse import parse_qs
from ...utils.py3_hook import with_hook
with with_hook():
from arcrest import Catalog
import numpy as np
cgi.parse_qs = parse_qs
def get_layers(service):
layers = service.layers
return {
layer.name: layer
for layer in layers
}
def mend_extent(extent):
extent.wkid = extent.spatialReference.wkid
return extent
def get_data(requested_layers: List[str]):
catalog = Catalog('http://services.ga.gov.au/site_7/rest/services')
service = catalog['NM_Transport_Infrastructure']
layers = get_layers(service)
return chain.from_iterable(
layers[layer].QueryLayer(Geometry=mend_extent(layers[layer].extent))
for layer in requested_layers
)
def get_paths(request_layers: List[str]) -> np.array:
paths = get_data(request_layers)
paths = map(itemgetter('geometry'), paths)
paths = chain.from_iterable(
geometry.paths
for geometry in paths
if hasattr(geometry, 'paths')
)
return np.array([
tuple(
(part.x, part.y)
for part in path
)
for path in paths
])
|
a818427216f71272ae8410f63927db4891dbe39e
|
netmiko/hp/hp_procurve_ssh.py
|
netmiko/hp/hp_procurve_ssh.py
|
from __future__ import print_function
from __future__ import unicode_literals
import re
import time
from netmiko.cisco_base_connection import CiscoSSHConnection
class HPProcurveSSH(CiscoSSHConnection):
def session_preparation(self):
"""
Prepare the session after the connection has been established.
Procurve uses - 'Press any key to continue'
"""
delay_factor = self.select_delay_factor(delay_factor=0)
time.sleep(1 * delay_factor)
self.write_channel("\n")
time.sleep(1 * delay_factor)
# HP output contains VT100 escape codes
self.ansi_escape_codes = True
self.set_base_prompt()
self.disable_paging(command="\nno page\n")
self.set_terminal_width(command='terminal width 511')
def enable(self, cmd='enable', pattern='password', re_flags=re.IGNORECASE,
default_username='manager'):
"""Enter enable mode"""
debug = False
output = self.send_command_timing(cmd)
if 'username' in output.lower():
output += self.send_command_timing(default_username)
if 'password' in output.lower():
output += self.send_command_timing(self.secret)
if debug:
print(output)
self.clear_buffer()
return output
|
from __future__ import print_function
from __future__ import unicode_literals
import re
import time
from netmiko.cisco_base_connection import CiscoSSHConnection
class HPProcurveSSH(CiscoSSHConnection):
def session_preparation(self):
"""
Prepare the session after the connection has been established.
Procurve uses - 'Press any key to continue'
"""
delay_factor = self.select_delay_factor(delay_factor=0)
time.sleep(1 * delay_factor)
self.write_channel("\n")
time.sleep(1 * delay_factor)
self.write_channel("\n")
time.sleep(1 * delay_factor)
# HP output contains VT100 escape codes
self.ansi_escape_codes = True
self.set_base_prompt()
self.disable_paging(command="\nno page\n")
self.set_terminal_width(command='terminal width 511')
def enable(self, cmd='enable', pattern='password', re_flags=re.IGNORECASE,
default_username='manager'):
"""Enter enable mode"""
debug = False
output = self.send_command_timing(cmd)
if 'username' in output.lower():
output += self.send_command_timing(default_username)
if 'password' in output.lower():
output += self.send_command_timing(self.secret)
if debug:
print(output)
self.clear_buffer()
return output
|
Fix issue with HP ProCurve stacks and multiple hit enter to continue messages
|
Fix issue with HP ProCurve stacks and multiple hit enter to continue messages
|
Python
|
mit
|
fooelisa/netmiko,ktbyers/netmiko,shamanu4/netmiko,ktbyers/netmiko,isidroamv/netmiko,fooelisa/netmiko,shamanu4/netmiko,isidroamv/netmiko
|
from __future__ import print_function
from __future__ import unicode_literals
import re
import time
from netmiko.cisco_base_connection import CiscoSSHConnection
class HPProcurveSSH(CiscoSSHConnection):
def session_preparation(self):
"""
Prepare the session after the connection has been established.
Procurve uses - 'Press any key to continue'
"""
delay_factor = self.select_delay_factor(delay_factor=0)
time.sleep(1 * delay_factor)
self.write_channel("\n")
time.sleep(1 * delay_factor)
# HP output contains VT100 escape codes
self.ansi_escape_codes = True
self.set_base_prompt()
self.disable_paging(command="\nno page\n")
self.set_terminal_width(command='terminal width 511')
def enable(self, cmd='enable', pattern='password', re_flags=re.IGNORECASE,
default_username='manager'):
"""Enter enable mode"""
debug = False
output = self.send_command_timing(cmd)
if 'username' in output.lower():
output += self.send_command_timing(default_username)
if 'password' in output.lower():
output += self.send_command_timing(self.secret)
if debug:
print(output)
self.clear_buffer()
return output
Fix issue with HP ProCurve stacks and multiple hit enter to continue messages
|
from __future__ import print_function
from __future__ import unicode_literals
import re
import time
from netmiko.cisco_base_connection import CiscoSSHConnection
class HPProcurveSSH(CiscoSSHConnection):
def session_preparation(self):
"""
Prepare the session after the connection has been established.
Procurve uses - 'Press any key to continue'
"""
delay_factor = self.select_delay_factor(delay_factor=0)
time.sleep(1 * delay_factor)
self.write_channel("\n")
time.sleep(1 * delay_factor)
self.write_channel("\n")
time.sleep(1 * delay_factor)
# HP output contains VT100 escape codes
self.ansi_escape_codes = True
self.set_base_prompt()
self.disable_paging(command="\nno page\n")
self.set_terminal_width(command='terminal width 511')
def enable(self, cmd='enable', pattern='password', re_flags=re.IGNORECASE,
default_username='manager'):
"""Enter enable mode"""
debug = False
output = self.send_command_timing(cmd)
if 'username' in output.lower():
output += self.send_command_timing(default_username)
if 'password' in output.lower():
output += self.send_command_timing(self.secret)
if debug:
print(output)
self.clear_buffer()
return output
|
<commit_before>from __future__ import print_function
from __future__ import unicode_literals
import re
import time
from netmiko.cisco_base_connection import CiscoSSHConnection
class HPProcurveSSH(CiscoSSHConnection):
def session_preparation(self):
"""
Prepare the session after the connection has been established.
Procurve uses - 'Press any key to continue'
"""
delay_factor = self.select_delay_factor(delay_factor=0)
time.sleep(1 * delay_factor)
self.write_channel("\n")
time.sleep(1 * delay_factor)
# HP output contains VT100 escape codes
self.ansi_escape_codes = True
self.set_base_prompt()
self.disable_paging(command="\nno page\n")
self.set_terminal_width(command='terminal width 511')
def enable(self, cmd='enable', pattern='password', re_flags=re.IGNORECASE,
default_username='manager'):
"""Enter enable mode"""
debug = False
output = self.send_command_timing(cmd)
if 'username' in output.lower():
output += self.send_command_timing(default_username)
if 'password' in output.lower():
output += self.send_command_timing(self.secret)
if debug:
print(output)
self.clear_buffer()
return output
<commit_msg>Fix issue with HP ProCurve stacks and multiple hit enter to continue messages<commit_after>
|
from __future__ import print_function
from __future__ import unicode_literals
import re
import time
from netmiko.cisco_base_connection import CiscoSSHConnection
class HPProcurveSSH(CiscoSSHConnection):
def session_preparation(self):
"""
Prepare the session after the connection has been established.
Procurve uses - 'Press any key to continue'
"""
delay_factor = self.select_delay_factor(delay_factor=0)
time.sleep(1 * delay_factor)
self.write_channel("\n")
time.sleep(1 * delay_factor)
self.write_channel("\n")
time.sleep(1 * delay_factor)
# HP output contains VT100 escape codes
self.ansi_escape_codes = True
self.set_base_prompt()
self.disable_paging(command="\nno page\n")
self.set_terminal_width(command='terminal width 511')
def enable(self, cmd='enable', pattern='password', re_flags=re.IGNORECASE,
default_username='manager'):
"""Enter enable mode"""
debug = False
output = self.send_command_timing(cmd)
if 'username' in output.lower():
output += self.send_command_timing(default_username)
if 'password' in output.lower():
output += self.send_command_timing(self.secret)
if debug:
print(output)
self.clear_buffer()
return output
|
from __future__ import print_function
from __future__ import unicode_literals
import re
import time
from netmiko.cisco_base_connection import CiscoSSHConnection
class HPProcurveSSH(CiscoSSHConnection):
def session_preparation(self):
"""
Prepare the session after the connection has been established.
Procurve uses - 'Press any key to continue'
"""
delay_factor = self.select_delay_factor(delay_factor=0)
time.sleep(1 * delay_factor)
self.write_channel("\n")
time.sleep(1 * delay_factor)
# HP output contains VT100 escape codes
self.ansi_escape_codes = True
self.set_base_prompt()
self.disable_paging(command="\nno page\n")
self.set_terminal_width(command='terminal width 511')
def enable(self, cmd='enable', pattern='password', re_flags=re.IGNORECASE,
default_username='manager'):
"""Enter enable mode"""
debug = False
output = self.send_command_timing(cmd)
if 'username' in output.lower():
output += self.send_command_timing(default_username)
if 'password' in output.lower():
output += self.send_command_timing(self.secret)
if debug:
print(output)
self.clear_buffer()
return output
Fix issue with HP ProCurve stacks and multiple hit enter to continue messagesfrom __future__ import print_function
from __future__ import unicode_literals
import re
import time
from netmiko.cisco_base_connection import CiscoSSHConnection
class HPProcurveSSH(CiscoSSHConnection):
def session_preparation(self):
"""
Prepare the session after the connection has been established.
Procurve uses - 'Press any key to continue'
"""
delay_factor = self.select_delay_factor(delay_factor=0)
time.sleep(1 * delay_factor)
self.write_channel("\n")
time.sleep(1 * delay_factor)
self.write_channel("\n")
time.sleep(1 * delay_factor)
# HP output contains VT100 escape codes
self.ansi_escape_codes = True
self.set_base_prompt()
self.disable_paging(command="\nno page\n")
self.set_terminal_width(command='terminal width 511')
def enable(self, cmd='enable', pattern='password', re_flags=re.IGNORECASE,
default_username='manager'):
"""Enter enable mode"""
debug = False
output = self.send_command_timing(cmd)
if 'username' in output.lower():
output += self.send_command_timing(default_username)
if 'password' in output.lower():
output += self.send_command_timing(self.secret)
if debug:
print(output)
self.clear_buffer()
return output
|
<commit_before>from __future__ import print_function
from __future__ import unicode_literals
import re
import time
from netmiko.cisco_base_connection import CiscoSSHConnection
class HPProcurveSSH(CiscoSSHConnection):
def session_preparation(self):
"""
Prepare the session after the connection has been established.
Procurve uses - 'Press any key to continue'
"""
delay_factor = self.select_delay_factor(delay_factor=0)
time.sleep(1 * delay_factor)
self.write_channel("\n")
time.sleep(1 * delay_factor)
# HP output contains VT100 escape codes
self.ansi_escape_codes = True
self.set_base_prompt()
self.disable_paging(command="\nno page\n")
self.set_terminal_width(command='terminal width 511')
def enable(self, cmd='enable', pattern='password', re_flags=re.IGNORECASE,
default_username='manager'):
"""Enter enable mode"""
debug = False
output = self.send_command_timing(cmd)
if 'username' in output.lower():
output += self.send_command_timing(default_username)
if 'password' in output.lower():
output += self.send_command_timing(self.secret)
if debug:
print(output)
self.clear_buffer()
return output
<commit_msg>Fix issue with HP ProCurve stacks and multiple hit enter to continue messages<commit_after>from __future__ import print_function
from __future__ import unicode_literals
import re
import time
from netmiko.cisco_base_connection import CiscoSSHConnection
class HPProcurveSSH(CiscoSSHConnection):
def session_preparation(self):
"""
Prepare the session after the connection has been established.
Procurve uses - 'Press any key to continue'
"""
delay_factor = self.select_delay_factor(delay_factor=0)
time.sleep(1 * delay_factor)
self.write_channel("\n")
time.sleep(1 * delay_factor)
self.write_channel("\n")
time.sleep(1 * delay_factor)
# HP output contains VT100 escape codes
self.ansi_escape_codes = True
self.set_base_prompt()
self.disable_paging(command="\nno page\n")
self.set_terminal_width(command='terminal width 511')
def enable(self, cmd='enable', pattern='password', re_flags=re.IGNORECASE,
default_username='manager'):
"""Enter enable mode"""
debug = False
output = self.send_command_timing(cmd)
if 'username' in output.lower():
output += self.send_command_timing(default_username)
if 'password' in output.lower():
output += self.send_command_timing(self.secret)
if debug:
print(output)
self.clear_buffer()
return output
|
b301d8b9860f93a2c1fecd552f8edda4c813c04a
|
controller.py
|
controller.py
|
import requests
payload = {'session':{'email':'david.armbrust@gmail.com','password':'Ovation1'}}
r = requests.post('http://localhost:3000/login', json=payload)
print r.status_code
|
import requests
payload = {'session':{'email':'david.armbrust@gmail.com','password':'Ovation1'}}
session = requests.Session()
r = session.post('http://localhost:3000/login', json=payload)
print r.status_code
payload = {'plant':{'name':'Test Name','species':'Test species','days_per_watering':'9','start_date':'9/9/1999'}}
r = session.post('http://localhost:3000/plants', json=payload)
print r.status_code
|
Add persistance of session across requests
|
Add persistance of session across requests
|
Python
|
mit
|
darmbrus/plant-watering-tracker,darmbrus/plant-watering-tracker,darmbrus/plant-watering-tracker,darmbrus/plant-watering-tracker,darmbrus/plant-watering-tracker
|
import requests
payload = {'session':{'email':'david.armbrust@gmail.com','password':'Ovation1'}}
r = requests.post('http://localhost:3000/login', json=payload)
print r.status_code
Add persistance of session across requests
|
import requests
payload = {'session':{'email':'david.armbrust@gmail.com','password':'Ovation1'}}
session = requests.Session()
r = session.post('http://localhost:3000/login', json=payload)
print r.status_code
payload = {'plant':{'name':'Test Name','species':'Test species','days_per_watering':'9','start_date':'9/9/1999'}}
r = session.post('http://localhost:3000/plants', json=payload)
print r.status_code
|
<commit_before>import requests
payload = {'session':{'email':'david.armbrust@gmail.com','password':'Ovation1'}}
r = requests.post('http://localhost:3000/login', json=payload)
print r.status_code
<commit_msg>Add persistance of session across requests<commit_after>
|
import requests
payload = {'session':{'email':'david.armbrust@gmail.com','password':'Ovation1'}}
session = requests.Session()
r = session.post('http://localhost:3000/login', json=payload)
print r.status_code
payload = {'plant':{'name':'Test Name','species':'Test species','days_per_watering':'9','start_date':'9/9/1999'}}
r = session.post('http://localhost:3000/plants', json=payload)
print r.status_code
|
import requests
payload = {'session':{'email':'david.armbrust@gmail.com','password':'Ovation1'}}
r = requests.post('http://localhost:3000/login', json=payload)
print r.status_code
Add persistance of session across requestsimport requests
payload = {'session':{'email':'david.armbrust@gmail.com','password':'Ovation1'}}
session = requests.Session()
r = session.post('http://localhost:3000/login', json=payload)
print r.status_code
payload = {'plant':{'name':'Test Name','species':'Test species','days_per_watering':'9','start_date':'9/9/1999'}}
r = session.post('http://localhost:3000/plants', json=payload)
print r.status_code
|
<commit_before>import requests
payload = {'session':{'email':'david.armbrust@gmail.com','password':'Ovation1'}}
r = requests.post('http://localhost:3000/login', json=payload)
print r.status_code
<commit_msg>Add persistance of session across requests<commit_after>import requests
payload = {'session':{'email':'david.armbrust@gmail.com','password':'Ovation1'}}
session = requests.Session()
r = session.post('http://localhost:3000/login', json=payload)
print r.status_code
payload = {'plant':{'name':'Test Name','species':'Test species','days_per_watering':'9','start_date':'9/9/1999'}}
r = session.post('http://localhost:3000/plants', json=payload)
print r.status_code
|
701a18199fd230f70793b2e2c23b84506b50014e
|
reports/urls.py
|
reports/urls.py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^reports/changes/lifetimes/(?P<slug>[^/.]+)/$',
views.DiaperChangeLifetimesChildReport.as_view(),
name='report-diaperchange-lifetimes-child'),
url(r'^reports/changes/types/(?P<slug>[^/.]+)/$',
views.DiaperChangeTypesChildReport.as_view(),
name='report-diaperchange-types-child'),
url(r'^reports/sleep/pattern/(?P<slug>[^/.]+)$',
views.SleepPatternChildReport.as_view(),
name='report-sleep-pattern-child'),
url(r'^reports/sleep/totals/(?P<slug>[^/.]+)$',
views.SleepTotalsChildReport.as_view(),
name='report-sleep-totals-child'),
url(r'^reports/timeline/(?P<slug>[^/.]+)$',
views.TimelineChildReport.as_view(),
name='report-timeline-child'),
]
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^children/(?P<slug>[^/.]+)/reports/changes/lifetimes/$',
views.DiaperChangeLifetimesChildReport.as_view(),
name='report-diaperchange-lifetimes-child'),
url(r'^children/(?P<slug>[^/.]+)/reports/changes/types/$',
views.DiaperChangeTypesChildReport.as_view(),
name='report-diaperchange-types-child'),
url(r'^children/(?P<slug>[^/.]+)/reports/sleep/pattern/$',
views.SleepPatternChildReport.as_view(),
name='report-sleep-pattern-child'),
url(r'^children/(?P<slug>[^/.]+)/reports/sleep/totals/$',
views.SleepTotalsChildReport.as_view(),
name='report-sleep-totals-child'),
url(r'^children/(?P<slug>[^/.]+)/reports/timeline/$',
views.TimelineChildReport.as_view(),
name='report-timeline-child'),
]
|
Change reports URLs to extend from /children/<slug>.
|
Change reports URLs to extend from /children/<slug>.
|
Python
|
bsd-2-clause
|
cdubz/babybuddy,cdubz/babybuddy,cdubz/babybuddy
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^reports/changes/lifetimes/(?P<slug>[^/.]+)/$',
views.DiaperChangeLifetimesChildReport.as_view(),
name='report-diaperchange-lifetimes-child'),
url(r'^reports/changes/types/(?P<slug>[^/.]+)/$',
views.DiaperChangeTypesChildReport.as_view(),
name='report-diaperchange-types-child'),
url(r'^reports/sleep/pattern/(?P<slug>[^/.]+)$',
views.SleepPatternChildReport.as_view(),
name='report-sleep-pattern-child'),
url(r'^reports/sleep/totals/(?P<slug>[^/.]+)$',
views.SleepTotalsChildReport.as_view(),
name='report-sleep-totals-child'),
url(r'^reports/timeline/(?P<slug>[^/.]+)$',
views.TimelineChildReport.as_view(),
name='report-timeline-child'),
]
Change reports URLs to extend from /children/<slug>.
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^children/(?P<slug>[^/.]+)/reports/changes/lifetimes/$',
views.DiaperChangeLifetimesChildReport.as_view(),
name='report-diaperchange-lifetimes-child'),
url(r'^children/(?P<slug>[^/.]+)/reports/changes/types/$',
views.DiaperChangeTypesChildReport.as_view(),
name='report-diaperchange-types-child'),
url(r'^children/(?P<slug>[^/.]+)/reports/sleep/pattern/$',
views.SleepPatternChildReport.as_view(),
name='report-sleep-pattern-child'),
url(r'^children/(?P<slug>[^/.]+)/reports/sleep/totals/$',
views.SleepTotalsChildReport.as_view(),
name='report-sleep-totals-child'),
url(r'^children/(?P<slug>[^/.]+)/reports/timeline/$',
views.TimelineChildReport.as_view(),
name='report-timeline-child'),
]
|
<commit_before># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^reports/changes/lifetimes/(?P<slug>[^/.]+)/$',
views.DiaperChangeLifetimesChildReport.as_view(),
name='report-diaperchange-lifetimes-child'),
url(r'^reports/changes/types/(?P<slug>[^/.]+)/$',
views.DiaperChangeTypesChildReport.as_view(),
name='report-diaperchange-types-child'),
url(r'^reports/sleep/pattern/(?P<slug>[^/.]+)$',
views.SleepPatternChildReport.as_view(),
name='report-sleep-pattern-child'),
url(r'^reports/sleep/totals/(?P<slug>[^/.]+)$',
views.SleepTotalsChildReport.as_view(),
name='report-sleep-totals-child'),
url(r'^reports/timeline/(?P<slug>[^/.]+)$',
views.TimelineChildReport.as_view(),
name='report-timeline-child'),
]
<commit_msg>Change reports URLs to extend from /children/<slug>.<commit_after>
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^children/(?P<slug>[^/.]+)/reports/changes/lifetimes/$',
views.DiaperChangeLifetimesChildReport.as_view(),
name='report-diaperchange-lifetimes-child'),
url(r'^children/(?P<slug>[^/.]+)/reports/changes/types/$',
views.DiaperChangeTypesChildReport.as_view(),
name='report-diaperchange-types-child'),
url(r'^children/(?P<slug>[^/.]+)/reports/sleep/pattern/$',
views.SleepPatternChildReport.as_view(),
name='report-sleep-pattern-child'),
url(r'^children/(?P<slug>[^/.]+)/reports/sleep/totals/$',
views.SleepTotalsChildReport.as_view(),
name='report-sleep-totals-child'),
url(r'^children/(?P<slug>[^/.]+)/reports/timeline/$',
views.TimelineChildReport.as_view(),
name='report-timeline-child'),
]
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^reports/changes/lifetimes/(?P<slug>[^/.]+)/$',
views.DiaperChangeLifetimesChildReport.as_view(),
name='report-diaperchange-lifetimes-child'),
url(r'^reports/changes/types/(?P<slug>[^/.]+)/$',
views.DiaperChangeTypesChildReport.as_view(),
name='report-diaperchange-types-child'),
url(r'^reports/sleep/pattern/(?P<slug>[^/.]+)$',
views.SleepPatternChildReport.as_view(),
name='report-sleep-pattern-child'),
url(r'^reports/sleep/totals/(?P<slug>[^/.]+)$',
views.SleepTotalsChildReport.as_view(),
name='report-sleep-totals-child'),
url(r'^reports/timeline/(?P<slug>[^/.]+)$',
views.TimelineChildReport.as_view(),
name='report-timeline-child'),
]
Change reports URLs to extend from /children/<slug>.# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^children/(?P<slug>[^/.]+)/reports/changes/lifetimes/$',
views.DiaperChangeLifetimesChildReport.as_view(),
name='report-diaperchange-lifetimes-child'),
url(r'^children/(?P<slug>[^/.]+)/reports/changes/types/$',
views.DiaperChangeTypesChildReport.as_view(),
name='report-diaperchange-types-child'),
url(r'^children/(?P<slug>[^/.]+)/reports/sleep/pattern/$',
views.SleepPatternChildReport.as_view(),
name='report-sleep-pattern-child'),
url(r'^children/(?P<slug>[^/.]+)/reports/sleep/totals/$',
views.SleepTotalsChildReport.as_view(),
name='report-sleep-totals-child'),
url(r'^children/(?P<slug>[^/.]+)/reports/timeline/$',
views.TimelineChildReport.as_view(),
name='report-timeline-child'),
]
|
<commit_before># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^reports/changes/lifetimes/(?P<slug>[^/.]+)/$',
views.DiaperChangeLifetimesChildReport.as_view(),
name='report-diaperchange-lifetimes-child'),
url(r'^reports/changes/types/(?P<slug>[^/.]+)/$',
views.DiaperChangeTypesChildReport.as_view(),
name='report-diaperchange-types-child'),
url(r'^reports/sleep/pattern/(?P<slug>[^/.]+)$',
views.SleepPatternChildReport.as_view(),
name='report-sleep-pattern-child'),
url(r'^reports/sleep/totals/(?P<slug>[^/.]+)$',
views.SleepTotalsChildReport.as_view(),
name='report-sleep-totals-child'),
url(r'^reports/timeline/(?P<slug>[^/.]+)$',
views.TimelineChildReport.as_view(),
name='report-timeline-child'),
]
<commit_msg>Change reports URLs to extend from /children/<slug>.<commit_after># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^children/(?P<slug>[^/.]+)/reports/changes/lifetimes/$',
views.DiaperChangeLifetimesChildReport.as_view(),
name='report-diaperchange-lifetimes-child'),
url(r'^children/(?P<slug>[^/.]+)/reports/changes/types/$',
views.DiaperChangeTypesChildReport.as_view(),
name='report-diaperchange-types-child'),
url(r'^children/(?P<slug>[^/.]+)/reports/sleep/pattern/$',
views.SleepPatternChildReport.as_view(),
name='report-sleep-pattern-child'),
url(r'^children/(?P<slug>[^/.]+)/reports/sleep/totals/$',
views.SleepTotalsChildReport.as_view(),
name='report-sleep-totals-child'),
url(r'^children/(?P<slug>[^/.]+)/reports/timeline/$',
views.TimelineChildReport.as_view(),
name='report-timeline-child'),
]
|
96a313eef46c31af3308805f10ffa63e330cc817
|
02/test_move.py
|
02/test_move.py
|
from move import load_moves, encode_moves, normalize_index, move
import unittest
class TestMove(unittest.TestCase):
def setUp(self):
self.moves = ['ULL', 'RRDDD', 'LURDL', 'UUUUD']
def test_load_moves(self):
assert load_moves('example.txt') == self.moves
def test_encode_moves(self):
assert encode_moves(self.moves) == '1985'
def test_normalize_index(self):
assert normalize_index(3) == 2
assert normalize_index(2) == 2
assert normalize_index(1) == 1
assert normalize_index(0) == 0
assert normalize_index(-1) == 0
assert normalize_index(2, 1) == 0
assert normalize_index(5, 2) == 1
assert normalize_index(-1, 4) == 0
def test_move(self):
assert move(5, 'U') == 2
assert move(8, 'D') == 8
assert move(7, 'L') == 7
assert move(7, 'D') == 7
assert move(2, 'R') == 3
assert move(1, 'L') == 1
def test_alternate_move(self):
assert alternate_move(5, 'U') == 5
assert alternate_move(5, 'L') == 5
assert alternate_move(7, 'D') == 'B'
assert alternate_move('D', 'D') == 'D'
|
from move import load_moves, encode_moves, normalize_index, move
import unittest
class TestMove(unittest.TestCase):
def setUp(self):
self.moves = ['ULL', 'RRDDD', 'LURDL', 'UUUUD']
def test_load_moves(self):
assert load_moves('example.txt') == self.moves
def test_encode_moves(self):
assert encode_moves(self.moves) == '1985'
def test_normalize_index(self):
assert normalize_index(3) == 2
assert normalize_index(2) == 2
assert normalize_index(1) == 1
assert normalize_index(0) == 0
assert normalize_index(-1) == 0
def test_move(self):
assert move(5, 'U') == 2
assert move(8, 'D') == 8
assert move(7, 'L') == 7
assert move(7, 'D') == 7
assert move(2, 'R') == 3
assert move(1, 'L') == 1
def test_alternate_move(self):
assert alternate_move(5, 'U') == 5
assert alternate_move(5, 'L') == 5
assert alternate_move(7, 'D') == 'B'
assert alternate_move('D', 'D') == 'D'
|
Remove test of two-argument normalize function.
|
Remove test of two-argument normalize function.
|
Python
|
mit
|
machinelearningdeveloper/aoc_2016
|
from move import load_moves, encode_moves, normalize_index, move
import unittest
class TestMove(unittest.TestCase):
def setUp(self):
self.moves = ['ULL', 'RRDDD', 'LURDL', 'UUUUD']
def test_load_moves(self):
assert load_moves('example.txt') == self.moves
def test_encode_moves(self):
assert encode_moves(self.moves) == '1985'
def test_normalize_index(self):
assert normalize_index(3) == 2
assert normalize_index(2) == 2
assert normalize_index(1) == 1
assert normalize_index(0) == 0
assert normalize_index(-1) == 0
assert normalize_index(2, 1) == 0
assert normalize_index(5, 2) == 1
assert normalize_index(-1, 4) == 0
def test_move(self):
assert move(5, 'U') == 2
assert move(8, 'D') == 8
assert move(7, 'L') == 7
assert move(7, 'D') == 7
assert move(2, 'R') == 3
assert move(1, 'L') == 1
def test_alternate_move(self):
assert alternate_move(5, 'U') == 5
assert alternate_move(5, 'L') == 5
assert alternate_move(7, 'D') == 'B'
assert alternate_move('D', 'D') == 'D'
Remove test of two-argument normalize function.
|
from move import load_moves, encode_moves, normalize_index, move
import unittest
class TestMove(unittest.TestCase):
def setUp(self):
self.moves = ['ULL', 'RRDDD', 'LURDL', 'UUUUD']
def test_load_moves(self):
assert load_moves('example.txt') == self.moves
def test_encode_moves(self):
assert encode_moves(self.moves) == '1985'
def test_normalize_index(self):
assert normalize_index(3) == 2
assert normalize_index(2) == 2
assert normalize_index(1) == 1
assert normalize_index(0) == 0
assert normalize_index(-1) == 0
def test_move(self):
assert move(5, 'U') == 2
assert move(8, 'D') == 8
assert move(7, 'L') == 7
assert move(7, 'D') == 7
assert move(2, 'R') == 3
assert move(1, 'L') == 1
def test_alternate_move(self):
assert alternate_move(5, 'U') == 5
assert alternate_move(5, 'L') == 5
assert alternate_move(7, 'D') == 'B'
assert alternate_move('D', 'D') == 'D'
|
<commit_before>from move import load_moves, encode_moves, normalize_index, move
import unittest
class TestMove(unittest.TestCase):
def setUp(self):
self.moves = ['ULL', 'RRDDD', 'LURDL', 'UUUUD']
def test_load_moves(self):
assert load_moves('example.txt') == self.moves
def test_encode_moves(self):
assert encode_moves(self.moves) == '1985'
def test_normalize_index(self):
assert normalize_index(3) == 2
assert normalize_index(2) == 2
assert normalize_index(1) == 1
assert normalize_index(0) == 0
assert normalize_index(-1) == 0
assert normalize_index(2, 1) == 0
assert normalize_index(5, 2) == 1
assert normalize_index(-1, 4) == 0
def test_move(self):
assert move(5, 'U') == 2
assert move(8, 'D') == 8
assert move(7, 'L') == 7
assert move(7, 'D') == 7
assert move(2, 'R') == 3
assert move(1, 'L') == 1
def test_alternate_move(self):
assert alternate_move(5, 'U') == 5
assert alternate_move(5, 'L') == 5
assert alternate_move(7, 'D') == 'B'
assert alternate_move('D', 'D') == 'D'
<commit_msg>Remove test of two-argument normalize function.<commit_after>
|
from move import load_moves, encode_moves, normalize_index, move
import unittest
class TestMove(unittest.TestCase):
def setUp(self):
self.moves = ['ULL', 'RRDDD', 'LURDL', 'UUUUD']
def test_load_moves(self):
assert load_moves('example.txt') == self.moves
def test_encode_moves(self):
assert encode_moves(self.moves) == '1985'
def test_normalize_index(self):
assert normalize_index(3) == 2
assert normalize_index(2) == 2
assert normalize_index(1) == 1
assert normalize_index(0) == 0
assert normalize_index(-1) == 0
def test_move(self):
assert move(5, 'U') == 2
assert move(8, 'D') == 8
assert move(7, 'L') == 7
assert move(7, 'D') == 7
assert move(2, 'R') == 3
assert move(1, 'L') == 1
def test_alternate_move(self):
assert alternate_move(5, 'U') == 5
assert alternate_move(5, 'L') == 5
assert alternate_move(7, 'D') == 'B'
assert alternate_move('D', 'D') == 'D'
|
from move import load_moves, encode_moves, normalize_index, move
import unittest
class TestMove(unittest.TestCase):
def setUp(self):
self.moves = ['ULL', 'RRDDD', 'LURDL', 'UUUUD']
def test_load_moves(self):
assert load_moves('example.txt') == self.moves
def test_encode_moves(self):
assert encode_moves(self.moves) == '1985'
def test_normalize_index(self):
assert normalize_index(3) == 2
assert normalize_index(2) == 2
assert normalize_index(1) == 1
assert normalize_index(0) == 0
assert normalize_index(-1) == 0
assert normalize_index(2, 1) == 0
assert normalize_index(5, 2) == 1
assert normalize_index(-1, 4) == 0
def test_move(self):
assert move(5, 'U') == 2
assert move(8, 'D') == 8
assert move(7, 'L') == 7
assert move(7, 'D') == 7
assert move(2, 'R') == 3
assert move(1, 'L') == 1
def test_alternate_move(self):
assert alternate_move(5, 'U') == 5
assert alternate_move(5, 'L') == 5
assert alternate_move(7, 'D') == 'B'
assert alternate_move('D', 'D') == 'D'
Remove test of two-argument normalize function.from move import load_moves, encode_moves, normalize_index, move
import unittest
class TestMove(unittest.TestCase):
def setUp(self):
self.moves = ['ULL', 'RRDDD', 'LURDL', 'UUUUD']
def test_load_moves(self):
assert load_moves('example.txt') == self.moves
def test_encode_moves(self):
assert encode_moves(self.moves) == '1985'
def test_normalize_index(self):
assert normalize_index(3) == 2
assert normalize_index(2) == 2
assert normalize_index(1) == 1
assert normalize_index(0) == 0
assert normalize_index(-1) == 0
def test_move(self):
assert move(5, 'U') == 2
assert move(8, 'D') == 8
assert move(7, 'L') == 7
assert move(7, 'D') == 7
assert move(2, 'R') == 3
assert move(1, 'L') == 1
def test_alternate_move(self):
assert alternate_move(5, 'U') == 5
assert alternate_move(5, 'L') == 5
assert alternate_move(7, 'D') == 'B'
assert alternate_move('D', 'D') == 'D'
|
<commit_before>from move import load_moves, encode_moves, normalize_index, move
import unittest
class TestMove(unittest.TestCase):
def setUp(self):
self.moves = ['ULL', 'RRDDD', 'LURDL', 'UUUUD']
def test_load_moves(self):
assert load_moves('example.txt') == self.moves
def test_encode_moves(self):
assert encode_moves(self.moves) == '1985'
def test_normalize_index(self):
assert normalize_index(3) == 2
assert normalize_index(2) == 2
assert normalize_index(1) == 1
assert normalize_index(0) == 0
assert normalize_index(-1) == 0
assert normalize_index(2, 1) == 0
assert normalize_index(5, 2) == 1
assert normalize_index(-1, 4) == 0
def test_move(self):
assert move(5, 'U') == 2
assert move(8, 'D') == 8
assert move(7, 'L') == 7
assert move(7, 'D') == 7
assert move(2, 'R') == 3
assert move(1, 'L') == 1
def test_alternate_move(self):
assert alternate_move(5, 'U') == 5
assert alternate_move(5, 'L') == 5
assert alternate_move(7, 'D') == 'B'
assert alternate_move('D', 'D') == 'D'
<commit_msg>Remove test of two-argument normalize function.<commit_after>from move import load_moves, encode_moves, normalize_index, move
import unittest
class TestMove(unittest.TestCase):
def setUp(self):
self.moves = ['ULL', 'RRDDD', 'LURDL', 'UUUUD']
def test_load_moves(self):
assert load_moves('example.txt') == self.moves
def test_encode_moves(self):
assert encode_moves(self.moves) == '1985'
def test_normalize_index(self):
assert normalize_index(3) == 2
assert normalize_index(2) == 2
assert normalize_index(1) == 1
assert normalize_index(0) == 0
assert normalize_index(-1) == 0
def test_move(self):
assert move(5, 'U') == 2
assert move(8, 'D') == 8
assert move(7, 'L') == 7
assert move(7, 'D') == 7
assert move(2, 'R') == 3
assert move(1, 'L') == 1
def test_alternate_move(self):
assert alternate_move(5, 'U') == 5
assert alternate_move(5, 'L') == 5
assert alternate_move(7, 'D') == 'B'
assert alternate_move('D', 'D') == 'D'
|
496d7fd6e9b2b581bc470b57984473b29d084e74
|
contentpages/tests.py
|
contentpages/tests.py
|
from django.test import TestCase
# Create your tests here.
|
from django.test import TestCase
from django.urls import reverse
from contentpages.views import ContentPage
class TestContentPage(TestCase):
def test_get_template(self):
# test that the template view uses the template requested
# using pliny as a view that will always be present
route = reverse('content:render', kwargs={'template': 'pliny'})
res = self.client.get(route)
self.assertTemplateUsed(res, 'contentpages/pliny.html')
|
Add coverage for content pages functionality
|
Add coverage for content pages functionality
|
Python
|
mit
|
bwhicks/PlinyProject,bwhicks/PlinyProject,bwhicks/PlinyProject,bwhicks/PlinyProject
|
from django.test import TestCase
# Create your tests here.
Add coverage for content pages functionality
|
from django.test import TestCase
from django.urls import reverse
from contentpages.views import ContentPage
class TestContentPage(TestCase):
def test_get_template(self):
# test that the template view uses the template requested
# using pliny as a view that will always be present
route = reverse('content:render', kwargs={'template': 'pliny'})
res = self.client.get(route)
self.assertTemplateUsed(res, 'contentpages/pliny.html')
|
<commit_before>from django.test import TestCase
# Create your tests here.
<commit_msg>Add coverage for content pages functionality<commit_after>
|
from django.test import TestCase
from django.urls import reverse
from contentpages.views import ContentPage
class TestContentPage(TestCase):
def test_get_template(self):
# test that the template view uses the template requested
# using pliny as a view that will always be present
route = reverse('content:render', kwargs={'template': 'pliny'})
res = self.client.get(route)
self.assertTemplateUsed(res, 'contentpages/pliny.html')
|
from django.test import TestCase
# Create your tests here.
Add coverage for content pages functionalityfrom django.test import TestCase
from django.urls import reverse
from contentpages.views import ContentPage
class TestContentPage(TestCase):
def test_get_template(self):
# test that the template view uses the template requested
# using pliny as a view that will always be present
route = reverse('content:render', kwargs={'template': 'pliny'})
res = self.client.get(route)
self.assertTemplateUsed(res, 'contentpages/pliny.html')
|
<commit_before>from django.test import TestCase
# Create your tests here.
<commit_msg>Add coverage for content pages functionality<commit_after>from django.test import TestCase
from django.urls import reverse
from contentpages.views import ContentPage
class TestContentPage(TestCase):
def test_get_template(self):
# test that the template view uses the template requested
# using pliny as a view that will always be present
route = reverse('content:render', kwargs={'template': 'pliny'})
res = self.client.get(route)
self.assertTemplateUsed(res, 'contentpages/pliny.html')
|
641d548b536c1574454d0d140263c56b7a0abae9
|
pyfr/mpiutil.py
|
pyfr/mpiutil.py
|
# -*- coding: utf-8 -*-
import os
from mpi4py import MPI
from excepthook import excepthook
def init():
MPI.Init_thread()
MPI.COMM_WORLD.barrier()
def atexit():
if not MPI.Is_initialized() or MPI.Is_finalized():
return
exc = excepthook.exception
if MPI.COMM_WORLD.size > 1 and exc is not None and\
not isinstance(exc, KeyboardInterrupt) and\
(not isinstance(exc, SystemExit) or exc.code != 0):
MPI.COMM_WORLD.Abort()
else:
MPI.Finalize()
def get_comm_rank_root():
comm = MPI.COMM_WORLD
return comm, comm.rank, 0
def get_local_rank():
envs = ['OMPI_COMM_WORLD_LOCAL_RANK', 'MV2_COMM_WORLD_LOCAL_RANK']
for ev in envs:
if ev in os.environ:
return int(os.environ[ev])
else:
raise RuntimeError('Unknown/unsupported MPI implementation')
|
# -*- coding: utf-8 -*-
import os
from mpi4py import MPI
from excepthook import excepthook
def init():
MPI.Init_thread()
MPI.COMM_WORLD.barrier()
def atexit():
if not MPI.Is_initialized() or MPI.Is_finalized():
return
exc = excepthook.exception
if MPI.COMM_WORLD.size > 1 and exc is not None and\
not isinstance(exc, KeyboardInterrupt) and\
(not isinstance(exc, SystemExit) or exc.code != 0):
MPI.COMM_WORLD.Abort(1)
else:
MPI.Finalize()
def get_comm_rank_root():
comm = MPI.COMM_WORLD
return comm, comm.rank, 0
def get_local_rank():
envs = ['OMPI_COMM_WORLD_LOCAL_RANK', 'MV2_COMM_WORLD_LOCAL_RANK']
for ev in envs:
if ev in os.environ:
return int(os.environ[ev])
else:
raise RuntimeError('Unknown/unsupported MPI implementation')
|
Improve how we abort MPI runs.
|
Improve how we abort MPI runs.
|
Python
|
bsd-3-clause
|
tjcorona/PyFR,Aerojspark/PyFR,tjcorona/PyFR,tjcorona/PyFR,BrianVermeire/PyFR,iyer-arvind/PyFR
|
# -*- coding: utf-8 -*-
import os
from mpi4py import MPI
from excepthook import excepthook
def init():
MPI.Init_thread()
MPI.COMM_WORLD.barrier()
def atexit():
if not MPI.Is_initialized() or MPI.Is_finalized():
return
exc = excepthook.exception
if MPI.COMM_WORLD.size > 1 and exc is not None and\
not isinstance(exc, KeyboardInterrupt) and\
(not isinstance(exc, SystemExit) or exc.code != 0):
MPI.COMM_WORLD.Abort()
else:
MPI.Finalize()
def get_comm_rank_root():
comm = MPI.COMM_WORLD
return comm, comm.rank, 0
def get_local_rank():
envs = ['OMPI_COMM_WORLD_LOCAL_RANK', 'MV2_COMM_WORLD_LOCAL_RANK']
for ev in envs:
if ev in os.environ:
return int(os.environ[ev])
else:
raise RuntimeError('Unknown/unsupported MPI implementation')
Improve how we abort MPI runs.
|
# -*- coding: utf-8 -*-
import os
from mpi4py import MPI
from excepthook import excepthook
def init():
MPI.Init_thread()
MPI.COMM_WORLD.barrier()
def atexit():
if not MPI.Is_initialized() or MPI.Is_finalized():
return
exc = excepthook.exception
if MPI.COMM_WORLD.size > 1 and exc is not None and\
not isinstance(exc, KeyboardInterrupt) and\
(not isinstance(exc, SystemExit) or exc.code != 0):
MPI.COMM_WORLD.Abort(1)
else:
MPI.Finalize()
def get_comm_rank_root():
comm = MPI.COMM_WORLD
return comm, comm.rank, 0
def get_local_rank():
envs = ['OMPI_COMM_WORLD_LOCAL_RANK', 'MV2_COMM_WORLD_LOCAL_RANK']
for ev in envs:
if ev in os.environ:
return int(os.environ[ev])
else:
raise RuntimeError('Unknown/unsupported MPI implementation')
|
<commit_before># -*- coding: utf-8 -*-
import os
from mpi4py import MPI
from excepthook import excepthook
def init():
MPI.Init_thread()
MPI.COMM_WORLD.barrier()
def atexit():
if not MPI.Is_initialized() or MPI.Is_finalized():
return
exc = excepthook.exception
if MPI.COMM_WORLD.size > 1 and exc is not None and\
not isinstance(exc, KeyboardInterrupt) and\
(not isinstance(exc, SystemExit) or exc.code != 0):
MPI.COMM_WORLD.Abort()
else:
MPI.Finalize()
def get_comm_rank_root():
comm = MPI.COMM_WORLD
return comm, comm.rank, 0
def get_local_rank():
envs = ['OMPI_COMM_WORLD_LOCAL_RANK', 'MV2_COMM_WORLD_LOCAL_RANK']
for ev in envs:
if ev in os.environ:
return int(os.environ[ev])
else:
raise RuntimeError('Unknown/unsupported MPI implementation')
<commit_msg>Improve how we abort MPI runs.<commit_after>
|
# -*- coding: utf-8 -*-
import os
from mpi4py import MPI
from excepthook import excepthook
def init():
MPI.Init_thread()
MPI.COMM_WORLD.barrier()
def atexit():
if not MPI.Is_initialized() or MPI.Is_finalized():
return
exc = excepthook.exception
if MPI.COMM_WORLD.size > 1 and exc is not None and\
not isinstance(exc, KeyboardInterrupt) and\
(not isinstance(exc, SystemExit) or exc.code != 0):
MPI.COMM_WORLD.Abort(1)
else:
MPI.Finalize()
def get_comm_rank_root():
comm = MPI.COMM_WORLD
return comm, comm.rank, 0
def get_local_rank():
envs = ['OMPI_COMM_WORLD_LOCAL_RANK', 'MV2_COMM_WORLD_LOCAL_RANK']
for ev in envs:
if ev in os.environ:
return int(os.environ[ev])
else:
raise RuntimeError('Unknown/unsupported MPI implementation')
|
# -*- coding: utf-8 -*-
import os
from mpi4py import MPI
from excepthook import excepthook
def init():
MPI.Init_thread()
MPI.COMM_WORLD.barrier()
def atexit():
if not MPI.Is_initialized() or MPI.Is_finalized():
return
exc = excepthook.exception
if MPI.COMM_WORLD.size > 1 and exc is not None and\
not isinstance(exc, KeyboardInterrupt) and\
(not isinstance(exc, SystemExit) or exc.code != 0):
MPI.COMM_WORLD.Abort()
else:
MPI.Finalize()
def get_comm_rank_root():
comm = MPI.COMM_WORLD
return comm, comm.rank, 0
def get_local_rank():
envs = ['OMPI_COMM_WORLD_LOCAL_RANK', 'MV2_COMM_WORLD_LOCAL_RANK']
for ev in envs:
if ev in os.environ:
return int(os.environ[ev])
else:
raise RuntimeError('Unknown/unsupported MPI implementation')
Improve how we abort MPI runs.# -*- coding: utf-8 -*-
import os
from mpi4py import MPI
from excepthook import excepthook
def init():
MPI.Init_thread()
MPI.COMM_WORLD.barrier()
def atexit():
if not MPI.Is_initialized() or MPI.Is_finalized():
return
exc = excepthook.exception
if MPI.COMM_WORLD.size > 1 and exc is not None and\
not isinstance(exc, KeyboardInterrupt) and\
(not isinstance(exc, SystemExit) or exc.code != 0):
MPI.COMM_WORLD.Abort(1)
else:
MPI.Finalize()
def get_comm_rank_root():
comm = MPI.COMM_WORLD
return comm, comm.rank, 0
def get_local_rank():
envs = ['OMPI_COMM_WORLD_LOCAL_RANK', 'MV2_COMM_WORLD_LOCAL_RANK']
for ev in envs:
if ev in os.environ:
return int(os.environ[ev])
else:
raise RuntimeError('Unknown/unsupported MPI implementation')
|
<commit_before># -*- coding: utf-8 -*-
import os
from mpi4py import MPI
from excepthook import excepthook
def init():
MPI.Init_thread()
MPI.COMM_WORLD.barrier()
def atexit():
if not MPI.Is_initialized() or MPI.Is_finalized():
return
exc = excepthook.exception
if MPI.COMM_WORLD.size > 1 and exc is not None and\
not isinstance(exc, KeyboardInterrupt) and\
(not isinstance(exc, SystemExit) or exc.code != 0):
MPI.COMM_WORLD.Abort()
else:
MPI.Finalize()
def get_comm_rank_root():
comm = MPI.COMM_WORLD
return comm, comm.rank, 0
def get_local_rank():
envs = ['OMPI_COMM_WORLD_LOCAL_RANK', 'MV2_COMM_WORLD_LOCAL_RANK']
for ev in envs:
if ev in os.environ:
return int(os.environ[ev])
else:
raise RuntimeError('Unknown/unsupported MPI implementation')
<commit_msg>Improve how we abort MPI runs.<commit_after># -*- coding: utf-8 -*-
import os
from mpi4py import MPI
from excepthook import excepthook
def init():
MPI.Init_thread()
MPI.COMM_WORLD.barrier()
def atexit():
if not MPI.Is_initialized() or MPI.Is_finalized():
return
exc = excepthook.exception
if MPI.COMM_WORLD.size > 1 and exc is not None and\
not isinstance(exc, KeyboardInterrupt) and\
(not isinstance(exc, SystemExit) or exc.code != 0):
MPI.COMM_WORLD.Abort(1)
else:
MPI.Finalize()
def get_comm_rank_root():
comm = MPI.COMM_WORLD
return comm, comm.rank, 0
def get_local_rank():
envs = ['OMPI_COMM_WORLD_LOCAL_RANK', 'MV2_COMM_WORLD_LOCAL_RANK']
for ev in envs:
if ev in os.environ:
return int(os.environ[ev])
else:
raise RuntimeError('Unknown/unsupported MPI implementation')
|
09fed8f6bfb32f0f4c3aba45d16a153eaefe79e4
|
fetch.py
|
fetch.py
|
import fetchparser
def print_parsed():
for line in fetchparser.parse_input(open("sample.fetch").read()):
print line
def print_lexed():
import fetchlexer
l=fetchlexer.get_lexer()
# Give the lexer some input
l.input(open("sample.fetch").read())
# Tokenize
while True:
tok = l.token()
if not tok: break # No more input
print tok
def interpret():
import fetchinterpreter
compiled = fetchparser.parse_input(open("sample.fetch").read())
for line in compiled:
fetchinterpreter.handle_line(line)
print "Output", fetchinterpreter.get_output()
def execute_compiled():
execfile("fetchout.py")
if __name__ == "__main__":
print "\n--Lexed--"
print_lexed()
print "\n--Parsed--"
try:
print_parsed()
except SyntaxError:
print "Terminating"
import sys
sys.exit(1)
print "\n--Interpreting--"
interpret()
|
import fetchparser
def print_parsed():
for line in fetchparser.parse_input(open("sample.fetch").read()):
print line
def print_lexed():
import fetchlexer
l=fetchlexer.get_lexer()
# Give the lexer some input
l.input(open("sample.fetch").read())
# Tokenize
while True:
tok = l.token()
if not tok: break # No more input
print tok
def interpret():
import fetchinterpreter
compiled = fetchparser.parse_input(open("sample.fetch").read())
for line in compiled:
fetchinterpreter.handle_line(line)
print "Output", fetchinterpreter.get_output()
if __name__ == "__main__":
print "\n--Lexed--"
print_lexed()
print "\n--Parsed--"
try:
print_parsed()
except SyntaxError:
print "Terminating"
import sys
sys.exit(1)
print "\n--Interpreting--"
interpret()
|
Kill dad code for old compiler
|
Kill dad code for old compiler
|
Python
|
mit
|
buffis/fetch
|
import fetchparser
def print_parsed():
for line in fetchparser.parse_input(open("sample.fetch").read()):
print line
def print_lexed():
import fetchlexer
l=fetchlexer.get_lexer()
# Give the lexer some input
l.input(open("sample.fetch").read())
# Tokenize
while True:
tok = l.token()
if not tok: break # No more input
print tok
def interpret():
import fetchinterpreter
compiled = fetchparser.parse_input(open("sample.fetch").read())
for line in compiled:
fetchinterpreter.handle_line(line)
print "Output", fetchinterpreter.get_output()
def execute_compiled():
execfile("fetchout.py")
if __name__ == "__main__":
print "\n--Lexed--"
print_lexed()
print "\n--Parsed--"
try:
print_parsed()
except SyntaxError:
print "Terminating"
import sys
sys.exit(1)
print "\n--Interpreting--"
interpret()
Kill dad code for old compiler
|
import fetchparser
def print_parsed():
for line in fetchparser.parse_input(open("sample.fetch").read()):
print line
def print_lexed():
import fetchlexer
l=fetchlexer.get_lexer()
# Give the lexer some input
l.input(open("sample.fetch").read())
# Tokenize
while True:
tok = l.token()
if not tok: break # No more input
print tok
def interpret():
import fetchinterpreter
compiled = fetchparser.parse_input(open("sample.fetch").read())
for line in compiled:
fetchinterpreter.handle_line(line)
print "Output", fetchinterpreter.get_output()
if __name__ == "__main__":
print "\n--Lexed--"
print_lexed()
print "\n--Parsed--"
try:
print_parsed()
except SyntaxError:
print "Terminating"
import sys
sys.exit(1)
print "\n--Interpreting--"
interpret()
|
<commit_before>import fetchparser
def print_parsed():
for line in fetchparser.parse_input(open("sample.fetch").read()):
print line
def print_lexed():
import fetchlexer
l=fetchlexer.get_lexer()
# Give the lexer some input
l.input(open("sample.fetch").read())
# Tokenize
while True:
tok = l.token()
if not tok: break # No more input
print tok
def interpret():
import fetchinterpreter
compiled = fetchparser.parse_input(open("sample.fetch").read())
for line in compiled:
fetchinterpreter.handle_line(line)
print "Output", fetchinterpreter.get_output()
def execute_compiled():
execfile("fetchout.py")
if __name__ == "__main__":
print "\n--Lexed--"
print_lexed()
print "\n--Parsed--"
try:
print_parsed()
except SyntaxError:
print "Terminating"
import sys
sys.exit(1)
print "\n--Interpreting--"
interpret()
<commit_msg>Kill dad code for old compiler<commit_after>
|
import fetchparser
def print_parsed():
for line in fetchparser.parse_input(open("sample.fetch").read()):
print line
def print_lexed():
import fetchlexer
l=fetchlexer.get_lexer()
# Give the lexer some input
l.input(open("sample.fetch").read())
# Tokenize
while True:
tok = l.token()
if not tok: break # No more input
print tok
def interpret():
import fetchinterpreter
compiled = fetchparser.parse_input(open("sample.fetch").read())
for line in compiled:
fetchinterpreter.handle_line(line)
print "Output", fetchinterpreter.get_output()
if __name__ == "__main__":
print "\n--Lexed--"
print_lexed()
print "\n--Parsed--"
try:
print_parsed()
except SyntaxError:
print "Terminating"
import sys
sys.exit(1)
print "\n--Interpreting--"
interpret()
|
import fetchparser
def print_parsed():
for line in fetchparser.parse_input(open("sample.fetch").read()):
print line
def print_lexed():
import fetchlexer
l=fetchlexer.get_lexer()
# Give the lexer some input
l.input(open("sample.fetch").read())
# Tokenize
while True:
tok = l.token()
if not tok: break # No more input
print tok
def interpret():
import fetchinterpreter
compiled = fetchparser.parse_input(open("sample.fetch").read())
for line in compiled:
fetchinterpreter.handle_line(line)
print "Output", fetchinterpreter.get_output()
def execute_compiled():
execfile("fetchout.py")
if __name__ == "__main__":
print "\n--Lexed--"
print_lexed()
print "\n--Parsed--"
try:
print_parsed()
except SyntaxError:
print "Terminating"
import sys
sys.exit(1)
print "\n--Interpreting--"
interpret()
Kill dad code for old compilerimport fetchparser
def print_parsed():
for line in fetchparser.parse_input(open("sample.fetch").read()):
print line
def print_lexed():
import fetchlexer
l=fetchlexer.get_lexer()
# Give the lexer some input
l.input(open("sample.fetch").read())
# Tokenize
while True:
tok = l.token()
if not tok: break # No more input
print tok
def interpret():
import fetchinterpreter
compiled = fetchparser.parse_input(open("sample.fetch").read())
for line in compiled:
fetchinterpreter.handle_line(line)
print "Output", fetchinterpreter.get_output()
if __name__ == "__main__":
print "\n--Lexed--"
print_lexed()
print "\n--Parsed--"
try:
print_parsed()
except SyntaxError:
print "Terminating"
import sys
sys.exit(1)
print "\n--Interpreting--"
interpret()
|
<commit_before>import fetchparser
def print_parsed():
for line in fetchparser.parse_input(open("sample.fetch").read()):
print line
def print_lexed():
import fetchlexer
l=fetchlexer.get_lexer()
# Give the lexer some input
l.input(open("sample.fetch").read())
# Tokenize
while True:
tok = l.token()
if not tok: break # No more input
print tok
def interpret():
import fetchinterpreter
compiled = fetchparser.parse_input(open("sample.fetch").read())
for line in compiled:
fetchinterpreter.handle_line(line)
print "Output", fetchinterpreter.get_output()
def execute_compiled():
execfile("fetchout.py")
if __name__ == "__main__":
print "\n--Lexed--"
print_lexed()
print "\n--Parsed--"
try:
print_parsed()
except SyntaxError:
print "Terminating"
import sys
sys.exit(1)
print "\n--Interpreting--"
interpret()
<commit_msg>Kill dad code for old compiler<commit_after>import fetchparser
def print_parsed():
for line in fetchparser.parse_input(open("sample.fetch").read()):
print line
def print_lexed():
import fetchlexer
l=fetchlexer.get_lexer()
# Give the lexer some input
l.input(open("sample.fetch").read())
# Tokenize
while True:
tok = l.token()
if not tok: break # No more input
print tok
def interpret():
import fetchinterpreter
compiled = fetchparser.parse_input(open("sample.fetch").read())
for line in compiled:
fetchinterpreter.handle_line(line)
print "Output", fetchinterpreter.get_output()
if __name__ == "__main__":
print "\n--Lexed--"
print_lexed()
print "\n--Parsed--"
try:
print_parsed()
except SyntaxError:
print "Terminating"
import sys
sys.exit(1)
print "\n--Interpreting--"
interpret()
|
a5fdffe2f37e2e1c34044c259ef56c0e5feca0cb
|
allegedb/allegedb/tests/test_branch_plan.py
|
allegedb/allegedb/tests/test_branch_plan.py
|
import pytest
import allegedb
@pytest.fixture(scope='function')
def orm():
with allegedb.ORM("sqlite:///:memory:") as it:
yield it
def test_single_plan(orm):
g = orm.new_graph('graph')
g.add_node(0)
orm.turn = 1
g.add_node(1)
with orm.plan():
orm.turn = 2
g.add_node(2)
assert orm.turn == 1
assert 2 not in g
orm.branch = 'b'
assert 2 not in g
assert 1 in g
orm.turn = 2
assert 2 in g
orm.turn = 1
orm.branch = 'trunk'
orm.turn = 0
assert 1 not in g
orm.branch = 'c'
orm.turn = 2
assert 1 not in g
assert 2 not in g
|
import pytest
import allegedb
@pytest.fixture(scope='function')
def orm():
with allegedb.ORM("sqlite:///:memory:") as it:
yield it
def test_single_plan(orm):
g = orm.new_graph('graph')
g.add_node(0)
orm.turn = 1
g.add_node(1)
with orm.plan():
orm.turn = 2
g.add_node(2)
assert orm.turn == 1
assert 2 not in g
orm.branch = 'b'
assert 2 not in g
assert 1 in g
orm.turn = 2
assert 2 in g
orm.turn = 1
orm.branch = 'trunk'
orm.turn = 0
assert 1 not in g
orm.branch = 'c'
orm.turn = 2
assert 1 not in g
assert 2 not in g
orm.turn = 0
orm.branch = 'trunk'
orm.turn = 2
assert 2 in g
|
Add an extra check in that test
|
Add an extra check in that test
|
Python
|
agpl-3.0
|
LogicalDash/LiSE,LogicalDash/LiSE
|
import pytest
import allegedb
@pytest.fixture(scope='function')
def orm():
with allegedb.ORM("sqlite:///:memory:") as it:
yield it
def test_single_plan(orm):
g = orm.new_graph('graph')
g.add_node(0)
orm.turn = 1
g.add_node(1)
with orm.plan():
orm.turn = 2
g.add_node(2)
assert orm.turn == 1
assert 2 not in g
orm.branch = 'b'
assert 2 not in g
assert 1 in g
orm.turn = 2
assert 2 in g
orm.turn = 1
orm.branch = 'trunk'
orm.turn = 0
assert 1 not in g
orm.branch = 'c'
orm.turn = 2
assert 1 not in g
assert 2 not in gAdd an extra check in that test
|
import pytest
import allegedb
@pytest.fixture(scope='function')
def orm():
with allegedb.ORM("sqlite:///:memory:") as it:
yield it
def test_single_plan(orm):
g = orm.new_graph('graph')
g.add_node(0)
orm.turn = 1
g.add_node(1)
with orm.plan():
orm.turn = 2
g.add_node(2)
assert orm.turn == 1
assert 2 not in g
orm.branch = 'b'
assert 2 not in g
assert 1 in g
orm.turn = 2
assert 2 in g
orm.turn = 1
orm.branch = 'trunk'
orm.turn = 0
assert 1 not in g
orm.branch = 'c'
orm.turn = 2
assert 1 not in g
assert 2 not in g
orm.turn = 0
orm.branch = 'trunk'
orm.turn = 2
assert 2 in g
|
<commit_before>import pytest
import allegedb
@pytest.fixture(scope='function')
def orm():
with allegedb.ORM("sqlite:///:memory:") as it:
yield it
def test_single_plan(orm):
g = orm.new_graph('graph')
g.add_node(0)
orm.turn = 1
g.add_node(1)
with orm.plan():
orm.turn = 2
g.add_node(2)
assert orm.turn == 1
assert 2 not in g
orm.branch = 'b'
assert 2 not in g
assert 1 in g
orm.turn = 2
assert 2 in g
orm.turn = 1
orm.branch = 'trunk'
orm.turn = 0
assert 1 not in g
orm.branch = 'c'
orm.turn = 2
assert 1 not in g
assert 2 not in g<commit_msg>Add an extra check in that test<commit_after>
|
import pytest
import allegedb
@pytest.fixture(scope='function')
def orm():
with allegedb.ORM("sqlite:///:memory:") as it:
yield it
def test_single_plan(orm):
g = orm.new_graph('graph')
g.add_node(0)
orm.turn = 1
g.add_node(1)
with orm.plan():
orm.turn = 2
g.add_node(2)
assert orm.turn == 1
assert 2 not in g
orm.branch = 'b'
assert 2 not in g
assert 1 in g
orm.turn = 2
assert 2 in g
orm.turn = 1
orm.branch = 'trunk'
orm.turn = 0
assert 1 not in g
orm.branch = 'c'
orm.turn = 2
assert 1 not in g
assert 2 not in g
orm.turn = 0
orm.branch = 'trunk'
orm.turn = 2
assert 2 in g
|
import pytest
import allegedb
@pytest.fixture(scope='function')
def orm():
with allegedb.ORM("sqlite:///:memory:") as it:
yield it
def test_single_plan(orm):
g = orm.new_graph('graph')
g.add_node(0)
orm.turn = 1
g.add_node(1)
with orm.plan():
orm.turn = 2
g.add_node(2)
assert orm.turn == 1
assert 2 not in g
orm.branch = 'b'
assert 2 not in g
assert 1 in g
orm.turn = 2
assert 2 in g
orm.turn = 1
orm.branch = 'trunk'
orm.turn = 0
assert 1 not in g
orm.branch = 'c'
orm.turn = 2
assert 1 not in g
assert 2 not in gAdd an extra check in that testimport pytest
import allegedb
@pytest.fixture(scope='function')
def orm():
with allegedb.ORM("sqlite:///:memory:") as it:
yield it
def test_single_plan(orm):
g = orm.new_graph('graph')
g.add_node(0)
orm.turn = 1
g.add_node(1)
with orm.plan():
orm.turn = 2
g.add_node(2)
assert orm.turn == 1
assert 2 not in g
orm.branch = 'b'
assert 2 not in g
assert 1 in g
orm.turn = 2
assert 2 in g
orm.turn = 1
orm.branch = 'trunk'
orm.turn = 0
assert 1 not in g
orm.branch = 'c'
orm.turn = 2
assert 1 not in g
assert 2 not in g
orm.turn = 0
orm.branch = 'trunk'
orm.turn = 2
assert 2 in g
|
<commit_before>import pytest
import allegedb
@pytest.fixture(scope='function')
def orm():
with allegedb.ORM("sqlite:///:memory:") as it:
yield it
def test_single_plan(orm):
g = orm.new_graph('graph')
g.add_node(0)
orm.turn = 1
g.add_node(1)
with orm.plan():
orm.turn = 2
g.add_node(2)
assert orm.turn == 1
assert 2 not in g
orm.branch = 'b'
assert 2 not in g
assert 1 in g
orm.turn = 2
assert 2 in g
orm.turn = 1
orm.branch = 'trunk'
orm.turn = 0
assert 1 not in g
orm.branch = 'c'
orm.turn = 2
assert 1 not in g
assert 2 not in g<commit_msg>Add an extra check in that test<commit_after>import pytest
import allegedb
@pytest.fixture(scope='function')
def orm():
with allegedb.ORM("sqlite:///:memory:") as it:
yield it
def test_single_plan(orm):
g = orm.new_graph('graph')
g.add_node(0)
orm.turn = 1
g.add_node(1)
with orm.plan():
orm.turn = 2
g.add_node(2)
assert orm.turn == 1
assert 2 not in g
orm.branch = 'b'
assert 2 not in g
assert 1 in g
orm.turn = 2
assert 2 in g
orm.turn = 1
orm.branch = 'trunk'
orm.turn = 0
assert 1 not in g
orm.branch = 'c'
orm.turn = 2
assert 1 not in g
assert 2 not in g
orm.turn = 0
orm.branch = 'trunk'
orm.turn = 2
assert 2 in g
|
46ebeba28f8fbb9d43457aa3fa539b29048a581b
|
netbox/users/api/views.py
|
netbox/users/api/views.py
|
from django.contrib.auth.models import Group, User
from django.db.models import Count
from users import filters
from users.models import ObjectPermission
from utilities.api import ModelViewSet
from utilities.querysets import RestrictedQuerySet
from . import serializers
#
# Users and groups
#
class UserViewSet(ModelViewSet):
queryset = RestrictedQuerySet(model=User).prefetch_related('groups')
serializer_class = serializers.UserSerializer
filterset_class = filters.UserFilterSet
class GroupViewSet(ModelViewSet):
queryset = RestrictedQuerySet(model=Group).annotate(user_count=Count('user'))
serializer_class = serializers.GroupSerializer
filterset_class = filters.GroupFilterSet
#
# ObjectPermissions
#
class ObjectPermissionViewSet(ModelViewSet):
queryset = ObjectPermission.objects.prefetch_related('object_types', 'groups', 'users')
serializer_class = serializers.ObjectPermissionSerializer
filterset_class = filters.ObjectPermissionFilterSet
|
from django.contrib.auth.models import Group, User
from django.db.models import Count
from users import filters
from users.models import ObjectPermission
from utilities.api import ModelViewSet
from utilities.querysets import RestrictedQuerySet
from . import serializers
#
# Users and groups
#
class UserViewSet(ModelViewSet):
queryset = RestrictedQuerySet(model=User).prefetch_related('groups').order_by('username')
serializer_class = serializers.UserSerializer
filterset_class = filters.UserFilterSet
class GroupViewSet(ModelViewSet):
queryset = RestrictedQuerySet(model=Group).annotate(user_count=Count('user')).order_by('name')
serializer_class = serializers.GroupSerializer
filterset_class = filters.GroupFilterSet
#
# ObjectPermissions
#
class ObjectPermissionViewSet(ModelViewSet):
queryset = ObjectPermission.objects.prefetch_related('object_types', 'groups', 'users')
serializer_class = serializers.ObjectPermissionSerializer
filterset_class = filters.ObjectPermissionFilterSet
|
Set default ordering for user and group API endpoints
|
Set default ordering for user and group API endpoints
|
Python
|
apache-2.0
|
digitalocean/netbox,digitalocean/netbox,digitalocean/netbox,digitalocean/netbox
|
from django.contrib.auth.models import Group, User
from django.db.models import Count
from users import filters
from users.models import ObjectPermission
from utilities.api import ModelViewSet
from utilities.querysets import RestrictedQuerySet
from . import serializers
#
# Users and groups
#
class UserViewSet(ModelViewSet):
queryset = RestrictedQuerySet(model=User).prefetch_related('groups')
serializer_class = serializers.UserSerializer
filterset_class = filters.UserFilterSet
class GroupViewSet(ModelViewSet):
queryset = RestrictedQuerySet(model=Group).annotate(user_count=Count('user'))
serializer_class = serializers.GroupSerializer
filterset_class = filters.GroupFilterSet
#
# ObjectPermissions
#
class ObjectPermissionViewSet(ModelViewSet):
queryset = ObjectPermission.objects.prefetch_related('object_types', 'groups', 'users')
serializer_class = serializers.ObjectPermissionSerializer
filterset_class = filters.ObjectPermissionFilterSet
Set default ordering for user and group API endpoints
|
from django.contrib.auth.models import Group, User
from django.db.models import Count
from users import filters
from users.models import ObjectPermission
from utilities.api import ModelViewSet
from utilities.querysets import RestrictedQuerySet
from . import serializers
#
# Users and groups
#
class UserViewSet(ModelViewSet):
queryset = RestrictedQuerySet(model=User).prefetch_related('groups').order_by('username')
serializer_class = serializers.UserSerializer
filterset_class = filters.UserFilterSet
class GroupViewSet(ModelViewSet):
queryset = RestrictedQuerySet(model=Group).annotate(user_count=Count('user')).order_by('name')
serializer_class = serializers.GroupSerializer
filterset_class = filters.GroupFilterSet
#
# ObjectPermissions
#
class ObjectPermissionViewSet(ModelViewSet):
queryset = ObjectPermission.objects.prefetch_related('object_types', 'groups', 'users')
serializer_class = serializers.ObjectPermissionSerializer
filterset_class = filters.ObjectPermissionFilterSet
|
<commit_before>from django.contrib.auth.models import Group, User
from django.db.models import Count
from users import filters
from users.models import ObjectPermission
from utilities.api import ModelViewSet
from utilities.querysets import RestrictedQuerySet
from . import serializers
#
# Users and groups
#
class UserViewSet(ModelViewSet):
queryset = RestrictedQuerySet(model=User).prefetch_related('groups')
serializer_class = serializers.UserSerializer
filterset_class = filters.UserFilterSet
class GroupViewSet(ModelViewSet):
queryset = RestrictedQuerySet(model=Group).annotate(user_count=Count('user'))
serializer_class = serializers.GroupSerializer
filterset_class = filters.GroupFilterSet
#
# ObjectPermissions
#
class ObjectPermissionViewSet(ModelViewSet):
queryset = ObjectPermission.objects.prefetch_related('object_types', 'groups', 'users')
serializer_class = serializers.ObjectPermissionSerializer
filterset_class = filters.ObjectPermissionFilterSet
<commit_msg>Set default ordering for user and group API endpoints<commit_after>
|
from django.contrib.auth.models import Group, User
from django.db.models import Count
from users import filters
from users.models import ObjectPermission
from utilities.api import ModelViewSet
from utilities.querysets import RestrictedQuerySet
from . import serializers
#
# Users and groups
#
class UserViewSet(ModelViewSet):
queryset = RestrictedQuerySet(model=User).prefetch_related('groups').order_by('username')
serializer_class = serializers.UserSerializer
filterset_class = filters.UserFilterSet
class GroupViewSet(ModelViewSet):
queryset = RestrictedQuerySet(model=Group).annotate(user_count=Count('user')).order_by('name')
serializer_class = serializers.GroupSerializer
filterset_class = filters.GroupFilterSet
#
# ObjectPermissions
#
class ObjectPermissionViewSet(ModelViewSet):
queryset = ObjectPermission.objects.prefetch_related('object_types', 'groups', 'users')
serializer_class = serializers.ObjectPermissionSerializer
filterset_class = filters.ObjectPermissionFilterSet
|
from django.contrib.auth.models import Group, User
from django.db.models import Count
from users import filters
from users.models import ObjectPermission
from utilities.api import ModelViewSet
from utilities.querysets import RestrictedQuerySet
from . import serializers
#
# Users and groups
#
class UserViewSet(ModelViewSet):
queryset = RestrictedQuerySet(model=User).prefetch_related('groups')
serializer_class = serializers.UserSerializer
filterset_class = filters.UserFilterSet
class GroupViewSet(ModelViewSet):
queryset = RestrictedQuerySet(model=Group).annotate(user_count=Count('user'))
serializer_class = serializers.GroupSerializer
filterset_class = filters.GroupFilterSet
#
# ObjectPermissions
#
class ObjectPermissionViewSet(ModelViewSet):
queryset = ObjectPermission.objects.prefetch_related('object_types', 'groups', 'users')
serializer_class = serializers.ObjectPermissionSerializer
filterset_class = filters.ObjectPermissionFilterSet
Set default ordering for user and group API endpointsfrom django.contrib.auth.models import Group, User
from django.db.models import Count
from users import filters
from users.models import ObjectPermission
from utilities.api import ModelViewSet
from utilities.querysets import RestrictedQuerySet
from . import serializers
#
# Users and groups
#
class UserViewSet(ModelViewSet):
queryset = RestrictedQuerySet(model=User).prefetch_related('groups').order_by('username')
serializer_class = serializers.UserSerializer
filterset_class = filters.UserFilterSet
class GroupViewSet(ModelViewSet):
queryset = RestrictedQuerySet(model=Group).annotate(user_count=Count('user')).order_by('name')
serializer_class = serializers.GroupSerializer
filterset_class = filters.GroupFilterSet
#
# ObjectPermissions
#
class ObjectPermissionViewSet(ModelViewSet):
queryset = ObjectPermission.objects.prefetch_related('object_types', 'groups', 'users')
serializer_class = serializers.ObjectPermissionSerializer
filterset_class = filters.ObjectPermissionFilterSet
|
<commit_before>from django.contrib.auth.models import Group, User
from django.db.models import Count
from users import filters
from users.models import ObjectPermission
from utilities.api import ModelViewSet
from utilities.querysets import RestrictedQuerySet
from . import serializers
#
# Users and groups
#
class UserViewSet(ModelViewSet):
queryset = RestrictedQuerySet(model=User).prefetch_related('groups')
serializer_class = serializers.UserSerializer
filterset_class = filters.UserFilterSet
class GroupViewSet(ModelViewSet):
queryset = RestrictedQuerySet(model=Group).annotate(user_count=Count('user'))
serializer_class = serializers.GroupSerializer
filterset_class = filters.GroupFilterSet
#
# ObjectPermissions
#
class ObjectPermissionViewSet(ModelViewSet):
queryset = ObjectPermission.objects.prefetch_related('object_types', 'groups', 'users')
serializer_class = serializers.ObjectPermissionSerializer
filterset_class = filters.ObjectPermissionFilterSet
<commit_msg>Set default ordering for user and group API endpoints<commit_after>from django.contrib.auth.models import Group, User
from django.db.models import Count
from users import filters
from users.models import ObjectPermission
from utilities.api import ModelViewSet
from utilities.querysets import RestrictedQuerySet
from . import serializers
#
# Users and groups
#
class UserViewSet(ModelViewSet):
queryset = RestrictedQuerySet(model=User).prefetch_related('groups').order_by('username')
serializer_class = serializers.UserSerializer
filterset_class = filters.UserFilterSet
class GroupViewSet(ModelViewSet):
queryset = RestrictedQuerySet(model=Group).annotate(user_count=Count('user')).order_by('name')
serializer_class = serializers.GroupSerializer
filterset_class = filters.GroupFilterSet
#
# ObjectPermissions
#
class ObjectPermissionViewSet(ModelViewSet):
queryset = ObjectPermission.objects.prefetch_related('object_types', 'groups', 'users')
serializer_class = serializers.ObjectPermissionSerializer
filterset_class = filters.ObjectPermissionFilterSet
|
b9fbc9ba6ab2c379e26d6e599fcaaf6ab9b84473
|
server/slack.py
|
server/slack.py
|
#!/usr/bin/python2.7
import json
import kartlogic.rank
import logging
import prettytable
import util.web
import util.slack
def handler(event, context):
logging.warning(event['body'])
logging.warning(json.dumps(util.slack.parse_input(event['body'])))
return util.web.respond_success("Successful")
def rank_individuals_by_average_score(event, context):
# retrieve the ranking board data
board_data = kartlogic.rank.average_individual()
# initialize the text table
table = prettytable.PrettyTable(['Rank', 'Player', 'Character', 'Average'])
# add player data to table
for index, player in enumerate(board_data):
table.add_row([(index + 1), player['name'], player['character'], player['average']])
# convert the entire table to a string
table_string = '```' + table.get_string(border=True) + '```'
# the response body that Slack expects
slack_response = util.slack.in_channel_response(table_string)
return util.web.respond_success_json(slack_response)
|
#!/usr/bin/python2.7
import kartlogic.rank
import prettytable
import util.web as webutil
import util.slack as slackutil
def handler(event, context):
input_data = slackutil.slack.parse_input(event['body'])
if slackutil.validate_slack_token(input_data) is False:
return webutil.respond_unauthorized("Invalid Slack token")
return webutil.respond_success("Successful")
def rank_individuals_by_average_score(event, context):
# retrieve the ranking board data
board_data = kartlogic.rank.average_individual()
# initialize the text table
table = prettytable.PrettyTable(['Rank', 'Player', 'Character', 'Average'])
# add player data to table
for index, player in enumerate(board_data):
table.add_row([(index + 1), player['name'], player['character'], player['average']])
# convert the entire table to a string
table_string = '```' + table.get_string(border=True) + '```'
# the response body that Slack expects
slack_response = slackutil.in_channel_response(table_string)
return webutil.respond_success_json(slack_response)
|
Add Slack token validation to handler
|
Add Slack token validation to handler
|
Python
|
mit
|
groppe/mario
|
#!/usr/bin/python2.7
import json
import kartlogic.rank
import logging
import prettytable
import util.web
import util.slack
def handler(event, context):
logging.warning(event['body'])
logging.warning(json.dumps(util.slack.parse_input(event['body'])))
return util.web.respond_success("Successful")
def rank_individuals_by_average_score(event, context):
# retrieve the ranking board data
board_data = kartlogic.rank.average_individual()
# initialize the text table
table = prettytable.PrettyTable(['Rank', 'Player', 'Character', 'Average'])
# add player data to table
for index, player in enumerate(board_data):
table.add_row([(index + 1), player['name'], player['character'], player['average']])
# convert the entire table to a string
table_string = '```' + table.get_string(border=True) + '```'
# the response body that Slack expects
slack_response = util.slack.in_channel_response(table_string)
return util.web.respond_success_json(slack_response)
Add Slack token validation to handler
|
#!/usr/bin/python2.7
import kartlogic.rank
import prettytable
import util.web as webutil
import util.slack as slackutil
def handler(event, context):
input_data = slackutil.slack.parse_input(event['body'])
if slackutil.validate_slack_token(input_data) is False:
return webutil.respond_unauthorized("Invalid Slack token")
return webutil.respond_success("Successful")
def rank_individuals_by_average_score(event, context):
# retrieve the ranking board data
board_data = kartlogic.rank.average_individual()
# initialize the text table
table = prettytable.PrettyTable(['Rank', 'Player', 'Character', 'Average'])
# add player data to table
for index, player in enumerate(board_data):
table.add_row([(index + 1), player['name'], player['character'], player['average']])
# convert the entire table to a string
table_string = '```' + table.get_string(border=True) + '```'
# the response body that Slack expects
slack_response = slackutil.in_channel_response(table_string)
return webutil.respond_success_json(slack_response)
|
<commit_before>#!/usr/bin/python2.7
import json
import kartlogic.rank
import logging
import prettytable
import util.web
import util.slack
def handler(event, context):
logging.warning(event['body'])
logging.warning(json.dumps(util.slack.parse_input(event['body'])))
return util.web.respond_success("Successful")
def rank_individuals_by_average_score(event, context):
# retrieve the ranking board data
board_data = kartlogic.rank.average_individual()
# initialize the text table
table = prettytable.PrettyTable(['Rank', 'Player', 'Character', 'Average'])
# add player data to table
for index, player in enumerate(board_data):
table.add_row([(index + 1), player['name'], player['character'], player['average']])
# convert the entire table to a string
table_string = '```' + table.get_string(border=True) + '```'
# the response body that Slack expects
slack_response = util.slack.in_channel_response(table_string)
return util.web.respond_success_json(slack_response)
<commit_msg>Add Slack token validation to handler<commit_after>
|
#!/usr/bin/python2.7
import kartlogic.rank
import prettytable
import util.web as webutil
import util.slack as slackutil
def handler(event, context):
input_data = slackutil.slack.parse_input(event['body'])
if slackutil.validate_slack_token(input_data) is False:
return webutil.respond_unauthorized("Invalid Slack token")
return webutil.respond_success("Successful")
def rank_individuals_by_average_score(event, context):
# retrieve the ranking board data
board_data = kartlogic.rank.average_individual()
# initialize the text table
table = prettytable.PrettyTable(['Rank', 'Player', 'Character', 'Average'])
# add player data to table
for index, player in enumerate(board_data):
table.add_row([(index + 1), player['name'], player['character'], player['average']])
# convert the entire table to a string
table_string = '```' + table.get_string(border=True) + '```'
# the response body that Slack expects
slack_response = slackutil.in_channel_response(table_string)
return webutil.respond_success_json(slack_response)
|
#!/usr/bin/python2.7
import json
import kartlogic.rank
import logging
import prettytable
import util.web
import util.slack
def handler(event, context):
logging.warning(event['body'])
logging.warning(json.dumps(util.slack.parse_input(event['body'])))
return util.web.respond_success("Successful")
def rank_individuals_by_average_score(event, context):
# retrieve the ranking board data
board_data = kartlogic.rank.average_individual()
# initialize the text table
table = prettytable.PrettyTable(['Rank', 'Player', 'Character', 'Average'])
# add player data to table
for index, player in enumerate(board_data):
table.add_row([(index + 1), player['name'], player['character'], player['average']])
# convert the entire table to a string
table_string = '```' + table.get_string(border=True) + '```'
# the response body that Slack expects
slack_response = util.slack.in_channel_response(table_string)
return util.web.respond_success_json(slack_response)
Add Slack token validation to handler#!/usr/bin/python2.7
import kartlogic.rank
import prettytable
import util.web as webutil
import util.slack as slackutil
def handler(event, context):
input_data = slackutil.slack.parse_input(event['body'])
if slackutil.validate_slack_token(input_data) is False:
return webutil.respond_unauthorized("Invalid Slack token")
return webutil.respond_success("Successful")
def rank_individuals_by_average_score(event, context):
# retrieve the ranking board data
board_data = kartlogic.rank.average_individual()
# initialize the text table
table = prettytable.PrettyTable(['Rank', 'Player', 'Character', 'Average'])
# add player data to table
for index, player in enumerate(board_data):
table.add_row([(index + 1), player['name'], player['character'], player['average']])
# convert the entire table to a string
table_string = '```' + table.get_string(border=True) + '```'
# the response body that Slack expects
slack_response = slackutil.in_channel_response(table_string)
return webutil.respond_success_json(slack_response)
|
<commit_before>#!/usr/bin/python2.7
import json
import kartlogic.rank
import logging
import prettytable
import util.web
import util.slack
def handler(event, context):
logging.warning(event['body'])
logging.warning(json.dumps(util.slack.parse_input(event['body'])))
return util.web.respond_success("Successful")
def rank_individuals_by_average_score(event, context):
# retrieve the ranking board data
board_data = kartlogic.rank.average_individual()
# initialize the text table
table = prettytable.PrettyTable(['Rank', 'Player', 'Character', 'Average'])
# add player data to table
for index, player in enumerate(board_data):
table.add_row([(index + 1), player['name'], player['character'], player['average']])
# convert the entire table to a string
table_string = '```' + table.get_string(border=True) + '```'
# the response body that Slack expects
slack_response = util.slack.in_channel_response(table_string)
return util.web.respond_success_json(slack_response)
<commit_msg>Add Slack token validation to handler<commit_after>#!/usr/bin/python2.7
import kartlogic.rank
import prettytable
import util.web as webutil
import util.slack as slackutil
def handler(event, context):
input_data = slackutil.slack.parse_input(event['body'])
if slackutil.validate_slack_token(input_data) is False:
return webutil.respond_unauthorized("Invalid Slack token")
return webutil.respond_success("Successful")
def rank_individuals_by_average_score(event, context):
# retrieve the ranking board data
board_data = kartlogic.rank.average_individual()
# initialize the text table
table = prettytable.PrettyTable(['Rank', 'Player', 'Character', 'Average'])
# add player data to table
for index, player in enumerate(board_data):
table.add_row([(index + 1), player['name'], player['character'], player['average']])
# convert the entire table to a string
table_string = '```' + table.get_string(border=True) + '```'
# the response body that Slack expects
slack_response = slackutil.in_channel_response(table_string)
return webutil.respond_success_json(slack_response)
|
d7e9244dcbfcb068305ab37ba2e08f0c19ffdd7d
|
nodeconductor/core/log.py
|
nodeconductor/core/log.py
|
from __future__ import absolute_import, unicode_literals
import logging
class EventLoggerAdapter(logging.LoggerAdapter):
"""
LoggerAdapter
"""
def __init__(self, logger):
super(EventLoggerAdapter, self).__init__(logger, {})
def process(self, msg, kwargs):
kwargs['extra'] = {'event': True}
return msg, kwargs
class EventLogFilter(logging.Filter):
"""
A filter that allows only event records that have event=True as extra parameter.
"""
def filter(self, record):
return hasattr(record, 'event')
|
from __future__ import absolute_import, unicode_literals
import logging
class EventLoggerAdapter(logging.LoggerAdapter, object):
"""
LoggerAdapter
"""
def __init__(self, logger):
super(EventLoggerAdapter, self).__init__(logger, {})
def process(self, msg, kwargs):
kwargs['extra'] = {'event': True}
return msg, kwargs
class EventLogFilter(logging.Filter):
"""
A filter that allows only event records that have event=True as extra parameter.
"""
def filter(self, record):
return hasattr(record, 'event')
|
Fix EventLoggerAdapter to work on py2.6
|
Fix EventLoggerAdapter to work on py2.6
|
Python
|
mit
|
opennode/nodeconductor,opennode/nodeconductor,opennode/nodeconductor
|
from __future__ import absolute_import, unicode_literals
import logging
class EventLoggerAdapter(logging.LoggerAdapter):
"""
LoggerAdapter
"""
def __init__(self, logger):
super(EventLoggerAdapter, self).__init__(logger, {})
def process(self, msg, kwargs):
kwargs['extra'] = {'event': True}
return msg, kwargs
class EventLogFilter(logging.Filter):
"""
A filter that allows only event records that have event=True as extra parameter.
"""
def filter(self, record):
return hasattr(record, 'event')Fix EventLoggerAdapter to work on py2.6
|
from __future__ import absolute_import, unicode_literals
import logging
class EventLoggerAdapter(logging.LoggerAdapter, object):
"""
LoggerAdapter
"""
def __init__(self, logger):
super(EventLoggerAdapter, self).__init__(logger, {})
def process(self, msg, kwargs):
kwargs['extra'] = {'event': True}
return msg, kwargs
class EventLogFilter(logging.Filter):
"""
A filter that allows only event records that have event=True as extra parameter.
"""
def filter(self, record):
return hasattr(record, 'event')
|
<commit_before>from __future__ import absolute_import, unicode_literals
import logging
class EventLoggerAdapter(logging.LoggerAdapter):
"""
LoggerAdapter
"""
def __init__(self, logger):
super(EventLoggerAdapter, self).__init__(logger, {})
def process(self, msg, kwargs):
kwargs['extra'] = {'event': True}
return msg, kwargs
class EventLogFilter(logging.Filter):
"""
A filter that allows only event records that have event=True as extra parameter.
"""
def filter(self, record):
return hasattr(record, 'event')<commit_msg>Fix EventLoggerAdapter to work on py2.6<commit_after>
|
from __future__ import absolute_import, unicode_literals
import logging
class EventLoggerAdapter(logging.LoggerAdapter, object):
"""
LoggerAdapter
"""
def __init__(self, logger):
super(EventLoggerAdapter, self).__init__(logger, {})
def process(self, msg, kwargs):
kwargs['extra'] = {'event': True}
return msg, kwargs
class EventLogFilter(logging.Filter):
"""
A filter that allows only event records that have event=True as extra parameter.
"""
def filter(self, record):
return hasattr(record, 'event')
|
from __future__ import absolute_import, unicode_literals
import logging
class EventLoggerAdapter(logging.LoggerAdapter):
"""
LoggerAdapter
"""
def __init__(self, logger):
super(EventLoggerAdapter, self).__init__(logger, {})
def process(self, msg, kwargs):
kwargs['extra'] = {'event': True}
return msg, kwargs
class EventLogFilter(logging.Filter):
"""
A filter that allows only event records that have event=True as extra parameter.
"""
def filter(self, record):
return hasattr(record, 'event')Fix EventLoggerAdapter to work on py2.6from __future__ import absolute_import, unicode_literals
import logging
class EventLoggerAdapter(logging.LoggerAdapter, object):
"""
LoggerAdapter
"""
def __init__(self, logger):
super(EventLoggerAdapter, self).__init__(logger, {})
def process(self, msg, kwargs):
kwargs['extra'] = {'event': True}
return msg, kwargs
class EventLogFilter(logging.Filter):
"""
A filter that allows only event records that have event=True as extra parameter.
"""
def filter(self, record):
return hasattr(record, 'event')
|
<commit_before>from __future__ import absolute_import, unicode_literals
import logging
class EventLoggerAdapter(logging.LoggerAdapter):
"""
LoggerAdapter
"""
def __init__(self, logger):
super(EventLoggerAdapter, self).__init__(logger, {})
def process(self, msg, kwargs):
kwargs['extra'] = {'event': True}
return msg, kwargs
class EventLogFilter(logging.Filter):
"""
A filter that allows only event records that have event=True as extra parameter.
"""
def filter(self, record):
return hasattr(record, 'event')<commit_msg>Fix EventLoggerAdapter to work on py2.6<commit_after>from __future__ import absolute_import, unicode_literals
import logging
class EventLoggerAdapter(logging.LoggerAdapter, object):
"""
LoggerAdapter
"""
def __init__(self, logger):
super(EventLoggerAdapter, self).__init__(logger, {})
def process(self, msg, kwargs):
kwargs['extra'] = {'event': True}
return msg, kwargs
class EventLogFilter(logging.Filter):
"""
A filter that allows only event records that have event=True as extra parameter.
"""
def filter(self, record):
return hasattr(record, 'event')
|
506b193781462b0771e01df383d1197f64d576d4
|
tests/basics/ModuleAttributes.py
|
tests/basics/ModuleAttributes.py
|
# Copyright 2012, Kay Hayen, mailto:kayhayen@gmx.de
#
# Python tests originally created or extracted from other peoples work. The
# parts were too small to be protected.
#
# 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.
#
""" Some module documentation.
With newline and stuff."""
import os
print "doc:", __doc__
print "filename:", __file__
print "builtins:", __builtins__
|
# Copyright 2012, Kay Hayen, mailto:kayhayen@gmx.de
#
# Python tests originally created or extracted from other peoples work. The
# parts were too small to be protected.
#
# 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.
#
""" Some module documentation.
With newline and stuff."""
import os
print "doc:", __doc__
print "filename:", __file__
print "builtins:", __builtins__
print "debug", __debug__
|
Cover the "__debug__" attribute as well.
|
Cover the "__debug__" attribute as well.
|
Python
|
apache-2.0
|
wfxiang08/Nuitka,tempbottle/Nuitka,tempbottle/Nuitka,wfxiang08/Nuitka,tempbottle/Nuitka,kayhayen/Nuitka,wfxiang08/Nuitka,kayhayen/Nuitka,kayhayen/Nuitka,kayhayen/Nuitka,tempbottle/Nuitka,wfxiang08/Nuitka
|
# Copyright 2012, Kay Hayen, mailto:kayhayen@gmx.de
#
# Python tests originally created or extracted from other peoples work. The
# parts were too small to be protected.
#
# 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.
#
""" Some module documentation.
With newline and stuff."""
import os
print "doc:", __doc__
print "filename:", __file__
print "builtins:", __builtins__
Cover the "__debug__" attribute as well.
|
# Copyright 2012, Kay Hayen, mailto:kayhayen@gmx.de
#
# Python tests originally created or extracted from other peoples work. The
# parts were too small to be protected.
#
# 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.
#
""" Some module documentation.
With newline and stuff."""
import os
print "doc:", __doc__
print "filename:", __file__
print "builtins:", __builtins__
print "debug", __debug__
|
<commit_before># Copyright 2012, Kay Hayen, mailto:kayhayen@gmx.de
#
# Python tests originally created or extracted from other peoples work. The
# parts were too small to be protected.
#
# 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.
#
""" Some module documentation.
With newline and stuff."""
import os
print "doc:", __doc__
print "filename:", __file__
print "builtins:", __builtins__
<commit_msg>Cover the "__debug__" attribute as well.<commit_after>
|
# Copyright 2012, Kay Hayen, mailto:kayhayen@gmx.de
#
# Python tests originally created or extracted from other peoples work. The
# parts were too small to be protected.
#
# 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.
#
""" Some module documentation.
With newline and stuff."""
import os
print "doc:", __doc__
print "filename:", __file__
print "builtins:", __builtins__
print "debug", __debug__
|
# Copyright 2012, Kay Hayen, mailto:kayhayen@gmx.de
#
# Python tests originally created or extracted from other peoples work. The
# parts were too small to be protected.
#
# 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.
#
""" Some module documentation.
With newline and stuff."""
import os
print "doc:", __doc__
print "filename:", __file__
print "builtins:", __builtins__
Cover the "__debug__" attribute as well.# Copyright 2012, Kay Hayen, mailto:kayhayen@gmx.de
#
# Python tests originally created or extracted from other peoples work. The
# parts were too small to be protected.
#
# 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.
#
""" Some module documentation.
With newline and stuff."""
import os
print "doc:", __doc__
print "filename:", __file__
print "builtins:", __builtins__
print "debug", __debug__
|
<commit_before># Copyright 2012, Kay Hayen, mailto:kayhayen@gmx.de
#
# Python tests originally created or extracted from other peoples work. The
# parts were too small to be protected.
#
# 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.
#
""" Some module documentation.
With newline and stuff."""
import os
print "doc:", __doc__
print "filename:", __file__
print "builtins:", __builtins__
<commit_msg>Cover the "__debug__" attribute as well.<commit_after># Copyright 2012, Kay Hayen, mailto:kayhayen@gmx.de
#
# Python tests originally created or extracted from other peoples work. The
# parts were too small to be protected.
#
# 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.
#
""" Some module documentation.
With newline and stuff."""
import os
print "doc:", __doc__
print "filename:", __file__
print "builtins:", __builtins__
print "debug", __debug__
|
f347341d138bb4f610dcca9c9791001d54e734be
|
diceclient.py
|
diceclient.py
|
#!/usr/bin/env python
import sys
from twisted.internet import reactor, defer
from twisted.internet.protocol import ClientCreator
from twisted.protocols import amp
from twisted.python import usage
from diceserver import RollDice, default_port
class Options(usage.Options):
optParameters = [
["host", "h", "localhost", "server hostname"],
["port", "p", default_port, "server port"],
]
def done(result):
print 'Got roll:', result
reactor.stop()
def roll_die(host, port):
clientcreator = ClientCreator(reactor, amp.AMP)
d1 = clientcreator.connectTCP(host, port)
d1.addCallback(lambda p: p.callRemote(RollDice, sides=6))
d1.addCallback(lambda result: result['result'])
d1.addCallback(done)
d1.addErrback(failure)
def failure(error):
print "failed", str(error)
reactor.stop()
if __name__ == '__main__':
options = Options()
try:
options.parseOptions()
except usage.UsageError, err:
print "%s: %s" % (sys.argv[0], err)
print "%s: Try --help for usage details" % sys.argv[0]
sys.exit(1)
host = options["host"]
port = int(options["port"])
roll_die(host, port)
reactor.run()
|
#!/usr/bin/env python
import sys
from twisted.internet import reactor, defer
from twisted.internet.protocol import ClientCreator
from twisted.protocols import amp
from twisted.python import usage
from diceserver import RollDice, default_port
class Options(usage.Options):
optParameters = [
["host", "h", "localhost", "server hostname"],
["port", "p", default_port, "server port"],
["sides", "s", 6, "number of sides"],
]
def done(result):
print 'Got roll:', result
reactor.stop()
def roll_die(host, port, sides):
clientcreator = ClientCreator(reactor, amp.AMP)
d1 = clientcreator.connectTCP(host, port)
d1.addCallback(lambda p: p.callRemote(RollDice, sides=sides))
d1.addCallback(lambda result: result['result'])
d1.addCallback(done)
d1.addErrback(failure)
def failure(error):
print "failed", str(error)
reactor.stop()
if __name__ == '__main__':
options = Options()
try:
options.parseOptions()
except usage.UsageError, err:
print "%s: %s" % (sys.argv[0], err)
print "%s: Try --help for usage details" % sys.argv[0]
sys.exit(1)
host = options["host"]
port = int(options["port"])
sides = int(options["sides"])
roll_die(host, port, sides)
reactor.run()
|
Add a command line option for number of sides.
|
Add a command line option for number of sides.
|
Python
|
mit
|
dripton/ampchat
|
#!/usr/bin/env python
import sys
from twisted.internet import reactor, defer
from twisted.internet.protocol import ClientCreator
from twisted.protocols import amp
from twisted.python import usage
from diceserver import RollDice, default_port
class Options(usage.Options):
optParameters = [
["host", "h", "localhost", "server hostname"],
["port", "p", default_port, "server port"],
]
def done(result):
print 'Got roll:', result
reactor.stop()
def roll_die(host, port):
clientcreator = ClientCreator(reactor, amp.AMP)
d1 = clientcreator.connectTCP(host, port)
d1.addCallback(lambda p: p.callRemote(RollDice, sides=6))
d1.addCallback(lambda result: result['result'])
d1.addCallback(done)
d1.addErrback(failure)
def failure(error):
print "failed", str(error)
reactor.stop()
if __name__ == '__main__':
options = Options()
try:
options.parseOptions()
except usage.UsageError, err:
print "%s: %s" % (sys.argv[0], err)
print "%s: Try --help for usage details" % sys.argv[0]
sys.exit(1)
host = options["host"]
port = int(options["port"])
roll_die(host, port)
reactor.run()
Add a command line option for number of sides.
|
#!/usr/bin/env python
import sys
from twisted.internet import reactor, defer
from twisted.internet.protocol import ClientCreator
from twisted.protocols import amp
from twisted.python import usage
from diceserver import RollDice, default_port
class Options(usage.Options):
optParameters = [
["host", "h", "localhost", "server hostname"],
["port", "p", default_port, "server port"],
["sides", "s", 6, "number of sides"],
]
def done(result):
print 'Got roll:', result
reactor.stop()
def roll_die(host, port, sides):
clientcreator = ClientCreator(reactor, amp.AMP)
d1 = clientcreator.connectTCP(host, port)
d1.addCallback(lambda p: p.callRemote(RollDice, sides=sides))
d1.addCallback(lambda result: result['result'])
d1.addCallback(done)
d1.addErrback(failure)
def failure(error):
print "failed", str(error)
reactor.stop()
if __name__ == '__main__':
options = Options()
try:
options.parseOptions()
except usage.UsageError, err:
print "%s: %s" % (sys.argv[0], err)
print "%s: Try --help for usage details" % sys.argv[0]
sys.exit(1)
host = options["host"]
port = int(options["port"])
sides = int(options["sides"])
roll_die(host, port, sides)
reactor.run()
|
<commit_before>#!/usr/bin/env python
import sys
from twisted.internet import reactor, defer
from twisted.internet.protocol import ClientCreator
from twisted.protocols import amp
from twisted.python import usage
from diceserver import RollDice, default_port
class Options(usage.Options):
optParameters = [
["host", "h", "localhost", "server hostname"],
["port", "p", default_port, "server port"],
]
def done(result):
print 'Got roll:', result
reactor.stop()
def roll_die(host, port):
clientcreator = ClientCreator(reactor, amp.AMP)
d1 = clientcreator.connectTCP(host, port)
d1.addCallback(lambda p: p.callRemote(RollDice, sides=6))
d1.addCallback(lambda result: result['result'])
d1.addCallback(done)
d1.addErrback(failure)
def failure(error):
print "failed", str(error)
reactor.stop()
if __name__ == '__main__':
options = Options()
try:
options.parseOptions()
except usage.UsageError, err:
print "%s: %s" % (sys.argv[0], err)
print "%s: Try --help for usage details" % sys.argv[0]
sys.exit(1)
host = options["host"]
port = int(options["port"])
roll_die(host, port)
reactor.run()
<commit_msg>Add a command line option for number of sides.<commit_after>
|
#!/usr/bin/env python
import sys
from twisted.internet import reactor, defer
from twisted.internet.protocol import ClientCreator
from twisted.protocols import amp
from twisted.python import usage
from diceserver import RollDice, default_port
class Options(usage.Options):
optParameters = [
["host", "h", "localhost", "server hostname"],
["port", "p", default_port, "server port"],
["sides", "s", 6, "number of sides"],
]
def done(result):
print 'Got roll:', result
reactor.stop()
def roll_die(host, port, sides):
clientcreator = ClientCreator(reactor, amp.AMP)
d1 = clientcreator.connectTCP(host, port)
d1.addCallback(lambda p: p.callRemote(RollDice, sides=sides))
d1.addCallback(lambda result: result['result'])
d1.addCallback(done)
d1.addErrback(failure)
def failure(error):
print "failed", str(error)
reactor.stop()
if __name__ == '__main__':
options = Options()
try:
options.parseOptions()
except usage.UsageError, err:
print "%s: %s" % (sys.argv[0], err)
print "%s: Try --help for usage details" % sys.argv[0]
sys.exit(1)
host = options["host"]
port = int(options["port"])
sides = int(options["sides"])
roll_die(host, port, sides)
reactor.run()
|
#!/usr/bin/env python
import sys
from twisted.internet import reactor, defer
from twisted.internet.protocol import ClientCreator
from twisted.protocols import amp
from twisted.python import usage
from diceserver import RollDice, default_port
class Options(usage.Options):
optParameters = [
["host", "h", "localhost", "server hostname"],
["port", "p", default_port, "server port"],
]
def done(result):
print 'Got roll:', result
reactor.stop()
def roll_die(host, port):
clientcreator = ClientCreator(reactor, amp.AMP)
d1 = clientcreator.connectTCP(host, port)
d1.addCallback(lambda p: p.callRemote(RollDice, sides=6))
d1.addCallback(lambda result: result['result'])
d1.addCallback(done)
d1.addErrback(failure)
def failure(error):
print "failed", str(error)
reactor.stop()
if __name__ == '__main__':
options = Options()
try:
options.parseOptions()
except usage.UsageError, err:
print "%s: %s" % (sys.argv[0], err)
print "%s: Try --help for usage details" % sys.argv[0]
sys.exit(1)
host = options["host"]
port = int(options["port"])
roll_die(host, port)
reactor.run()
Add a command line option for number of sides.#!/usr/bin/env python
import sys
from twisted.internet import reactor, defer
from twisted.internet.protocol import ClientCreator
from twisted.protocols import amp
from twisted.python import usage
from diceserver import RollDice, default_port
class Options(usage.Options):
optParameters = [
["host", "h", "localhost", "server hostname"],
["port", "p", default_port, "server port"],
["sides", "s", 6, "number of sides"],
]
def done(result):
print 'Got roll:', result
reactor.stop()
def roll_die(host, port, sides):
clientcreator = ClientCreator(reactor, amp.AMP)
d1 = clientcreator.connectTCP(host, port)
d1.addCallback(lambda p: p.callRemote(RollDice, sides=sides))
d1.addCallback(lambda result: result['result'])
d1.addCallback(done)
d1.addErrback(failure)
def failure(error):
print "failed", str(error)
reactor.stop()
if __name__ == '__main__':
options = Options()
try:
options.parseOptions()
except usage.UsageError, err:
print "%s: %s" % (sys.argv[0], err)
print "%s: Try --help for usage details" % sys.argv[0]
sys.exit(1)
host = options["host"]
port = int(options["port"])
sides = int(options["sides"])
roll_die(host, port, sides)
reactor.run()
|
<commit_before>#!/usr/bin/env python
import sys
from twisted.internet import reactor, defer
from twisted.internet.protocol import ClientCreator
from twisted.protocols import amp
from twisted.python import usage
from diceserver import RollDice, default_port
class Options(usage.Options):
optParameters = [
["host", "h", "localhost", "server hostname"],
["port", "p", default_port, "server port"],
]
def done(result):
print 'Got roll:', result
reactor.stop()
def roll_die(host, port):
clientcreator = ClientCreator(reactor, amp.AMP)
d1 = clientcreator.connectTCP(host, port)
d1.addCallback(lambda p: p.callRemote(RollDice, sides=6))
d1.addCallback(lambda result: result['result'])
d1.addCallback(done)
d1.addErrback(failure)
def failure(error):
print "failed", str(error)
reactor.stop()
if __name__ == '__main__':
options = Options()
try:
options.parseOptions()
except usage.UsageError, err:
print "%s: %s" % (sys.argv[0], err)
print "%s: Try --help for usage details" % sys.argv[0]
sys.exit(1)
host = options["host"]
port = int(options["port"])
roll_die(host, port)
reactor.run()
<commit_msg>Add a command line option for number of sides.<commit_after>#!/usr/bin/env python
import sys
from twisted.internet import reactor, defer
from twisted.internet.protocol import ClientCreator
from twisted.protocols import amp
from twisted.python import usage
from diceserver import RollDice, default_port
class Options(usage.Options):
optParameters = [
["host", "h", "localhost", "server hostname"],
["port", "p", default_port, "server port"],
["sides", "s", 6, "number of sides"],
]
def done(result):
print 'Got roll:', result
reactor.stop()
def roll_die(host, port, sides):
clientcreator = ClientCreator(reactor, amp.AMP)
d1 = clientcreator.connectTCP(host, port)
d1.addCallback(lambda p: p.callRemote(RollDice, sides=sides))
d1.addCallback(lambda result: result['result'])
d1.addCallback(done)
d1.addErrback(failure)
def failure(error):
print "failed", str(error)
reactor.stop()
if __name__ == '__main__':
options = Options()
try:
options.parseOptions()
except usage.UsageError, err:
print "%s: %s" % (sys.argv[0], err)
print "%s: Try --help for usage details" % sys.argv[0]
sys.exit(1)
host = options["host"]
port = int(options["port"])
sides = int(options["sides"])
roll_die(host, port, sides)
reactor.run()
|
b71a96f818c66b5578fb7c4475b67ecdcb16937a
|
recipes/recipe_modules/gclient/tests/sync_failure.py
|
recipes/recipe_modules/gclient/tests/sync_failure.py
|
# Copyright 2019 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 recipe_engine import post_process
DEPS = ['gclient']
def RunSteps(api):
src_cfg = api.gclient.make_config(CACHE_DIR='[ROOT]/git_cache')
api.gclient.sync(src_cfg)
def GenTests(api):
yield api.test(
'no-json',
api.override_step_data('gclient sync', retcode=1),
api.post_check(
lambda check, steps:
check(not steps['$result']['failure']['humanReason']
.startswith('Uncaught Exception'))),
api.post_process(post_process.DropExpectation)
)
|
# Copyright 2019 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 recipe_engine import post_process
DEPS = ['gclient']
def RunSteps(api):
src_cfg = api.gclient.make_config(CACHE_DIR='[ROOT]/git_cache')
api.gclient.sync(src_cfg)
def GenTests(api):
yield api.test(
'no-json',
api.override_step_data('gclient sync', retcode=1),
# Should not fail with uncaught exception
api.post_process(post_process.ResultReasonRE, r'^(?!Uncaught Exception)'),
api.post_process(post_process.DropExpectation)
)
|
Replace customzied test failure assertion with ResultReasonRE from engine
|
Replace customzied test failure assertion with ResultReasonRE from engine
This change is to facilitate the annotation protocol -> luciexe protocol
migration in the future. The failure response structure will be changed
after the migration. Therefore, we only need to change the
implementation detail of ResultReasonRE at that time.
R=iannucci
Change-Id: If5e0005dddcaf6ccdfbcb047e3855763cf4eadc5
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/tools/depot_tools/+/2146066
Auto-Submit: Yiwei Zhang <50b2a565e2e78c292794832469a30ce5abc9959c@google.com>
Reviewed-by: Robbie Iannucci <40f3d43a28ebae3cb819288542e1c84d73d962d5@chromium.org>
Commit-Queue: Robbie Iannucci <40f3d43a28ebae3cb819288542e1c84d73d962d5@chromium.org>
|
Python
|
bsd-3-clause
|
CoherentLabs/depot_tools,CoherentLabs/depot_tools
|
# Copyright 2019 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 recipe_engine import post_process
DEPS = ['gclient']
def RunSteps(api):
src_cfg = api.gclient.make_config(CACHE_DIR='[ROOT]/git_cache')
api.gclient.sync(src_cfg)
def GenTests(api):
yield api.test(
'no-json',
api.override_step_data('gclient sync', retcode=1),
api.post_check(
lambda check, steps:
check(not steps['$result']['failure']['humanReason']
.startswith('Uncaught Exception'))),
api.post_process(post_process.DropExpectation)
)
Replace customzied test failure assertion with ResultReasonRE from engine
This change is to facilitate the annotation protocol -> luciexe protocol
migration in the future. The failure response structure will be changed
after the migration. Therefore, we only need to change the
implementation detail of ResultReasonRE at that time.
R=iannucci
Change-Id: If5e0005dddcaf6ccdfbcb047e3855763cf4eadc5
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/tools/depot_tools/+/2146066
Auto-Submit: Yiwei Zhang <50b2a565e2e78c292794832469a30ce5abc9959c@google.com>
Reviewed-by: Robbie Iannucci <40f3d43a28ebae3cb819288542e1c84d73d962d5@chromium.org>
Commit-Queue: Robbie Iannucci <40f3d43a28ebae3cb819288542e1c84d73d962d5@chromium.org>
|
# Copyright 2019 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 recipe_engine import post_process
DEPS = ['gclient']
def RunSteps(api):
src_cfg = api.gclient.make_config(CACHE_DIR='[ROOT]/git_cache')
api.gclient.sync(src_cfg)
def GenTests(api):
yield api.test(
'no-json',
api.override_step_data('gclient sync', retcode=1),
# Should not fail with uncaught exception
api.post_process(post_process.ResultReasonRE, r'^(?!Uncaught Exception)'),
api.post_process(post_process.DropExpectation)
)
|
<commit_before># Copyright 2019 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 recipe_engine import post_process
DEPS = ['gclient']
def RunSteps(api):
src_cfg = api.gclient.make_config(CACHE_DIR='[ROOT]/git_cache')
api.gclient.sync(src_cfg)
def GenTests(api):
yield api.test(
'no-json',
api.override_step_data('gclient sync', retcode=1),
api.post_check(
lambda check, steps:
check(not steps['$result']['failure']['humanReason']
.startswith('Uncaught Exception'))),
api.post_process(post_process.DropExpectation)
)
<commit_msg>Replace customzied test failure assertion with ResultReasonRE from engine
This change is to facilitate the annotation protocol -> luciexe protocol
migration in the future. The failure response structure will be changed
after the migration. Therefore, we only need to change the
implementation detail of ResultReasonRE at that time.
R=iannucci
Change-Id: If5e0005dddcaf6ccdfbcb047e3855763cf4eadc5
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/tools/depot_tools/+/2146066
Auto-Submit: Yiwei Zhang <50b2a565e2e78c292794832469a30ce5abc9959c@google.com>
Reviewed-by: Robbie Iannucci <40f3d43a28ebae3cb819288542e1c84d73d962d5@chromium.org>
Commit-Queue: Robbie Iannucci <40f3d43a28ebae3cb819288542e1c84d73d962d5@chromium.org><commit_after>
|
# Copyright 2019 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 recipe_engine import post_process
DEPS = ['gclient']
def RunSteps(api):
src_cfg = api.gclient.make_config(CACHE_DIR='[ROOT]/git_cache')
api.gclient.sync(src_cfg)
def GenTests(api):
yield api.test(
'no-json',
api.override_step_data('gclient sync', retcode=1),
# Should not fail with uncaught exception
api.post_process(post_process.ResultReasonRE, r'^(?!Uncaught Exception)'),
api.post_process(post_process.DropExpectation)
)
|
# Copyright 2019 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 recipe_engine import post_process
DEPS = ['gclient']
def RunSteps(api):
src_cfg = api.gclient.make_config(CACHE_DIR='[ROOT]/git_cache')
api.gclient.sync(src_cfg)
def GenTests(api):
yield api.test(
'no-json',
api.override_step_data('gclient sync', retcode=1),
api.post_check(
lambda check, steps:
check(not steps['$result']['failure']['humanReason']
.startswith('Uncaught Exception'))),
api.post_process(post_process.DropExpectation)
)
Replace customzied test failure assertion with ResultReasonRE from engine
This change is to facilitate the annotation protocol -> luciexe protocol
migration in the future. The failure response structure will be changed
after the migration. Therefore, we only need to change the
implementation detail of ResultReasonRE at that time.
R=iannucci
Change-Id: If5e0005dddcaf6ccdfbcb047e3855763cf4eadc5
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/tools/depot_tools/+/2146066
Auto-Submit: Yiwei Zhang <50b2a565e2e78c292794832469a30ce5abc9959c@google.com>
Reviewed-by: Robbie Iannucci <40f3d43a28ebae3cb819288542e1c84d73d962d5@chromium.org>
Commit-Queue: Robbie Iannucci <40f3d43a28ebae3cb819288542e1c84d73d962d5@chromium.org># Copyright 2019 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 recipe_engine import post_process
DEPS = ['gclient']
def RunSteps(api):
src_cfg = api.gclient.make_config(CACHE_DIR='[ROOT]/git_cache')
api.gclient.sync(src_cfg)
def GenTests(api):
yield api.test(
'no-json',
api.override_step_data('gclient sync', retcode=1),
# Should not fail with uncaught exception
api.post_process(post_process.ResultReasonRE, r'^(?!Uncaught Exception)'),
api.post_process(post_process.DropExpectation)
)
|
<commit_before># Copyright 2019 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 recipe_engine import post_process
DEPS = ['gclient']
def RunSteps(api):
src_cfg = api.gclient.make_config(CACHE_DIR='[ROOT]/git_cache')
api.gclient.sync(src_cfg)
def GenTests(api):
yield api.test(
'no-json',
api.override_step_data('gclient sync', retcode=1),
api.post_check(
lambda check, steps:
check(not steps['$result']['failure']['humanReason']
.startswith('Uncaught Exception'))),
api.post_process(post_process.DropExpectation)
)
<commit_msg>Replace customzied test failure assertion with ResultReasonRE from engine
This change is to facilitate the annotation protocol -> luciexe protocol
migration in the future. The failure response structure will be changed
after the migration. Therefore, we only need to change the
implementation detail of ResultReasonRE at that time.
R=iannucci
Change-Id: If5e0005dddcaf6ccdfbcb047e3855763cf4eadc5
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/tools/depot_tools/+/2146066
Auto-Submit: Yiwei Zhang <50b2a565e2e78c292794832469a30ce5abc9959c@google.com>
Reviewed-by: Robbie Iannucci <40f3d43a28ebae3cb819288542e1c84d73d962d5@chromium.org>
Commit-Queue: Robbie Iannucci <40f3d43a28ebae3cb819288542e1c84d73d962d5@chromium.org><commit_after># Copyright 2019 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 recipe_engine import post_process
DEPS = ['gclient']
def RunSteps(api):
src_cfg = api.gclient.make_config(CACHE_DIR='[ROOT]/git_cache')
api.gclient.sync(src_cfg)
def GenTests(api):
yield api.test(
'no-json',
api.override_step_data('gclient sync', retcode=1),
# Should not fail with uncaught exception
api.post_process(post_process.ResultReasonRE, r'^(?!Uncaught Exception)'),
api.post_process(post_process.DropExpectation)
)
|
caab908d8f8948c3035c94018d7a1e31332edbad
|
udata/tests/frontend/__init__.py
|
udata/tests/frontend/__init__.py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import json
import re
from udata.tests import TestCase, WebTestMixin, SearchTestMixin
from udata import frontend, api
class FrontTestCase(WebTestMixin, SearchTestMixin, TestCase):
def create_app(self):
app = super(FrontTestCase, self).create_app()
api.init_app(app)
frontend.init_app(app)
return app
def get_json_ld(self, response):
# In the pattern below, we extract the content of the JSON-LD script
# The first ? is used to name the extracted string
# The second ? is used to express the non-greediness of the extraction
pattern = '<script id="json_ld" type="application/ld\+json">(?P<json_ld>[\s\S]*?)</script>'
json_ld = re.search(pattern, response.data).group('json_ld')
return json.loads(json_ld)
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import json
import re
from udata.tests import TestCase, WebTestMixin, SearchTestMixin
from udata import frontend, api
class FrontTestCase(WebTestMixin, SearchTestMixin, TestCase):
def create_app(self):
app = super(FrontTestCase, self).create_app()
api.init_app(app)
frontend.init_app(app)
return app
def get_json_ld(self, response):
# In the pattern below, we extract the content of the JSON-LD script
# The first ? is used to name the extracted string
# The second ? is used to express the non-greediness of the extraction
pattern = '<script id="json_ld" type="application/ld\+json">(?P<json_ld>[\s\S]*?)</script>'
search = re.search(pattern, response.data)
self.assertIsNotNone(search, (pattern, response.data))
json_ld = search.group('json_ld')
return json.loads(json_ld)
|
Add traces if there is no JSON-LD while it was expected
|
Add traces if there is no JSON-LD while it was expected
|
Python
|
agpl-3.0
|
opendatateam/udata,opendatateam/udata,etalab/udata,jphnoel/udata,jphnoel/udata,etalab/udata,davidbgk/udata,davidbgk/udata,jphnoel/udata,etalab/udata,davidbgk/udata,opendatateam/udata
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import json
import re
from udata.tests import TestCase, WebTestMixin, SearchTestMixin
from udata import frontend, api
class FrontTestCase(WebTestMixin, SearchTestMixin, TestCase):
def create_app(self):
app = super(FrontTestCase, self).create_app()
api.init_app(app)
frontend.init_app(app)
return app
def get_json_ld(self, response):
# In the pattern below, we extract the content of the JSON-LD script
# The first ? is used to name the extracted string
# The second ? is used to express the non-greediness of the extraction
pattern = '<script id="json_ld" type="application/ld\+json">(?P<json_ld>[\s\S]*?)</script>'
json_ld = re.search(pattern, response.data).group('json_ld')
return json.loads(json_ld)
Add traces if there is no JSON-LD while it was expected
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import json
import re
from udata.tests import TestCase, WebTestMixin, SearchTestMixin
from udata import frontend, api
class FrontTestCase(WebTestMixin, SearchTestMixin, TestCase):
def create_app(self):
app = super(FrontTestCase, self).create_app()
api.init_app(app)
frontend.init_app(app)
return app
def get_json_ld(self, response):
# In the pattern below, we extract the content of the JSON-LD script
# The first ? is used to name the extracted string
# The second ? is used to express the non-greediness of the extraction
pattern = '<script id="json_ld" type="application/ld\+json">(?P<json_ld>[\s\S]*?)</script>'
search = re.search(pattern, response.data)
self.assertIsNotNone(search, (pattern, response.data))
json_ld = search.group('json_ld')
return json.loads(json_ld)
|
<commit_before># -*- coding: utf-8 -*-
from __future__ import unicode_literals
import json
import re
from udata.tests import TestCase, WebTestMixin, SearchTestMixin
from udata import frontend, api
class FrontTestCase(WebTestMixin, SearchTestMixin, TestCase):
def create_app(self):
app = super(FrontTestCase, self).create_app()
api.init_app(app)
frontend.init_app(app)
return app
def get_json_ld(self, response):
# In the pattern below, we extract the content of the JSON-LD script
# The first ? is used to name the extracted string
# The second ? is used to express the non-greediness of the extraction
pattern = '<script id="json_ld" type="application/ld\+json">(?P<json_ld>[\s\S]*?)</script>'
json_ld = re.search(pattern, response.data).group('json_ld')
return json.loads(json_ld)
<commit_msg>Add traces if there is no JSON-LD while it was expected<commit_after>
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import json
import re
from udata.tests import TestCase, WebTestMixin, SearchTestMixin
from udata import frontend, api
class FrontTestCase(WebTestMixin, SearchTestMixin, TestCase):
def create_app(self):
app = super(FrontTestCase, self).create_app()
api.init_app(app)
frontend.init_app(app)
return app
def get_json_ld(self, response):
# In the pattern below, we extract the content of the JSON-LD script
# The first ? is used to name the extracted string
# The second ? is used to express the non-greediness of the extraction
pattern = '<script id="json_ld" type="application/ld\+json">(?P<json_ld>[\s\S]*?)</script>'
search = re.search(pattern, response.data)
self.assertIsNotNone(search, (pattern, response.data))
json_ld = search.group('json_ld')
return json.loads(json_ld)
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import json
import re
from udata.tests import TestCase, WebTestMixin, SearchTestMixin
from udata import frontend, api
class FrontTestCase(WebTestMixin, SearchTestMixin, TestCase):
def create_app(self):
app = super(FrontTestCase, self).create_app()
api.init_app(app)
frontend.init_app(app)
return app
def get_json_ld(self, response):
# In the pattern below, we extract the content of the JSON-LD script
# The first ? is used to name the extracted string
# The second ? is used to express the non-greediness of the extraction
pattern = '<script id="json_ld" type="application/ld\+json">(?P<json_ld>[\s\S]*?)</script>'
json_ld = re.search(pattern, response.data).group('json_ld')
return json.loads(json_ld)
Add traces if there is no JSON-LD while it was expected# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import json
import re
from udata.tests import TestCase, WebTestMixin, SearchTestMixin
from udata import frontend, api
class FrontTestCase(WebTestMixin, SearchTestMixin, TestCase):
def create_app(self):
app = super(FrontTestCase, self).create_app()
api.init_app(app)
frontend.init_app(app)
return app
def get_json_ld(self, response):
# In the pattern below, we extract the content of the JSON-LD script
# The first ? is used to name the extracted string
# The second ? is used to express the non-greediness of the extraction
pattern = '<script id="json_ld" type="application/ld\+json">(?P<json_ld>[\s\S]*?)</script>'
search = re.search(pattern, response.data)
self.assertIsNotNone(search, (pattern, response.data))
json_ld = search.group('json_ld')
return json.loads(json_ld)
|
<commit_before># -*- coding: utf-8 -*-
from __future__ import unicode_literals
import json
import re
from udata.tests import TestCase, WebTestMixin, SearchTestMixin
from udata import frontend, api
class FrontTestCase(WebTestMixin, SearchTestMixin, TestCase):
def create_app(self):
app = super(FrontTestCase, self).create_app()
api.init_app(app)
frontend.init_app(app)
return app
def get_json_ld(self, response):
# In the pattern below, we extract the content of the JSON-LD script
# The first ? is used to name the extracted string
# The second ? is used to express the non-greediness of the extraction
pattern = '<script id="json_ld" type="application/ld\+json">(?P<json_ld>[\s\S]*?)</script>'
json_ld = re.search(pattern, response.data).group('json_ld')
return json.loads(json_ld)
<commit_msg>Add traces if there is no JSON-LD while it was expected<commit_after># -*- coding: utf-8 -*-
from __future__ import unicode_literals
import json
import re
from udata.tests import TestCase, WebTestMixin, SearchTestMixin
from udata import frontend, api
class FrontTestCase(WebTestMixin, SearchTestMixin, TestCase):
def create_app(self):
app = super(FrontTestCase, self).create_app()
api.init_app(app)
frontend.init_app(app)
return app
def get_json_ld(self, response):
# In the pattern below, we extract the content of the JSON-LD script
# The first ? is used to name the extracted string
# The second ? is used to express the non-greediness of the extraction
pattern = '<script id="json_ld" type="application/ld\+json">(?P<json_ld>[\s\S]*?)</script>'
search = re.search(pattern, response.data)
self.assertIsNotNone(search, (pattern, response.data))
json_ld = search.group('json_ld')
return json.loads(json_ld)
|
62cc65003a426c7144da5e24f4806eb89cfd8118
|
polling_stations/apps/data_collection/management/commands/import_south_cambridge.py
|
polling_stations/apps/data_collection/management/commands/import_south_cambridge.py
|
from data_collection.management.commands import BaseXpressDemocracyClubCsvImporter
class Command(BaseXpressDemocracyClubCsvImporter):
council_id = 'E07000012'
addresses_name = 'May 2017/Democracy_Club__04May2017 (1).CSV'
stations_name = 'May 2017/Democracy_Club__04May2017 (1).CSV'
elections = [
'local.cambridgeshire.2017-05-04',
'mayor.cambridgeshire-and-peterborough.2017-05-04',
'parl.2017-06-08'
]
|
from data_collection.management.commands import BaseXpressDemocracyClubCsvImporter
class Command(BaseXpressDemocracyClubCsvImporter):
council_id = 'E07000012'
addresses_name = 'May 2017/Democracy_Club__04May2017 (1).CSV'
stations_name = 'May 2017/Democracy_Club__04May2017 (1).CSV'
elections = [
'local.cambridgeshire.2017-05-04',
'mayor.cambridgeshire-and-peterborough.2017-05-04',
#'parl.2017-06-08'
]
|
Comment out South Cambridgeshire election id
|
Comment out South Cambridgeshire election id
Update provided but queries to chase :(
|
Python
|
bsd-3-clause
|
DemocracyClub/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,chris48s/UK-Polling-Stations,chris48s/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,chris48s/UK-Polling-Stations
|
from data_collection.management.commands import BaseXpressDemocracyClubCsvImporter
class Command(BaseXpressDemocracyClubCsvImporter):
council_id = 'E07000012'
addresses_name = 'May 2017/Democracy_Club__04May2017 (1).CSV'
stations_name = 'May 2017/Democracy_Club__04May2017 (1).CSV'
elections = [
'local.cambridgeshire.2017-05-04',
'mayor.cambridgeshire-and-peterborough.2017-05-04',
'parl.2017-06-08'
]
Comment out South Cambridgeshire election id
Update provided but queries to chase :(
|
from data_collection.management.commands import BaseXpressDemocracyClubCsvImporter
class Command(BaseXpressDemocracyClubCsvImporter):
council_id = 'E07000012'
addresses_name = 'May 2017/Democracy_Club__04May2017 (1).CSV'
stations_name = 'May 2017/Democracy_Club__04May2017 (1).CSV'
elections = [
'local.cambridgeshire.2017-05-04',
'mayor.cambridgeshire-and-peterborough.2017-05-04',
#'parl.2017-06-08'
]
|
<commit_before>from data_collection.management.commands import BaseXpressDemocracyClubCsvImporter
class Command(BaseXpressDemocracyClubCsvImporter):
council_id = 'E07000012'
addresses_name = 'May 2017/Democracy_Club__04May2017 (1).CSV'
stations_name = 'May 2017/Democracy_Club__04May2017 (1).CSV'
elections = [
'local.cambridgeshire.2017-05-04',
'mayor.cambridgeshire-and-peterborough.2017-05-04',
'parl.2017-06-08'
]
<commit_msg>Comment out South Cambridgeshire election id
Update provided but queries to chase :(<commit_after>
|
from data_collection.management.commands import BaseXpressDemocracyClubCsvImporter
class Command(BaseXpressDemocracyClubCsvImporter):
council_id = 'E07000012'
addresses_name = 'May 2017/Democracy_Club__04May2017 (1).CSV'
stations_name = 'May 2017/Democracy_Club__04May2017 (1).CSV'
elections = [
'local.cambridgeshire.2017-05-04',
'mayor.cambridgeshire-and-peterborough.2017-05-04',
#'parl.2017-06-08'
]
|
from data_collection.management.commands import BaseXpressDemocracyClubCsvImporter
class Command(BaseXpressDemocracyClubCsvImporter):
council_id = 'E07000012'
addresses_name = 'May 2017/Democracy_Club__04May2017 (1).CSV'
stations_name = 'May 2017/Democracy_Club__04May2017 (1).CSV'
elections = [
'local.cambridgeshire.2017-05-04',
'mayor.cambridgeshire-and-peterborough.2017-05-04',
'parl.2017-06-08'
]
Comment out South Cambridgeshire election id
Update provided but queries to chase :(from data_collection.management.commands import BaseXpressDemocracyClubCsvImporter
class Command(BaseXpressDemocracyClubCsvImporter):
council_id = 'E07000012'
addresses_name = 'May 2017/Democracy_Club__04May2017 (1).CSV'
stations_name = 'May 2017/Democracy_Club__04May2017 (1).CSV'
elections = [
'local.cambridgeshire.2017-05-04',
'mayor.cambridgeshire-and-peterborough.2017-05-04',
#'parl.2017-06-08'
]
|
<commit_before>from data_collection.management.commands import BaseXpressDemocracyClubCsvImporter
class Command(BaseXpressDemocracyClubCsvImporter):
council_id = 'E07000012'
addresses_name = 'May 2017/Democracy_Club__04May2017 (1).CSV'
stations_name = 'May 2017/Democracy_Club__04May2017 (1).CSV'
elections = [
'local.cambridgeshire.2017-05-04',
'mayor.cambridgeshire-and-peterborough.2017-05-04',
'parl.2017-06-08'
]
<commit_msg>Comment out South Cambridgeshire election id
Update provided but queries to chase :(<commit_after>from data_collection.management.commands import BaseXpressDemocracyClubCsvImporter
class Command(BaseXpressDemocracyClubCsvImporter):
council_id = 'E07000012'
addresses_name = 'May 2017/Democracy_Club__04May2017 (1).CSV'
stations_name = 'May 2017/Democracy_Club__04May2017 (1).CSV'
elections = [
'local.cambridgeshire.2017-05-04',
'mayor.cambridgeshire-and-peterborough.2017-05-04',
#'parl.2017-06-08'
]
|
cf297fc336d069b9210cfebec9f2cd724faa62fa
|
src/acme/demo_bundle/command.py
|
src/acme/demo_bundle/command.py
|
# -*- coding: utf-8 -*-
# This file is part of the pymfony package.
#
# (c) Alexandre Quercia <alquerci@email.com>
#
# For the full copyright and license information, please view the LICENSE
# file that was distributed with this source code.
"""
"""
from __future__ import absolute_import;
import time
from pymfony.component.console import Response
from pymfony.component.dependency import ContainerAware
from pymfony.component.console import Request
class DemoController(ContainerAware):
def helloAction(self, request):
assert isinstance(request, Request);
clock = "";
if request.getOption('time'):
clock = "{0}: ".format(time.time());
return Response("{0}Hello <info>{1}</info>!".format(
clock,
request.getArgument('name'),
));
|
# -*- coding: utf-8 -*-
# This file is part of the pymfony package.
#
# (c) Alexandre Quercia <alquerci@email.com>
#
# For the full copyright and license information, please view the LICENSE
# file that was distributed with this source code.
"""
"""
from __future__ import absolute_import;
import time
from pymfony.component.console import Response
from pymfony.component.dependency import ContainerAware
from pymfony.component.console import Request
class DemoCommand(ContainerAware):
def helloAction(self, request):
assert isinstance(request, Request);
clock = "";
if request.getOption('time'):
clock = "{0}: ".format(time.time());
return Response("{0}Hello <info>{1}</info>!".format(
clock,
request.getArgument('name'),
));
|
Update with last version of pymfony
|
Update with last version of pymfony
|
Python
|
mit
|
pymfony/pymfony-standard
|
# -*- coding: utf-8 -*-
# This file is part of the pymfony package.
#
# (c) Alexandre Quercia <alquerci@email.com>
#
# For the full copyright and license information, please view the LICENSE
# file that was distributed with this source code.
"""
"""
from __future__ import absolute_import;
import time
from pymfony.component.console import Response
from pymfony.component.dependency import ContainerAware
from pymfony.component.console import Request
class DemoController(ContainerAware):
def helloAction(self, request):
assert isinstance(request, Request);
clock = "";
if request.getOption('time'):
clock = "{0}: ".format(time.time());
return Response("{0}Hello <info>{1}</info>!".format(
clock,
request.getArgument('name'),
));
Update with last version of pymfony
|
# -*- coding: utf-8 -*-
# This file is part of the pymfony package.
#
# (c) Alexandre Quercia <alquerci@email.com>
#
# For the full copyright and license information, please view the LICENSE
# file that was distributed with this source code.
"""
"""
from __future__ import absolute_import;
import time
from pymfony.component.console import Response
from pymfony.component.dependency import ContainerAware
from pymfony.component.console import Request
class DemoCommand(ContainerAware):
def helloAction(self, request):
assert isinstance(request, Request);
clock = "";
if request.getOption('time'):
clock = "{0}: ".format(time.time());
return Response("{0}Hello <info>{1}</info>!".format(
clock,
request.getArgument('name'),
));
|
<commit_before># -*- coding: utf-8 -*-
# This file is part of the pymfony package.
#
# (c) Alexandre Quercia <alquerci@email.com>
#
# For the full copyright and license information, please view the LICENSE
# file that was distributed with this source code.
"""
"""
from __future__ import absolute_import;
import time
from pymfony.component.console import Response
from pymfony.component.dependency import ContainerAware
from pymfony.component.console import Request
class DemoController(ContainerAware):
def helloAction(self, request):
assert isinstance(request, Request);
clock = "";
if request.getOption('time'):
clock = "{0}: ".format(time.time());
return Response("{0}Hello <info>{1}</info>!".format(
clock,
request.getArgument('name'),
));
<commit_msg>Update with last version of pymfony<commit_after>
|
# -*- coding: utf-8 -*-
# This file is part of the pymfony package.
#
# (c) Alexandre Quercia <alquerci@email.com>
#
# For the full copyright and license information, please view the LICENSE
# file that was distributed with this source code.
"""
"""
from __future__ import absolute_import;
import time
from pymfony.component.console import Response
from pymfony.component.dependency import ContainerAware
from pymfony.component.console import Request
class DemoCommand(ContainerAware):
def helloAction(self, request):
assert isinstance(request, Request);
clock = "";
if request.getOption('time'):
clock = "{0}: ".format(time.time());
return Response("{0}Hello <info>{1}</info>!".format(
clock,
request.getArgument('name'),
));
|
# -*- coding: utf-8 -*-
# This file is part of the pymfony package.
#
# (c) Alexandre Quercia <alquerci@email.com>
#
# For the full copyright and license information, please view the LICENSE
# file that was distributed with this source code.
"""
"""
from __future__ import absolute_import;
import time
from pymfony.component.console import Response
from pymfony.component.dependency import ContainerAware
from pymfony.component.console import Request
class DemoController(ContainerAware):
def helloAction(self, request):
assert isinstance(request, Request);
clock = "";
if request.getOption('time'):
clock = "{0}: ".format(time.time());
return Response("{0}Hello <info>{1}</info>!".format(
clock,
request.getArgument('name'),
));
Update with last version of pymfony# -*- coding: utf-8 -*-
# This file is part of the pymfony package.
#
# (c) Alexandre Quercia <alquerci@email.com>
#
# For the full copyright and license information, please view the LICENSE
# file that was distributed with this source code.
"""
"""
from __future__ import absolute_import;
import time
from pymfony.component.console import Response
from pymfony.component.dependency import ContainerAware
from pymfony.component.console import Request
class DemoCommand(ContainerAware):
def helloAction(self, request):
assert isinstance(request, Request);
clock = "";
if request.getOption('time'):
clock = "{0}: ".format(time.time());
return Response("{0}Hello <info>{1}</info>!".format(
clock,
request.getArgument('name'),
));
|
<commit_before># -*- coding: utf-8 -*-
# This file is part of the pymfony package.
#
# (c) Alexandre Quercia <alquerci@email.com>
#
# For the full copyright and license information, please view the LICENSE
# file that was distributed with this source code.
"""
"""
from __future__ import absolute_import;
import time
from pymfony.component.console import Response
from pymfony.component.dependency import ContainerAware
from pymfony.component.console import Request
class DemoController(ContainerAware):
def helloAction(self, request):
assert isinstance(request, Request);
clock = "";
if request.getOption('time'):
clock = "{0}: ".format(time.time());
return Response("{0}Hello <info>{1}</info>!".format(
clock,
request.getArgument('name'),
));
<commit_msg>Update with last version of pymfony<commit_after># -*- coding: utf-8 -*-
# This file is part of the pymfony package.
#
# (c) Alexandre Quercia <alquerci@email.com>
#
# For the full copyright and license information, please view the LICENSE
# file that was distributed with this source code.
"""
"""
from __future__ import absolute_import;
import time
from pymfony.component.console import Response
from pymfony.component.dependency import ContainerAware
from pymfony.component.console import Request
class DemoCommand(ContainerAware):
def helloAction(self, request):
assert isinstance(request, Request);
clock = "";
if request.getOption('time'):
clock = "{0}: ".format(time.time());
return Response("{0}Hello <info>{1}</info>!".format(
clock,
request.getArgument('name'),
));
|
d7fdebdc4ce52e59c126a27ea06171994a6c846b
|
src/config/common/ssl_adapter.py
|
src/config/common/ssl_adapter.py
|
""" HTTPS Transport Adapter for python-requests, that allows configuration of
SSL version"""
# -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# @author: Sanju Abraham, Juniper Networks, OpenContrail
from requests.adapters import HTTPAdapter
try:
# This is required for RDO, which installs both python-requests
# and python-urllib3, but symlinks python-request's internally packaged
# urllib3 to the site installed one.
from requests.packages.urllib3.poolmanager import PoolManager
except ImportError:
# Fallback to standard installation methods
from urllib3.poolmanager import PoolManager
class SSLAdapter(HTTPAdapter):
'''An HTTPS Transport Adapter that can be configured with SSL/TLS
version.'''
def __init__(self, ssl_version=None, **kwargs):
self.ssl_version = ssl_version
self.poolmanager = None
super(SSLAdapter, self).__init__(**kwargs)
def init_poolmanager(self, connections, maxsize, block=False):
self.poolmanager = PoolManager(num_pools=connections,
maxsize=maxsize,
block=block,
ssl_version=self.ssl_version)
|
""" HTTPS Transport Adapter for python-requests, that allows configuration of
SSL version"""
# -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# @author: Sanju Abraham, Juniper Networks, OpenContrail
from requests.adapters import HTTPAdapter
try:
# This is required for RDO, which installs both python-requests
# and python-urllib3, but symlinks python-request's internally packaged
# urllib3 to the site installed one.
from requests.packages.urllib3.poolmanager import PoolManager
except ImportError:
# Fallback to standard installation methods
from urllib3.poolmanager import PoolManager
class SSLAdapter(HTTPAdapter):
'''An HTTPS Transport Adapter that can be configured with SSL/TLS
version.'''
HTTPAdapter.__attrs__.extend(['ssl_version'])
def __init__(self, ssl_version=None, **kwargs):
self.ssl_version = ssl_version
self.poolmanager = None
super(SSLAdapter, self).__init__(**kwargs)
def init_poolmanager(self, connections, maxsize, block=False):
self.poolmanager = PoolManager(num_pools=connections,
maxsize=maxsize,
block=block,
ssl_version=self.ssl_version)
|
Add ssl_version to the list of attributes, required when vnc_api gets called via multiprocessing module. This will ensure ssl_version gets included when pickle calls __getstate__ and __setstate__.
|
Add ssl_version to the list of attributes, required when vnc_api gets called via multiprocessing module.
This will ensure ssl_version gets included when pickle calls __getstate__ and __setstate__.
Courtesy: https://github.com/sigmavirus24/requests-toolbelt/commit/decadbd3512444889feb30cf1ff2f1448a3ecfca
Closes-Bug:#1604247
Change-Id: Iee9e0348c005e88c535f4da33cf98149a8c1b19d
|
Python
|
apache-2.0
|
codilime/contrail-controller,codilime/contrail-controller,codilime/contrail-controller,codilime/contrail-controller,codilime/contrail-controller,codilime/contrail-controller
|
""" HTTPS Transport Adapter for python-requests, that allows configuration of
SSL version"""
# -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# @author: Sanju Abraham, Juniper Networks, OpenContrail
from requests.adapters import HTTPAdapter
try:
# This is required for RDO, which installs both python-requests
# and python-urllib3, but symlinks python-request's internally packaged
# urllib3 to the site installed one.
from requests.packages.urllib3.poolmanager import PoolManager
except ImportError:
# Fallback to standard installation methods
from urllib3.poolmanager import PoolManager
class SSLAdapter(HTTPAdapter):
'''An HTTPS Transport Adapter that can be configured with SSL/TLS
version.'''
def __init__(self, ssl_version=None, **kwargs):
self.ssl_version = ssl_version
self.poolmanager = None
super(SSLAdapter, self).__init__(**kwargs)
def init_poolmanager(self, connections, maxsize, block=False):
self.poolmanager = PoolManager(num_pools=connections,
maxsize=maxsize,
block=block,
ssl_version=self.ssl_version)
Add ssl_version to the list of attributes, required when vnc_api gets called via multiprocessing module.
This will ensure ssl_version gets included when pickle calls __getstate__ and __setstate__.
Courtesy: https://github.com/sigmavirus24/requests-toolbelt/commit/decadbd3512444889feb30cf1ff2f1448a3ecfca
Closes-Bug:#1604247
Change-Id: Iee9e0348c005e88c535f4da33cf98149a8c1b19d
|
""" HTTPS Transport Adapter for python-requests, that allows configuration of
SSL version"""
# -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# @author: Sanju Abraham, Juniper Networks, OpenContrail
from requests.adapters import HTTPAdapter
try:
# This is required for RDO, which installs both python-requests
# and python-urllib3, but symlinks python-request's internally packaged
# urllib3 to the site installed one.
from requests.packages.urllib3.poolmanager import PoolManager
except ImportError:
# Fallback to standard installation methods
from urllib3.poolmanager import PoolManager
class SSLAdapter(HTTPAdapter):
'''An HTTPS Transport Adapter that can be configured with SSL/TLS
version.'''
HTTPAdapter.__attrs__.extend(['ssl_version'])
def __init__(self, ssl_version=None, **kwargs):
self.ssl_version = ssl_version
self.poolmanager = None
super(SSLAdapter, self).__init__(**kwargs)
def init_poolmanager(self, connections, maxsize, block=False):
self.poolmanager = PoolManager(num_pools=connections,
maxsize=maxsize,
block=block,
ssl_version=self.ssl_version)
|
<commit_before>""" HTTPS Transport Adapter for python-requests, that allows configuration of
SSL version"""
# -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# @author: Sanju Abraham, Juniper Networks, OpenContrail
from requests.adapters import HTTPAdapter
try:
# This is required for RDO, which installs both python-requests
# and python-urllib3, but symlinks python-request's internally packaged
# urllib3 to the site installed one.
from requests.packages.urllib3.poolmanager import PoolManager
except ImportError:
# Fallback to standard installation methods
from urllib3.poolmanager import PoolManager
class SSLAdapter(HTTPAdapter):
'''An HTTPS Transport Adapter that can be configured with SSL/TLS
version.'''
def __init__(self, ssl_version=None, **kwargs):
self.ssl_version = ssl_version
self.poolmanager = None
super(SSLAdapter, self).__init__(**kwargs)
def init_poolmanager(self, connections, maxsize, block=False):
self.poolmanager = PoolManager(num_pools=connections,
maxsize=maxsize,
block=block,
ssl_version=self.ssl_version)
<commit_msg>Add ssl_version to the list of attributes, required when vnc_api gets called via multiprocessing module.
This will ensure ssl_version gets included when pickle calls __getstate__ and __setstate__.
Courtesy: https://github.com/sigmavirus24/requests-toolbelt/commit/decadbd3512444889feb30cf1ff2f1448a3ecfca
Closes-Bug:#1604247
Change-Id: Iee9e0348c005e88c535f4da33cf98149a8c1b19d<commit_after>
|
""" HTTPS Transport Adapter for python-requests, that allows configuration of
SSL version"""
# -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# @author: Sanju Abraham, Juniper Networks, OpenContrail
from requests.adapters import HTTPAdapter
try:
# This is required for RDO, which installs both python-requests
# and python-urllib3, but symlinks python-request's internally packaged
# urllib3 to the site installed one.
from requests.packages.urllib3.poolmanager import PoolManager
except ImportError:
# Fallback to standard installation methods
from urllib3.poolmanager import PoolManager
class SSLAdapter(HTTPAdapter):
'''An HTTPS Transport Adapter that can be configured with SSL/TLS
version.'''
HTTPAdapter.__attrs__.extend(['ssl_version'])
def __init__(self, ssl_version=None, **kwargs):
self.ssl_version = ssl_version
self.poolmanager = None
super(SSLAdapter, self).__init__(**kwargs)
def init_poolmanager(self, connections, maxsize, block=False):
self.poolmanager = PoolManager(num_pools=connections,
maxsize=maxsize,
block=block,
ssl_version=self.ssl_version)
|
""" HTTPS Transport Adapter for python-requests, that allows configuration of
SSL version"""
# -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# @author: Sanju Abraham, Juniper Networks, OpenContrail
from requests.adapters import HTTPAdapter
try:
# This is required for RDO, which installs both python-requests
# and python-urllib3, but symlinks python-request's internally packaged
# urllib3 to the site installed one.
from requests.packages.urllib3.poolmanager import PoolManager
except ImportError:
# Fallback to standard installation methods
from urllib3.poolmanager import PoolManager
class SSLAdapter(HTTPAdapter):
'''An HTTPS Transport Adapter that can be configured with SSL/TLS
version.'''
def __init__(self, ssl_version=None, **kwargs):
self.ssl_version = ssl_version
self.poolmanager = None
super(SSLAdapter, self).__init__(**kwargs)
def init_poolmanager(self, connections, maxsize, block=False):
self.poolmanager = PoolManager(num_pools=connections,
maxsize=maxsize,
block=block,
ssl_version=self.ssl_version)
Add ssl_version to the list of attributes, required when vnc_api gets called via multiprocessing module.
This will ensure ssl_version gets included when pickle calls __getstate__ and __setstate__.
Courtesy: https://github.com/sigmavirus24/requests-toolbelt/commit/decadbd3512444889feb30cf1ff2f1448a3ecfca
Closes-Bug:#1604247
Change-Id: Iee9e0348c005e88c535f4da33cf98149a8c1b19d""" HTTPS Transport Adapter for python-requests, that allows configuration of
SSL version"""
# -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# @author: Sanju Abraham, Juniper Networks, OpenContrail
from requests.adapters import HTTPAdapter
try:
# This is required for RDO, which installs both python-requests
# and python-urllib3, but symlinks python-request's internally packaged
# urllib3 to the site installed one.
from requests.packages.urllib3.poolmanager import PoolManager
except ImportError:
# Fallback to standard installation methods
from urllib3.poolmanager import PoolManager
class SSLAdapter(HTTPAdapter):
'''An HTTPS Transport Adapter that can be configured with SSL/TLS
version.'''
HTTPAdapter.__attrs__.extend(['ssl_version'])
def __init__(self, ssl_version=None, **kwargs):
self.ssl_version = ssl_version
self.poolmanager = None
super(SSLAdapter, self).__init__(**kwargs)
def init_poolmanager(self, connections, maxsize, block=False):
self.poolmanager = PoolManager(num_pools=connections,
maxsize=maxsize,
block=block,
ssl_version=self.ssl_version)
|
<commit_before>""" HTTPS Transport Adapter for python-requests, that allows configuration of
SSL version"""
# -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# @author: Sanju Abraham, Juniper Networks, OpenContrail
from requests.adapters import HTTPAdapter
try:
# This is required for RDO, which installs both python-requests
# and python-urllib3, but symlinks python-request's internally packaged
# urllib3 to the site installed one.
from requests.packages.urllib3.poolmanager import PoolManager
except ImportError:
# Fallback to standard installation methods
from urllib3.poolmanager import PoolManager
class SSLAdapter(HTTPAdapter):
'''An HTTPS Transport Adapter that can be configured with SSL/TLS
version.'''
def __init__(self, ssl_version=None, **kwargs):
self.ssl_version = ssl_version
self.poolmanager = None
super(SSLAdapter, self).__init__(**kwargs)
def init_poolmanager(self, connections, maxsize, block=False):
self.poolmanager = PoolManager(num_pools=connections,
maxsize=maxsize,
block=block,
ssl_version=self.ssl_version)
<commit_msg>Add ssl_version to the list of attributes, required when vnc_api gets called via multiprocessing module.
This will ensure ssl_version gets included when pickle calls __getstate__ and __setstate__.
Courtesy: https://github.com/sigmavirus24/requests-toolbelt/commit/decadbd3512444889feb30cf1ff2f1448a3ecfca
Closes-Bug:#1604247
Change-Id: Iee9e0348c005e88c535f4da33cf98149a8c1b19d<commit_after>""" HTTPS Transport Adapter for python-requests, that allows configuration of
SSL version"""
# -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# @author: Sanju Abraham, Juniper Networks, OpenContrail
from requests.adapters import HTTPAdapter
try:
# This is required for RDO, which installs both python-requests
# and python-urllib3, but symlinks python-request's internally packaged
# urllib3 to the site installed one.
from requests.packages.urllib3.poolmanager import PoolManager
except ImportError:
# Fallback to standard installation methods
from urllib3.poolmanager import PoolManager
class SSLAdapter(HTTPAdapter):
'''An HTTPS Transport Adapter that can be configured with SSL/TLS
version.'''
HTTPAdapter.__attrs__.extend(['ssl_version'])
def __init__(self, ssl_version=None, **kwargs):
self.ssl_version = ssl_version
self.poolmanager = None
super(SSLAdapter, self).__init__(**kwargs)
def init_poolmanager(self, connections, maxsize, block=False):
self.poolmanager = PoolManager(num_pools=connections,
maxsize=maxsize,
block=block,
ssl_version=self.ssl_version)
|
01c17356bd9eed56979c55ccb55659508d08b218
|
src/waldur_openstack/openstack_tenant/migrations/0004_fill_tenant_id.py
|
src/waldur_openstack/openstack_tenant/migrations/0004_fill_tenant_id.py
|
from django.db import migrations
def fill_tenant_id(apps, schema_editor):
ServiceSettings = apps.get_model('structure', 'ServiceSettings')
for service_settings in ServiceSettings.objects.filter(type='OpenStackTenant'):
tenant = service_settings.scope
if (
tenant
and tenant.backend_id
and not service_settings.options.get('tenant_id')
):
service_settings.options['tenant_id'] = tenant.backend_id
service_settings.save(update_fields=['options'])
class Migration(migrations.Migration):
dependencies = [
('openstack_tenant', '0003_extend_description_limits'),
]
operations = [
migrations.RunPython(fill_tenant_id),
]
|
from django.core.exceptions import ObjectDoesNotExist
from django.db import migrations
def fill_tenant_id(apps, schema_editor):
ServiceSettings = apps.get_model('structure', 'ServiceSettings')
Tenant = apps.get_model('openstack', 'Tenant')
for service_settings in ServiceSettings.objects.filter(type='OpenStackTenant'):
if not service_settings.object_id:
continue
try:
tenant = Tenant.objects.get(id=service_settings.object_id)
except ObjectDoesNotExist:
pass
else:
if tenant.backend_id and not service_settings.options.get('tenant_id'):
service_settings.options['tenant_id'] = tenant.backend_id
service_settings.save(update_fields=['options'])
class Migration(migrations.Migration):
dependencies = [
('openstack_tenant', '0003_extend_description_limits'),
]
operations = [
migrations.RunPython(fill_tenant_id),
]
|
Fix migration: don't use virtual field scope.
|
Fix migration: don't use virtual field scope.
|
Python
|
mit
|
opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind
|
from django.db import migrations
def fill_tenant_id(apps, schema_editor):
ServiceSettings = apps.get_model('structure', 'ServiceSettings')
for service_settings in ServiceSettings.objects.filter(type='OpenStackTenant'):
tenant = service_settings.scope
if (
tenant
and tenant.backend_id
and not service_settings.options.get('tenant_id')
):
service_settings.options['tenant_id'] = tenant.backend_id
service_settings.save(update_fields=['options'])
class Migration(migrations.Migration):
dependencies = [
('openstack_tenant', '0003_extend_description_limits'),
]
operations = [
migrations.RunPython(fill_tenant_id),
]
Fix migration: don't use virtual field scope.
|
from django.core.exceptions import ObjectDoesNotExist
from django.db import migrations
def fill_tenant_id(apps, schema_editor):
ServiceSettings = apps.get_model('structure', 'ServiceSettings')
Tenant = apps.get_model('openstack', 'Tenant')
for service_settings in ServiceSettings.objects.filter(type='OpenStackTenant'):
if not service_settings.object_id:
continue
try:
tenant = Tenant.objects.get(id=service_settings.object_id)
except ObjectDoesNotExist:
pass
else:
if tenant.backend_id and not service_settings.options.get('tenant_id'):
service_settings.options['tenant_id'] = tenant.backend_id
service_settings.save(update_fields=['options'])
class Migration(migrations.Migration):
dependencies = [
('openstack_tenant', '0003_extend_description_limits'),
]
operations = [
migrations.RunPython(fill_tenant_id),
]
|
<commit_before>from django.db import migrations
def fill_tenant_id(apps, schema_editor):
ServiceSettings = apps.get_model('structure', 'ServiceSettings')
for service_settings in ServiceSettings.objects.filter(type='OpenStackTenant'):
tenant = service_settings.scope
if (
tenant
and tenant.backend_id
and not service_settings.options.get('tenant_id')
):
service_settings.options['tenant_id'] = tenant.backend_id
service_settings.save(update_fields=['options'])
class Migration(migrations.Migration):
dependencies = [
('openstack_tenant', '0003_extend_description_limits'),
]
operations = [
migrations.RunPython(fill_tenant_id),
]
<commit_msg>Fix migration: don't use virtual field scope.<commit_after>
|
from django.core.exceptions import ObjectDoesNotExist
from django.db import migrations
def fill_tenant_id(apps, schema_editor):
ServiceSettings = apps.get_model('structure', 'ServiceSettings')
Tenant = apps.get_model('openstack', 'Tenant')
for service_settings in ServiceSettings.objects.filter(type='OpenStackTenant'):
if not service_settings.object_id:
continue
try:
tenant = Tenant.objects.get(id=service_settings.object_id)
except ObjectDoesNotExist:
pass
else:
if tenant.backend_id and not service_settings.options.get('tenant_id'):
service_settings.options['tenant_id'] = tenant.backend_id
service_settings.save(update_fields=['options'])
class Migration(migrations.Migration):
dependencies = [
('openstack_tenant', '0003_extend_description_limits'),
]
operations = [
migrations.RunPython(fill_tenant_id),
]
|
from django.db import migrations
def fill_tenant_id(apps, schema_editor):
ServiceSettings = apps.get_model('structure', 'ServiceSettings')
for service_settings in ServiceSettings.objects.filter(type='OpenStackTenant'):
tenant = service_settings.scope
if (
tenant
and tenant.backend_id
and not service_settings.options.get('tenant_id')
):
service_settings.options['tenant_id'] = tenant.backend_id
service_settings.save(update_fields=['options'])
class Migration(migrations.Migration):
dependencies = [
('openstack_tenant', '0003_extend_description_limits'),
]
operations = [
migrations.RunPython(fill_tenant_id),
]
Fix migration: don't use virtual field scope.from django.core.exceptions import ObjectDoesNotExist
from django.db import migrations
def fill_tenant_id(apps, schema_editor):
ServiceSettings = apps.get_model('structure', 'ServiceSettings')
Tenant = apps.get_model('openstack', 'Tenant')
for service_settings in ServiceSettings.objects.filter(type='OpenStackTenant'):
if not service_settings.object_id:
continue
try:
tenant = Tenant.objects.get(id=service_settings.object_id)
except ObjectDoesNotExist:
pass
else:
if tenant.backend_id and not service_settings.options.get('tenant_id'):
service_settings.options['tenant_id'] = tenant.backend_id
service_settings.save(update_fields=['options'])
class Migration(migrations.Migration):
dependencies = [
('openstack_tenant', '0003_extend_description_limits'),
]
operations = [
migrations.RunPython(fill_tenant_id),
]
|
<commit_before>from django.db import migrations
def fill_tenant_id(apps, schema_editor):
ServiceSettings = apps.get_model('structure', 'ServiceSettings')
for service_settings in ServiceSettings.objects.filter(type='OpenStackTenant'):
tenant = service_settings.scope
if (
tenant
and tenant.backend_id
and not service_settings.options.get('tenant_id')
):
service_settings.options['tenant_id'] = tenant.backend_id
service_settings.save(update_fields=['options'])
class Migration(migrations.Migration):
dependencies = [
('openstack_tenant', '0003_extend_description_limits'),
]
operations = [
migrations.RunPython(fill_tenant_id),
]
<commit_msg>Fix migration: don't use virtual field scope.<commit_after>from django.core.exceptions import ObjectDoesNotExist
from django.db import migrations
def fill_tenant_id(apps, schema_editor):
ServiceSettings = apps.get_model('structure', 'ServiceSettings')
Tenant = apps.get_model('openstack', 'Tenant')
for service_settings in ServiceSettings.objects.filter(type='OpenStackTenant'):
if not service_settings.object_id:
continue
try:
tenant = Tenant.objects.get(id=service_settings.object_id)
except ObjectDoesNotExist:
pass
else:
if tenant.backend_id and not service_settings.options.get('tenant_id'):
service_settings.options['tenant_id'] = tenant.backend_id
service_settings.save(update_fields=['options'])
class Migration(migrations.Migration):
dependencies = [
('openstack_tenant', '0003_extend_description_limits'),
]
operations = [
migrations.RunPython(fill_tenant_id),
]
|
8bbdadc61611512dbd1bfbff2495ff0dee101054
|
adhocracy4/categories/forms.py
|
adhocracy4/categories/forms.py
|
from django import forms
from adhocracy4.categories import models as category_models
class CategorizableFieldMixin:
category_field_name = 'category'
def __init__(self, *args, **kwargs):
module = kwargs.pop('module')
super().__init__(*args, **kwargs)
queryset = category_models.Category.objects.filter(module=module)
self.fields[self.category_field_name] = forms.ModelChoiceField(
queryset=queryset,
empty_label=None,
required=False,
)
def show_categories(self):
module_has_categories = len(self.fields['category'].queryset) > 0
return module_has_categories
|
from adhocracy4.categories import models as category_models
class CategorizableFieldMixin:
category_field_name = 'category'
def __init__(self, *args, **kwargs):
module = kwargs.pop('module')
super().__init__(*args, **kwargs)
field = self.fields[self.category_field_name]
field.queryset = category_models.Category.objects.filter(module=module)
required = field.queryset.exists()
field.empty_label = None
field.required = required
field.widget.is_required = required
def show_categories(self):
field = self.fields[self.category_field_name]
module_has_categories = field.queryset.exists()
return module_has_categories
|
Modify generated category form field instead of reinitialize it
|
Modify generated category form field instead of reinitialize it
The category fields had not been translated as the field had been
reinitialized instead of modified. With this PR the auto generated field
(with its localized verbose_name) will be kept and adapted to the
filtered queryset.
Furthermore the required parameter is set to true if there are any
categories for the module.
|
Python
|
agpl-3.0
|
liqd/adhocracy4,liqd/adhocracy4,liqd/adhocracy4,liqd/adhocracy4
|
from django import forms
from adhocracy4.categories import models as category_models
class CategorizableFieldMixin:
category_field_name = 'category'
def __init__(self, *args, **kwargs):
module = kwargs.pop('module')
super().__init__(*args, **kwargs)
queryset = category_models.Category.objects.filter(module=module)
self.fields[self.category_field_name] = forms.ModelChoiceField(
queryset=queryset,
empty_label=None,
required=False,
)
def show_categories(self):
module_has_categories = len(self.fields['category'].queryset) > 0
return module_has_categories
Modify generated category form field instead of reinitialize it
The category fields had not been translated as the field had been
reinitialized instead of modified. With this PR the auto generated field
(with its localized verbose_name) will be kept and adapted to the
filtered queryset.
Furthermore the required parameter is set to true if there are any
categories for the module.
|
from adhocracy4.categories import models as category_models
class CategorizableFieldMixin:
category_field_name = 'category'
def __init__(self, *args, **kwargs):
module = kwargs.pop('module')
super().__init__(*args, **kwargs)
field = self.fields[self.category_field_name]
field.queryset = category_models.Category.objects.filter(module=module)
required = field.queryset.exists()
field.empty_label = None
field.required = required
field.widget.is_required = required
def show_categories(self):
field = self.fields[self.category_field_name]
module_has_categories = field.queryset.exists()
return module_has_categories
|
<commit_before>from django import forms
from adhocracy4.categories import models as category_models
class CategorizableFieldMixin:
category_field_name = 'category'
def __init__(self, *args, **kwargs):
module = kwargs.pop('module')
super().__init__(*args, **kwargs)
queryset = category_models.Category.objects.filter(module=module)
self.fields[self.category_field_name] = forms.ModelChoiceField(
queryset=queryset,
empty_label=None,
required=False,
)
def show_categories(self):
module_has_categories = len(self.fields['category'].queryset) > 0
return module_has_categories
<commit_msg>Modify generated category form field instead of reinitialize it
The category fields had not been translated as the field had been
reinitialized instead of modified. With this PR the auto generated field
(with its localized verbose_name) will be kept and adapted to the
filtered queryset.
Furthermore the required parameter is set to true if there are any
categories for the module.<commit_after>
|
from adhocracy4.categories import models as category_models
class CategorizableFieldMixin:
category_field_name = 'category'
def __init__(self, *args, **kwargs):
module = kwargs.pop('module')
super().__init__(*args, **kwargs)
field = self.fields[self.category_field_name]
field.queryset = category_models.Category.objects.filter(module=module)
required = field.queryset.exists()
field.empty_label = None
field.required = required
field.widget.is_required = required
def show_categories(self):
field = self.fields[self.category_field_name]
module_has_categories = field.queryset.exists()
return module_has_categories
|
from django import forms
from adhocracy4.categories import models as category_models
class CategorizableFieldMixin:
category_field_name = 'category'
def __init__(self, *args, **kwargs):
module = kwargs.pop('module')
super().__init__(*args, **kwargs)
queryset = category_models.Category.objects.filter(module=module)
self.fields[self.category_field_name] = forms.ModelChoiceField(
queryset=queryset,
empty_label=None,
required=False,
)
def show_categories(self):
module_has_categories = len(self.fields['category'].queryset) > 0
return module_has_categories
Modify generated category form field instead of reinitialize it
The category fields had not been translated as the field had been
reinitialized instead of modified. With this PR the auto generated field
(with its localized verbose_name) will be kept and adapted to the
filtered queryset.
Furthermore the required parameter is set to true if there are any
categories for the module.from adhocracy4.categories import models as category_models
class CategorizableFieldMixin:
category_field_name = 'category'
def __init__(self, *args, **kwargs):
module = kwargs.pop('module')
super().__init__(*args, **kwargs)
field = self.fields[self.category_field_name]
field.queryset = category_models.Category.objects.filter(module=module)
required = field.queryset.exists()
field.empty_label = None
field.required = required
field.widget.is_required = required
def show_categories(self):
field = self.fields[self.category_field_name]
module_has_categories = field.queryset.exists()
return module_has_categories
|
<commit_before>from django import forms
from adhocracy4.categories import models as category_models
class CategorizableFieldMixin:
category_field_name = 'category'
def __init__(self, *args, **kwargs):
module = kwargs.pop('module')
super().__init__(*args, **kwargs)
queryset = category_models.Category.objects.filter(module=module)
self.fields[self.category_field_name] = forms.ModelChoiceField(
queryset=queryset,
empty_label=None,
required=False,
)
def show_categories(self):
module_has_categories = len(self.fields['category'].queryset) > 0
return module_has_categories
<commit_msg>Modify generated category form field instead of reinitialize it
The category fields had not been translated as the field had been
reinitialized instead of modified. With this PR the auto generated field
(with its localized verbose_name) will be kept and adapted to the
filtered queryset.
Furthermore the required parameter is set to true if there are any
categories for the module.<commit_after>from adhocracy4.categories import models as category_models
class CategorizableFieldMixin:
category_field_name = 'category'
def __init__(self, *args, **kwargs):
module = kwargs.pop('module')
super().__init__(*args, **kwargs)
field = self.fields[self.category_field_name]
field.queryset = category_models.Category.objects.filter(module=module)
required = field.queryset.exists()
field.empty_label = None
field.required = required
field.widget.is_required = required
def show_categories(self):
field = self.fields[self.category_field_name]
module_has_categories = field.queryset.exists()
return module_has_categories
|
957f3e82f13dc8a9bd09d40a25c1f65847e144b8
|
aiohttp_json_api/decorators.py
|
aiohttp_json_api/decorators.py
|
from functools import wraps
from boltons.iterutils import first
from .context import RequestContext
from .errors import HTTPUnsupportedMediaType
from .const import JSONAPI_CONTENT_TYPE
def jsonapi_content(handler):
@wraps(handler)
async def wrapper(*args, **kwargs):
context = kwargs.get('context')
if context is None:
context = first(args, key=lambda v: isinstance(v, RequestContext))
assert context
if context.request.content_type != JSONAPI_CONTENT_TYPE:
raise HTTPUnsupportedMediaType(
detail=f"Only '{JSONAPI_CONTENT_TYPE}' "
f"content-type is acceptable."
)
return await handler(*args, **kwargs)
return wrapper
|
from functools import wraps
from aiohttp import web
from boltons.iterutils import first
from .context import RequestContext
from .errors import HTTPUnsupportedMediaType
from .const import JSONAPI, JSONAPI_CONTENT_TYPE
def jsonapi_content(handler):
@wraps(handler)
async def wrapper(*args, **kwargs):
request = kwargs.get('request')
if request is None:
request = first(args, key=lambda v: isinstance(v, web.Request))
context = request[JSONAPI]
assert context and isinstance(context, RequestContext)
if context.request.content_type != JSONAPI_CONTENT_TYPE:
raise HTTPUnsupportedMediaType(
detail=f"Only '{JSONAPI_CONTENT_TYPE}' "
f"content-type is acceptable."
)
return await handler(*args, **kwargs)
return wrapper
|
Fix bug with arguments handling in JSON API content decorator
|
Fix bug with arguments handling in JSON API content decorator
|
Python
|
mit
|
vovanbo/aiohttp_json_api
|
from functools import wraps
from boltons.iterutils import first
from .context import RequestContext
from .errors import HTTPUnsupportedMediaType
from .const import JSONAPI_CONTENT_TYPE
def jsonapi_content(handler):
@wraps(handler)
async def wrapper(*args, **kwargs):
context = kwargs.get('context')
if context is None:
context = first(args, key=lambda v: isinstance(v, RequestContext))
assert context
if context.request.content_type != JSONAPI_CONTENT_TYPE:
raise HTTPUnsupportedMediaType(
detail=f"Only '{JSONAPI_CONTENT_TYPE}' "
f"content-type is acceptable."
)
return await handler(*args, **kwargs)
return wrapper
Fix bug with arguments handling in JSON API content decorator
|
from functools import wraps
from aiohttp import web
from boltons.iterutils import first
from .context import RequestContext
from .errors import HTTPUnsupportedMediaType
from .const import JSONAPI, JSONAPI_CONTENT_TYPE
def jsonapi_content(handler):
@wraps(handler)
async def wrapper(*args, **kwargs):
request = kwargs.get('request')
if request is None:
request = first(args, key=lambda v: isinstance(v, web.Request))
context = request[JSONAPI]
assert context and isinstance(context, RequestContext)
if context.request.content_type != JSONAPI_CONTENT_TYPE:
raise HTTPUnsupportedMediaType(
detail=f"Only '{JSONAPI_CONTENT_TYPE}' "
f"content-type is acceptable."
)
return await handler(*args, **kwargs)
return wrapper
|
<commit_before>from functools import wraps
from boltons.iterutils import first
from .context import RequestContext
from .errors import HTTPUnsupportedMediaType
from .const import JSONAPI_CONTENT_TYPE
def jsonapi_content(handler):
@wraps(handler)
async def wrapper(*args, **kwargs):
context = kwargs.get('context')
if context is None:
context = first(args, key=lambda v: isinstance(v, RequestContext))
assert context
if context.request.content_type != JSONAPI_CONTENT_TYPE:
raise HTTPUnsupportedMediaType(
detail=f"Only '{JSONAPI_CONTENT_TYPE}' "
f"content-type is acceptable."
)
return await handler(*args, **kwargs)
return wrapper
<commit_msg>Fix bug with arguments handling in JSON API content decorator<commit_after>
|
from functools import wraps
from aiohttp import web
from boltons.iterutils import first
from .context import RequestContext
from .errors import HTTPUnsupportedMediaType
from .const import JSONAPI, JSONAPI_CONTENT_TYPE
def jsonapi_content(handler):
@wraps(handler)
async def wrapper(*args, **kwargs):
request = kwargs.get('request')
if request is None:
request = first(args, key=lambda v: isinstance(v, web.Request))
context = request[JSONAPI]
assert context and isinstance(context, RequestContext)
if context.request.content_type != JSONAPI_CONTENT_TYPE:
raise HTTPUnsupportedMediaType(
detail=f"Only '{JSONAPI_CONTENT_TYPE}' "
f"content-type is acceptable."
)
return await handler(*args, **kwargs)
return wrapper
|
from functools import wraps
from boltons.iterutils import first
from .context import RequestContext
from .errors import HTTPUnsupportedMediaType
from .const import JSONAPI_CONTENT_TYPE
def jsonapi_content(handler):
@wraps(handler)
async def wrapper(*args, **kwargs):
context = kwargs.get('context')
if context is None:
context = first(args, key=lambda v: isinstance(v, RequestContext))
assert context
if context.request.content_type != JSONAPI_CONTENT_TYPE:
raise HTTPUnsupportedMediaType(
detail=f"Only '{JSONAPI_CONTENT_TYPE}' "
f"content-type is acceptable."
)
return await handler(*args, **kwargs)
return wrapper
Fix bug with arguments handling in JSON API content decoratorfrom functools import wraps
from aiohttp import web
from boltons.iterutils import first
from .context import RequestContext
from .errors import HTTPUnsupportedMediaType
from .const import JSONAPI, JSONAPI_CONTENT_TYPE
def jsonapi_content(handler):
@wraps(handler)
async def wrapper(*args, **kwargs):
request = kwargs.get('request')
if request is None:
request = first(args, key=lambda v: isinstance(v, web.Request))
context = request[JSONAPI]
assert context and isinstance(context, RequestContext)
if context.request.content_type != JSONAPI_CONTENT_TYPE:
raise HTTPUnsupportedMediaType(
detail=f"Only '{JSONAPI_CONTENT_TYPE}' "
f"content-type is acceptable."
)
return await handler(*args, **kwargs)
return wrapper
|
<commit_before>from functools import wraps
from boltons.iterutils import first
from .context import RequestContext
from .errors import HTTPUnsupportedMediaType
from .const import JSONAPI_CONTENT_TYPE
def jsonapi_content(handler):
@wraps(handler)
async def wrapper(*args, **kwargs):
context = kwargs.get('context')
if context is None:
context = first(args, key=lambda v: isinstance(v, RequestContext))
assert context
if context.request.content_type != JSONAPI_CONTENT_TYPE:
raise HTTPUnsupportedMediaType(
detail=f"Only '{JSONAPI_CONTENT_TYPE}' "
f"content-type is acceptable."
)
return await handler(*args, **kwargs)
return wrapper
<commit_msg>Fix bug with arguments handling in JSON API content decorator<commit_after>from functools import wraps
from aiohttp import web
from boltons.iterutils import first
from .context import RequestContext
from .errors import HTTPUnsupportedMediaType
from .const import JSONAPI, JSONAPI_CONTENT_TYPE
def jsonapi_content(handler):
@wraps(handler)
async def wrapper(*args, **kwargs):
request = kwargs.get('request')
if request is None:
request = first(args, key=lambda v: isinstance(v, web.Request))
context = request[JSONAPI]
assert context and isinstance(context, RequestContext)
if context.request.content_type != JSONAPI_CONTENT_TYPE:
raise HTTPUnsupportedMediaType(
detail=f"Only '{JSONAPI_CONTENT_TYPE}' "
f"content-type is acceptable."
)
return await handler(*args, **kwargs)
return wrapper
|
fb59f2e0bd01d75c90ea3cc0089c24fc5db86e8e
|
config/jupyter/jupyter_notebook_config.py
|
config/jupyter/jupyter_notebook_config.py
|
import sys
sys.path.append('/root/.jupyter/extensions/')
c.JupyterApp.ip = '*'
c.JupyterApp.port = 80
c.JupyterApp.open_browser = False
c.JupyterApp.allow_credentials = True
c.JupyterApp.nbserver_extensions = ['jupyter_nbgallery.status', 'jupyter_nbgallery.post']
c.JupyterApp.reraise_server_extension_failures = True
c.JupyterApp.extra_static_paths = ['/root/.jupyter/static']
c.JupyterApp.extra_nbextensions_path = ['/root/.jupyter/extensions/']
c.JupyterApp.tornado_settings = {'static_url_prefix': '/Jupyter/static/'}
c.JupyterApp.allow_origin = 'https://nb.gallery'
# needed to receive notebooks from the gallery
c.JupyterApp.disable_check_xsrf = True
|
import json
import os
import sys
sys.path.append('/root/.jupyter/extensions/')
c.JupyterApp.ip = '*'
c.JupyterApp.port = 80
c.JupyterApp.open_browser = False
c.JupyterApp.allow_credentials = True
c.JupyterApp.nbserver_extensions = ['jupyter_nbgallery.status', 'jupyter_nbgallery.post']
c.JupyterApp.reraise_server_extension_failures = True
c.JupyterApp.extra_static_paths = ['/root/.jupyter/static']
c.JupyterApp.extra_nbextensions_path = ['/root/.jupyter/extensions/']
c.JupyterApp.tornado_settings = {'static_url_prefix': '/Jupyter/static/'}
c.JupyterApp.allow_origin = 'https://nb.gallery'
# needed to receive notebooks from the gallery
c.JupyterApp.disable_check_xsrf = True
# Override gallery location
nbgallery_url = os.getenv('NBGALLERY_URL')
if nbgallery_url:
print('Setting nbgallery url to %s' % nbgallery_url)
c.JupyterApp.allow_origin = nbgallery_url
config = json.loads(open('/root/.jupyter/nbconfig/common.json').read())
config['nbgallery']['url'] = nbgallery_url
with open('/root/.jupyter/nbconfig/common.json', 'w') as output:
output.write(json.dumps(config, indent=2))
|
Set $NBGALLERY_URL to override gallery location
|
Set $NBGALLERY_URL to override gallery location
|
Python
|
mit
|
jupyter-gallery/jupyter-docker,jupyter-gallery/jupyter-docker,jupyter-gallery/jupyter-docker
|
import sys
sys.path.append('/root/.jupyter/extensions/')
c.JupyterApp.ip = '*'
c.JupyterApp.port = 80
c.JupyterApp.open_browser = False
c.JupyterApp.allow_credentials = True
c.JupyterApp.nbserver_extensions = ['jupyter_nbgallery.status', 'jupyter_nbgallery.post']
c.JupyterApp.reraise_server_extension_failures = True
c.JupyterApp.extra_static_paths = ['/root/.jupyter/static']
c.JupyterApp.extra_nbextensions_path = ['/root/.jupyter/extensions/']
c.JupyterApp.tornado_settings = {'static_url_prefix': '/Jupyter/static/'}
c.JupyterApp.allow_origin = 'https://nb.gallery'
# needed to receive notebooks from the gallery
c.JupyterApp.disable_check_xsrf = True
Set $NBGALLERY_URL to override gallery location
|
import json
import os
import sys
sys.path.append('/root/.jupyter/extensions/')
c.JupyterApp.ip = '*'
c.JupyterApp.port = 80
c.JupyterApp.open_browser = False
c.JupyterApp.allow_credentials = True
c.JupyterApp.nbserver_extensions = ['jupyter_nbgallery.status', 'jupyter_nbgallery.post']
c.JupyterApp.reraise_server_extension_failures = True
c.JupyterApp.extra_static_paths = ['/root/.jupyter/static']
c.JupyterApp.extra_nbextensions_path = ['/root/.jupyter/extensions/']
c.JupyterApp.tornado_settings = {'static_url_prefix': '/Jupyter/static/'}
c.JupyterApp.allow_origin = 'https://nb.gallery'
# needed to receive notebooks from the gallery
c.JupyterApp.disable_check_xsrf = True
# Override gallery location
nbgallery_url = os.getenv('NBGALLERY_URL')
if nbgallery_url:
print('Setting nbgallery url to %s' % nbgallery_url)
c.JupyterApp.allow_origin = nbgallery_url
config = json.loads(open('/root/.jupyter/nbconfig/common.json').read())
config['nbgallery']['url'] = nbgallery_url
with open('/root/.jupyter/nbconfig/common.json', 'w') as output:
output.write(json.dumps(config, indent=2))
|
<commit_before>import sys
sys.path.append('/root/.jupyter/extensions/')
c.JupyterApp.ip = '*'
c.JupyterApp.port = 80
c.JupyterApp.open_browser = False
c.JupyterApp.allow_credentials = True
c.JupyterApp.nbserver_extensions = ['jupyter_nbgallery.status', 'jupyter_nbgallery.post']
c.JupyterApp.reraise_server_extension_failures = True
c.JupyterApp.extra_static_paths = ['/root/.jupyter/static']
c.JupyterApp.extra_nbextensions_path = ['/root/.jupyter/extensions/']
c.JupyterApp.tornado_settings = {'static_url_prefix': '/Jupyter/static/'}
c.JupyterApp.allow_origin = 'https://nb.gallery'
# needed to receive notebooks from the gallery
c.JupyterApp.disable_check_xsrf = True
<commit_msg>Set $NBGALLERY_URL to override gallery location<commit_after>
|
import json
import os
import sys
sys.path.append('/root/.jupyter/extensions/')
c.JupyterApp.ip = '*'
c.JupyterApp.port = 80
c.JupyterApp.open_browser = False
c.JupyterApp.allow_credentials = True
c.JupyterApp.nbserver_extensions = ['jupyter_nbgallery.status', 'jupyter_nbgallery.post']
c.JupyterApp.reraise_server_extension_failures = True
c.JupyterApp.extra_static_paths = ['/root/.jupyter/static']
c.JupyterApp.extra_nbextensions_path = ['/root/.jupyter/extensions/']
c.JupyterApp.tornado_settings = {'static_url_prefix': '/Jupyter/static/'}
c.JupyterApp.allow_origin = 'https://nb.gallery'
# needed to receive notebooks from the gallery
c.JupyterApp.disable_check_xsrf = True
# Override gallery location
nbgallery_url = os.getenv('NBGALLERY_URL')
if nbgallery_url:
print('Setting nbgallery url to %s' % nbgallery_url)
c.JupyterApp.allow_origin = nbgallery_url
config = json.loads(open('/root/.jupyter/nbconfig/common.json').read())
config['nbgallery']['url'] = nbgallery_url
with open('/root/.jupyter/nbconfig/common.json', 'w') as output:
output.write(json.dumps(config, indent=2))
|
import sys
sys.path.append('/root/.jupyter/extensions/')
c.JupyterApp.ip = '*'
c.JupyterApp.port = 80
c.JupyterApp.open_browser = False
c.JupyterApp.allow_credentials = True
c.JupyterApp.nbserver_extensions = ['jupyter_nbgallery.status', 'jupyter_nbgallery.post']
c.JupyterApp.reraise_server_extension_failures = True
c.JupyterApp.extra_static_paths = ['/root/.jupyter/static']
c.JupyterApp.extra_nbextensions_path = ['/root/.jupyter/extensions/']
c.JupyterApp.tornado_settings = {'static_url_prefix': '/Jupyter/static/'}
c.JupyterApp.allow_origin = 'https://nb.gallery'
# needed to receive notebooks from the gallery
c.JupyterApp.disable_check_xsrf = True
Set $NBGALLERY_URL to override gallery locationimport json
import os
import sys
sys.path.append('/root/.jupyter/extensions/')
c.JupyterApp.ip = '*'
c.JupyterApp.port = 80
c.JupyterApp.open_browser = False
c.JupyterApp.allow_credentials = True
c.JupyterApp.nbserver_extensions = ['jupyter_nbgallery.status', 'jupyter_nbgallery.post']
c.JupyterApp.reraise_server_extension_failures = True
c.JupyterApp.extra_static_paths = ['/root/.jupyter/static']
c.JupyterApp.extra_nbextensions_path = ['/root/.jupyter/extensions/']
c.JupyterApp.tornado_settings = {'static_url_prefix': '/Jupyter/static/'}
c.JupyterApp.allow_origin = 'https://nb.gallery'
# needed to receive notebooks from the gallery
c.JupyterApp.disable_check_xsrf = True
# Override gallery location
nbgallery_url = os.getenv('NBGALLERY_URL')
if nbgallery_url:
print('Setting nbgallery url to %s' % nbgallery_url)
c.JupyterApp.allow_origin = nbgallery_url
config = json.loads(open('/root/.jupyter/nbconfig/common.json').read())
config['nbgallery']['url'] = nbgallery_url
with open('/root/.jupyter/nbconfig/common.json', 'w') as output:
output.write(json.dumps(config, indent=2))
|
<commit_before>import sys
sys.path.append('/root/.jupyter/extensions/')
c.JupyterApp.ip = '*'
c.JupyterApp.port = 80
c.JupyterApp.open_browser = False
c.JupyterApp.allow_credentials = True
c.JupyterApp.nbserver_extensions = ['jupyter_nbgallery.status', 'jupyter_nbgallery.post']
c.JupyterApp.reraise_server_extension_failures = True
c.JupyterApp.extra_static_paths = ['/root/.jupyter/static']
c.JupyterApp.extra_nbextensions_path = ['/root/.jupyter/extensions/']
c.JupyterApp.tornado_settings = {'static_url_prefix': '/Jupyter/static/'}
c.JupyterApp.allow_origin = 'https://nb.gallery'
# needed to receive notebooks from the gallery
c.JupyterApp.disable_check_xsrf = True
<commit_msg>Set $NBGALLERY_URL to override gallery location<commit_after>import json
import os
import sys
sys.path.append('/root/.jupyter/extensions/')
c.JupyterApp.ip = '*'
c.JupyterApp.port = 80
c.JupyterApp.open_browser = False
c.JupyterApp.allow_credentials = True
c.JupyterApp.nbserver_extensions = ['jupyter_nbgallery.status', 'jupyter_nbgallery.post']
c.JupyterApp.reraise_server_extension_failures = True
c.JupyterApp.extra_static_paths = ['/root/.jupyter/static']
c.JupyterApp.extra_nbextensions_path = ['/root/.jupyter/extensions/']
c.JupyterApp.tornado_settings = {'static_url_prefix': '/Jupyter/static/'}
c.JupyterApp.allow_origin = 'https://nb.gallery'
# needed to receive notebooks from the gallery
c.JupyterApp.disable_check_xsrf = True
# Override gallery location
nbgallery_url = os.getenv('NBGALLERY_URL')
if nbgallery_url:
print('Setting nbgallery url to %s' % nbgallery_url)
c.JupyterApp.allow_origin = nbgallery_url
config = json.loads(open('/root/.jupyter/nbconfig/common.json').read())
config['nbgallery']['url'] = nbgallery_url
with open('/root/.jupyter/nbconfig/common.json', 'w') as output:
output.write(json.dumps(config, indent=2))
|
08c54be9e2e34b5655b2ea6f7778a83b606acade
|
src/lexus/lexical_simplifier.py
|
src/lexus/lexical_simplifier.py
|
__author__ = 's7a'
# All imports
from extras import Sanitizer
from replacer import Replacer
# The Lexical simplification class
class LexicalSimplifier:
# Constructor for the Lexical Simplifier
def __init__(self):
# Unused
pass
# Simplify a given content
@staticmethod
def simplify(content, lwlm_n):
words = [str(word) for word in content.split()]
length = len(words)
results = []
for i in range(length):
sanitized_word = Sanitizer.sanitize_word(words[i])
if sanitized_word == '':
continue
replacer = Replacer(lwlm_n)
result = replacer.detailed_replacement(sanitized_word)
results.append(result)
return results
|
__author__ = 's7a'
# All imports
from extras import Sanitizer
from replacer import Replacer
# The Lexical simplification class
class LexicalSimplifier:
# Constructor for the Lexical Simplifier
def __init__(self):
# Unused
pass
# Simplify a given content
@staticmethod
def simplify(content, lwlm_n):
words = [str(word) for word in content.split()]
length = len(words)
results = []
replacer = Replacer(lwlm_n)
for i in range(length):
sanitized_word = Sanitizer.sanitize_word(words[i])
if sanitized_word == '':
continue
result = replacer.detailed_replacement(sanitized_word)
results.append(result)
return results
|
Reduce the runtime of webapp api
|
Reduce the runtime of webapp api
|
Python
|
mit
|
Somsubhra/Simplify,Somsubhra/Simplify,Somsubhra/Simplify
|
__author__ = 's7a'
# All imports
from extras import Sanitizer
from replacer import Replacer
# The Lexical simplification class
class LexicalSimplifier:
# Constructor for the Lexical Simplifier
def __init__(self):
# Unused
pass
# Simplify a given content
@staticmethod
def simplify(content, lwlm_n):
words = [str(word) for word in content.split()]
length = len(words)
results = []
for i in range(length):
sanitized_word = Sanitizer.sanitize_word(words[i])
if sanitized_word == '':
continue
replacer = Replacer(lwlm_n)
result = replacer.detailed_replacement(sanitized_word)
results.append(result)
return resultsReduce the runtime of webapp api
|
__author__ = 's7a'
# All imports
from extras import Sanitizer
from replacer import Replacer
# The Lexical simplification class
class LexicalSimplifier:
# Constructor for the Lexical Simplifier
def __init__(self):
# Unused
pass
# Simplify a given content
@staticmethod
def simplify(content, lwlm_n):
words = [str(word) for word in content.split()]
length = len(words)
results = []
replacer = Replacer(lwlm_n)
for i in range(length):
sanitized_word = Sanitizer.sanitize_word(words[i])
if sanitized_word == '':
continue
result = replacer.detailed_replacement(sanitized_word)
results.append(result)
return results
|
<commit_before>__author__ = 's7a'
# All imports
from extras import Sanitizer
from replacer import Replacer
# The Lexical simplification class
class LexicalSimplifier:
# Constructor for the Lexical Simplifier
def __init__(self):
# Unused
pass
# Simplify a given content
@staticmethod
def simplify(content, lwlm_n):
words = [str(word) for word in content.split()]
length = len(words)
results = []
for i in range(length):
sanitized_word = Sanitizer.sanitize_word(words[i])
if sanitized_word == '':
continue
replacer = Replacer(lwlm_n)
result = replacer.detailed_replacement(sanitized_word)
results.append(result)
return results<commit_msg>Reduce the runtime of webapp api<commit_after>
|
__author__ = 's7a'
# All imports
from extras import Sanitizer
from replacer import Replacer
# The Lexical simplification class
class LexicalSimplifier:
# Constructor for the Lexical Simplifier
def __init__(self):
# Unused
pass
# Simplify a given content
@staticmethod
def simplify(content, lwlm_n):
words = [str(word) for word in content.split()]
length = len(words)
results = []
replacer = Replacer(lwlm_n)
for i in range(length):
sanitized_word = Sanitizer.sanitize_word(words[i])
if sanitized_word == '':
continue
result = replacer.detailed_replacement(sanitized_word)
results.append(result)
return results
|
__author__ = 's7a'
# All imports
from extras import Sanitizer
from replacer import Replacer
# The Lexical simplification class
class LexicalSimplifier:
# Constructor for the Lexical Simplifier
def __init__(self):
# Unused
pass
# Simplify a given content
@staticmethod
def simplify(content, lwlm_n):
words = [str(word) for word in content.split()]
length = len(words)
results = []
for i in range(length):
sanitized_word = Sanitizer.sanitize_word(words[i])
if sanitized_word == '':
continue
replacer = Replacer(lwlm_n)
result = replacer.detailed_replacement(sanitized_word)
results.append(result)
return resultsReduce the runtime of webapp api__author__ = 's7a'
# All imports
from extras import Sanitizer
from replacer import Replacer
# The Lexical simplification class
class LexicalSimplifier:
# Constructor for the Lexical Simplifier
def __init__(self):
# Unused
pass
# Simplify a given content
@staticmethod
def simplify(content, lwlm_n):
words = [str(word) for word in content.split()]
length = len(words)
results = []
replacer = Replacer(lwlm_n)
for i in range(length):
sanitized_word = Sanitizer.sanitize_word(words[i])
if sanitized_word == '':
continue
result = replacer.detailed_replacement(sanitized_word)
results.append(result)
return results
|
<commit_before>__author__ = 's7a'
# All imports
from extras import Sanitizer
from replacer import Replacer
# The Lexical simplification class
class LexicalSimplifier:
# Constructor for the Lexical Simplifier
def __init__(self):
# Unused
pass
# Simplify a given content
@staticmethod
def simplify(content, lwlm_n):
words = [str(word) for word in content.split()]
length = len(words)
results = []
for i in range(length):
sanitized_word = Sanitizer.sanitize_word(words[i])
if sanitized_word == '':
continue
replacer = Replacer(lwlm_n)
result = replacer.detailed_replacement(sanitized_word)
results.append(result)
return results<commit_msg>Reduce the runtime of webapp api<commit_after>__author__ = 's7a'
# All imports
from extras import Sanitizer
from replacer import Replacer
# The Lexical simplification class
class LexicalSimplifier:
# Constructor for the Lexical Simplifier
def __init__(self):
# Unused
pass
# Simplify a given content
@staticmethod
def simplify(content, lwlm_n):
words = [str(word) for word in content.split()]
length = len(words)
results = []
replacer = Replacer(lwlm_n)
for i in range(length):
sanitized_word = Sanitizer.sanitize_word(words[i])
if sanitized_word == '':
continue
result = replacer.detailed_replacement(sanitized_word)
results.append(result)
return results
|
6d1612698c2e42ab60d521915f31ff08832e3745
|
waterbutler/providers/dropbox/settings.py
|
waterbutler/providers/dropbox/settings.py
|
try:
from waterbutler import settings
except ImportError:
settings = {}
config = settings.get('DROPBOX_PROVIDER_CONFIG', {})
BASE_URL = config.get('BASE_URL', 'https://api.dropbox.com/1/')
BASE_CONTENT_URL = config.get('BASE_CONTENT_URL', 'https://api-content.dropbox.com/1/')
|
try:
from waterbutler import settings
except ImportError:
settings = {}
config = settings.get('DROPBOX_PROVIDER_CONFIG', {})
BASE_URL = config.get('BASE_URL', 'https://api.dropboxapi.com/1/')
BASE_CONTENT_URL = config.get('BASE_CONTENT_URL', 'https://content.dropboxapi.com/1/')
|
Update drobox api urls h/t @felliott
|
Update drobox api urls h/t @felliott
|
Python
|
apache-2.0
|
RCOSDP/waterbutler,rdhyee/waterbutler,TomBaxter/waterbutler,felliott/waterbutler,CenterForOpenScience/waterbutler,Johnetordoff/waterbutler
|
try:
from waterbutler import settings
except ImportError:
settings = {}
config = settings.get('DROPBOX_PROVIDER_CONFIG', {})
BASE_URL = config.get('BASE_URL', 'https://api.dropbox.com/1/')
BASE_CONTENT_URL = config.get('BASE_CONTENT_URL', 'https://api-content.dropbox.com/1/')
Update drobox api urls h/t @felliott
|
try:
from waterbutler import settings
except ImportError:
settings = {}
config = settings.get('DROPBOX_PROVIDER_CONFIG', {})
BASE_URL = config.get('BASE_URL', 'https://api.dropboxapi.com/1/')
BASE_CONTENT_URL = config.get('BASE_CONTENT_URL', 'https://content.dropboxapi.com/1/')
|
<commit_before>try:
from waterbutler import settings
except ImportError:
settings = {}
config = settings.get('DROPBOX_PROVIDER_CONFIG', {})
BASE_URL = config.get('BASE_URL', 'https://api.dropbox.com/1/')
BASE_CONTENT_URL = config.get('BASE_CONTENT_URL', 'https://api-content.dropbox.com/1/')
<commit_msg>Update drobox api urls h/t @felliott<commit_after>
|
try:
from waterbutler import settings
except ImportError:
settings = {}
config = settings.get('DROPBOX_PROVIDER_CONFIG', {})
BASE_URL = config.get('BASE_URL', 'https://api.dropboxapi.com/1/')
BASE_CONTENT_URL = config.get('BASE_CONTENT_URL', 'https://content.dropboxapi.com/1/')
|
try:
from waterbutler import settings
except ImportError:
settings = {}
config = settings.get('DROPBOX_PROVIDER_CONFIG', {})
BASE_URL = config.get('BASE_URL', 'https://api.dropbox.com/1/')
BASE_CONTENT_URL = config.get('BASE_CONTENT_URL', 'https://api-content.dropbox.com/1/')
Update drobox api urls h/t @felliotttry:
from waterbutler import settings
except ImportError:
settings = {}
config = settings.get('DROPBOX_PROVIDER_CONFIG', {})
BASE_URL = config.get('BASE_URL', 'https://api.dropboxapi.com/1/')
BASE_CONTENT_URL = config.get('BASE_CONTENT_URL', 'https://content.dropboxapi.com/1/')
|
<commit_before>try:
from waterbutler import settings
except ImportError:
settings = {}
config = settings.get('DROPBOX_PROVIDER_CONFIG', {})
BASE_URL = config.get('BASE_URL', 'https://api.dropbox.com/1/')
BASE_CONTENT_URL = config.get('BASE_CONTENT_URL', 'https://api-content.dropbox.com/1/')
<commit_msg>Update drobox api urls h/t @felliott<commit_after>try:
from waterbutler import settings
except ImportError:
settings = {}
config = settings.get('DROPBOX_PROVIDER_CONFIG', {})
BASE_URL = config.get('BASE_URL', 'https://api.dropboxapi.com/1/')
BASE_CONTENT_URL = config.get('BASE_CONTENT_URL', 'https://content.dropboxapi.com/1/')
|
9d78a7be6ea922844bc9c6a0795af8d7b7a247a3
|
bl/text.py
|
bl/text.py
|
import os, shutil, tempfile
from bl.file import File
from bl.string import String
class Text(File):
def __init__(self, fn=None, text=None, encoding='UTF-8', **args):
File.__init__(self, fn=fn, encoding=encoding, **args)
if text is not None:
self.text = text
elif fn is not None and os.path.exists(fn):
self.text = String(self.read().decode(encoding))
else:
self.text = String("")
def write(self, fn=None, text=None, encoding='UTF-8', data=None, **args):
if data is None:
try:
data = (text or self.text or '').encode(encoding)
except:
data = (text or self.text or '').encode()
File.write(self, fn=fn, data=data, **args)
|
import os, shutil, tempfile
from bl.file import File
from bl.string import String
class Text(File):
def __init__(self, fn=None, text=None, encoding='UTF-8', **args):
File.__init__(self, fn=fn, encoding=encoding, **args)
if text is not None:
self.text = text
elif fn is not None and os.path.exists(fn):
self.text = String(self.read().decode(encoding))
else:
self.text = String("")
def write(self, fn=None, text=None, encoding='UTF-8', **args):
try:
data = (text or self.text or '').encode(encoding)
except:
data = (text or self.text or '').encode()
File.write(self, fn=fn, data=data, **args)
|
Revert "allow to write Text with raw data"
|
Revert "allow to write Text with raw data"
This reverts commit d05df9ea67bc626adc7a4940c9bad4881d672a38.
|
Python
|
mpl-2.0
|
BlackEarth/bl,BlackEarth/bl
|
import os, shutil, tempfile
from bl.file import File
from bl.string import String
class Text(File):
def __init__(self, fn=None, text=None, encoding='UTF-8', **args):
File.__init__(self, fn=fn, encoding=encoding, **args)
if text is not None:
self.text = text
elif fn is not None and os.path.exists(fn):
self.text = String(self.read().decode(encoding))
else:
self.text = String("")
def write(self, fn=None, text=None, encoding='UTF-8', data=None, **args):
if data is None:
try:
data = (text or self.text or '').encode(encoding)
except:
data = (text or self.text or '').encode()
File.write(self, fn=fn, data=data, **args)
Revert "allow to write Text with raw data"
This reverts commit d05df9ea67bc626adc7a4940c9bad4881d672a38.
|
import os, shutil, tempfile
from bl.file import File
from bl.string import String
class Text(File):
def __init__(self, fn=None, text=None, encoding='UTF-8', **args):
File.__init__(self, fn=fn, encoding=encoding, **args)
if text is not None:
self.text = text
elif fn is not None and os.path.exists(fn):
self.text = String(self.read().decode(encoding))
else:
self.text = String("")
def write(self, fn=None, text=None, encoding='UTF-8', **args):
try:
data = (text or self.text or '').encode(encoding)
except:
data = (text or self.text or '').encode()
File.write(self, fn=fn, data=data, **args)
|
<commit_before>
import os, shutil, tempfile
from bl.file import File
from bl.string import String
class Text(File):
def __init__(self, fn=None, text=None, encoding='UTF-8', **args):
File.__init__(self, fn=fn, encoding=encoding, **args)
if text is not None:
self.text = text
elif fn is not None and os.path.exists(fn):
self.text = String(self.read().decode(encoding))
else:
self.text = String("")
def write(self, fn=None, text=None, encoding='UTF-8', data=None, **args):
if data is None:
try:
data = (text or self.text or '').encode(encoding)
except:
data = (text or self.text or '').encode()
File.write(self, fn=fn, data=data, **args)
<commit_msg>Revert "allow to write Text with raw data"
This reverts commit d05df9ea67bc626adc7a4940c9bad4881d672a38.<commit_after>
|
import os, shutil, tempfile
from bl.file import File
from bl.string import String
class Text(File):
def __init__(self, fn=None, text=None, encoding='UTF-8', **args):
File.__init__(self, fn=fn, encoding=encoding, **args)
if text is not None:
self.text = text
elif fn is not None and os.path.exists(fn):
self.text = String(self.read().decode(encoding))
else:
self.text = String("")
def write(self, fn=None, text=None, encoding='UTF-8', **args):
try:
data = (text or self.text or '').encode(encoding)
except:
data = (text or self.text or '').encode()
File.write(self, fn=fn, data=data, **args)
|
import os, shutil, tempfile
from bl.file import File
from bl.string import String
class Text(File):
def __init__(self, fn=None, text=None, encoding='UTF-8', **args):
File.__init__(self, fn=fn, encoding=encoding, **args)
if text is not None:
self.text = text
elif fn is not None and os.path.exists(fn):
self.text = String(self.read().decode(encoding))
else:
self.text = String("")
def write(self, fn=None, text=None, encoding='UTF-8', data=None, **args):
if data is None:
try:
data = (text or self.text or '').encode(encoding)
except:
data = (text or self.text or '').encode()
File.write(self, fn=fn, data=data, **args)
Revert "allow to write Text with raw data"
This reverts commit d05df9ea67bc626adc7a4940c9bad4881d672a38.
import os, shutil, tempfile
from bl.file import File
from bl.string import String
class Text(File):
def __init__(self, fn=None, text=None, encoding='UTF-8', **args):
File.__init__(self, fn=fn, encoding=encoding, **args)
if text is not None:
self.text = text
elif fn is not None and os.path.exists(fn):
self.text = String(self.read().decode(encoding))
else:
self.text = String("")
def write(self, fn=None, text=None, encoding='UTF-8', **args):
try:
data = (text or self.text or '').encode(encoding)
except:
data = (text or self.text or '').encode()
File.write(self, fn=fn, data=data, **args)
|
<commit_before>
import os, shutil, tempfile
from bl.file import File
from bl.string import String
class Text(File):
def __init__(self, fn=None, text=None, encoding='UTF-8', **args):
File.__init__(self, fn=fn, encoding=encoding, **args)
if text is not None:
self.text = text
elif fn is not None and os.path.exists(fn):
self.text = String(self.read().decode(encoding))
else:
self.text = String("")
def write(self, fn=None, text=None, encoding='UTF-8', data=None, **args):
if data is None:
try:
data = (text or self.text or '').encode(encoding)
except:
data = (text or self.text or '').encode()
File.write(self, fn=fn, data=data, **args)
<commit_msg>Revert "allow to write Text with raw data"
This reverts commit d05df9ea67bc626adc7a4940c9bad4881d672a38.<commit_after>
import os, shutil, tempfile
from bl.file import File
from bl.string import String
class Text(File):
def __init__(self, fn=None, text=None, encoding='UTF-8', **args):
File.__init__(self, fn=fn, encoding=encoding, **args)
if text is not None:
self.text = text
elif fn is not None and os.path.exists(fn):
self.text = String(self.read().decode(encoding))
else:
self.text = String("")
def write(self, fn=None, text=None, encoding='UTF-8', **args):
try:
data = (text or self.text or '').encode(encoding)
except:
data = (text or self.text or '').encode()
File.write(self, fn=fn, data=data, **args)
|
c42092f643bf34c997f2b964e3d132ed95012755
|
scipy/testing/nulltester.py
|
scipy/testing/nulltester.py
|
''' Null tester (when nose not importable)
Merely returns error reporting lack of nose package
See pkgtester, nosetester modules
'''
nose_url = 'http://somethingaboutorange.com/mrl/projects/nose'
class NullTester(object):
def __init__(self, *args, **kwargs):
pass
def test(self, labels=None, *args, **kwargs):
raise ImportError, 'Need nose for tests - see %s' % nose_url
|
''' Null tester (when nose not importable)
Merely returns error reporting lack of nose package
See pkgtester, nosetester modules
'''
nose_url = 'http://somethingaboutorange.com/mrl/projects/nose'
class NullTester(object):
def __init__(self, *args, **kwargs):
pass
def test(self, labels=None, *args, **kwargs):
raise ImportError, 'Need nose for tests - see %s' % nose_url
def bench(self, labels=None, *args, **kwargs):
raise ImportError, 'Need nose for benchmarks - see %s' % nose_url
|
Fix bench error on scipy import when nose is not installed
|
Fix bench error on scipy import when nose is not installed
git-svn-id: 003f22d385e25de9cff933a5ea4efd77cb5e7b28@3851 d6536bca-fef9-0310-8506-e4c0a848fbcf
|
Python
|
bsd-3-clause
|
lesserwhirls/scipy-cwt,scipy/scipy-svn,jasonmccampbell/scipy-refactor,scipy/scipy-svn,jasonmccampbell/scipy-refactor,scipy/scipy-svn,jasonmccampbell/scipy-refactor,lesserwhirls/scipy-cwt,lesserwhirls/scipy-cwt,jasonmccampbell/scipy-refactor,scipy/scipy-svn,lesserwhirls/scipy-cwt
|
''' Null tester (when nose not importable)
Merely returns error reporting lack of nose package
See pkgtester, nosetester modules
'''
nose_url = 'http://somethingaboutorange.com/mrl/projects/nose'
class NullTester(object):
def __init__(self, *args, **kwargs):
pass
def test(self, labels=None, *args, **kwargs):
raise ImportError, 'Need nose for tests - see %s' % nose_url
Fix bench error on scipy import when nose is not installed
git-svn-id: 003f22d385e25de9cff933a5ea4efd77cb5e7b28@3851 d6536bca-fef9-0310-8506-e4c0a848fbcf
|
''' Null tester (when nose not importable)
Merely returns error reporting lack of nose package
See pkgtester, nosetester modules
'''
nose_url = 'http://somethingaboutorange.com/mrl/projects/nose'
class NullTester(object):
def __init__(self, *args, **kwargs):
pass
def test(self, labels=None, *args, **kwargs):
raise ImportError, 'Need nose for tests - see %s' % nose_url
def bench(self, labels=None, *args, **kwargs):
raise ImportError, 'Need nose for benchmarks - see %s' % nose_url
|
<commit_before>''' Null tester (when nose not importable)
Merely returns error reporting lack of nose package
See pkgtester, nosetester modules
'''
nose_url = 'http://somethingaboutorange.com/mrl/projects/nose'
class NullTester(object):
def __init__(self, *args, **kwargs):
pass
def test(self, labels=None, *args, **kwargs):
raise ImportError, 'Need nose for tests - see %s' % nose_url
<commit_msg>Fix bench error on scipy import when nose is not installed
git-svn-id: 003f22d385e25de9cff933a5ea4efd77cb5e7b28@3851 d6536bca-fef9-0310-8506-e4c0a848fbcf<commit_after>
|
''' Null tester (when nose not importable)
Merely returns error reporting lack of nose package
See pkgtester, nosetester modules
'''
nose_url = 'http://somethingaboutorange.com/mrl/projects/nose'
class NullTester(object):
def __init__(self, *args, **kwargs):
pass
def test(self, labels=None, *args, **kwargs):
raise ImportError, 'Need nose for tests - see %s' % nose_url
def bench(self, labels=None, *args, **kwargs):
raise ImportError, 'Need nose for benchmarks - see %s' % nose_url
|
''' Null tester (when nose not importable)
Merely returns error reporting lack of nose package
See pkgtester, nosetester modules
'''
nose_url = 'http://somethingaboutorange.com/mrl/projects/nose'
class NullTester(object):
def __init__(self, *args, **kwargs):
pass
def test(self, labels=None, *args, **kwargs):
raise ImportError, 'Need nose for tests - see %s' % nose_url
Fix bench error on scipy import when nose is not installed
git-svn-id: 003f22d385e25de9cff933a5ea4efd77cb5e7b28@3851 d6536bca-fef9-0310-8506-e4c0a848fbcf''' Null tester (when nose not importable)
Merely returns error reporting lack of nose package
See pkgtester, nosetester modules
'''
nose_url = 'http://somethingaboutorange.com/mrl/projects/nose'
class NullTester(object):
def __init__(self, *args, **kwargs):
pass
def test(self, labels=None, *args, **kwargs):
raise ImportError, 'Need nose for tests - see %s' % nose_url
def bench(self, labels=None, *args, **kwargs):
raise ImportError, 'Need nose for benchmarks - see %s' % nose_url
|
<commit_before>''' Null tester (when nose not importable)
Merely returns error reporting lack of nose package
See pkgtester, nosetester modules
'''
nose_url = 'http://somethingaboutorange.com/mrl/projects/nose'
class NullTester(object):
def __init__(self, *args, **kwargs):
pass
def test(self, labels=None, *args, **kwargs):
raise ImportError, 'Need nose for tests - see %s' % nose_url
<commit_msg>Fix bench error on scipy import when nose is not installed
git-svn-id: 003f22d385e25de9cff933a5ea4efd77cb5e7b28@3851 d6536bca-fef9-0310-8506-e4c0a848fbcf<commit_after>''' Null tester (when nose not importable)
Merely returns error reporting lack of nose package
See pkgtester, nosetester modules
'''
nose_url = 'http://somethingaboutorange.com/mrl/projects/nose'
class NullTester(object):
def __init__(self, *args, **kwargs):
pass
def test(self, labels=None, *args, **kwargs):
raise ImportError, 'Need nose for tests - see %s' % nose_url
def bench(self, labels=None, *args, **kwargs):
raise ImportError, 'Need nose for benchmarks - see %s' % nose_url
|
50e972491e7fbe62045a6bda4351428769103c81
|
annotateit/model/annotation.py
|
annotateit/model/annotation.py
|
from flask import g
from annotator.annotation import Annotation as Annotation_
from annotator.authz import permissions_filter
class Annotation(Annotation_):
@classmethod
def stats_for_user(cls, user):
stats = {}
q = {'query': {'match_all': {}},
'filter': {'and': [permissions_filter(g.user),
{'or': [{'term': {'user': user.id}},
{'term': {'user.id': user.id}}]}]}}
stats['num_annotations'] = cls.es.conn.count({'filtered': q})['count']
uris_res = cls.es.conn.search({
'query': {'filtered': q},
'facets': {'uri': {'terms': {'field': 'uri'}}},
'size': 0
})
stats['num_uris'] = len(uris_res['facets']['uri']['terms'])
return stats
|
from flask import g
from annotator.annotation import Annotation as Annotation_
from annotator.authz import permissions_filter
class Annotation(Annotation_):
@classmethod
def stats_for_user(cls, user):
stats = {}
q = {'query': {'match_all': {}},
'filter': {'and': [permissions_filter(g.user),
{'or': [{'term': {'user': user.id}},
{'term': {'user.id': user.id}}]}]}}
stats['num_annotations'] = cls.es.conn.count({'filtered': q})['count']
uris_res = cls.es.conn.search_raw({
'query': {'filtered': q},
'facets': {'uri': {'terms': {'field': 'uri'}}},
'size': 0
})
stats['num_uris'] = len(uris_res['facets']['uri']['terms'])
return stats
|
Update for compatibility with pyes==0.19.1
|
Update for compatibility with pyes==0.19.1
|
Python
|
agpl-3.0
|
openannotation/annotateit,openannotation/annotateit
|
from flask import g
from annotator.annotation import Annotation as Annotation_
from annotator.authz import permissions_filter
class Annotation(Annotation_):
@classmethod
def stats_for_user(cls, user):
stats = {}
q = {'query': {'match_all': {}},
'filter': {'and': [permissions_filter(g.user),
{'or': [{'term': {'user': user.id}},
{'term': {'user.id': user.id}}]}]}}
stats['num_annotations'] = cls.es.conn.count({'filtered': q})['count']
uris_res = cls.es.conn.search({
'query': {'filtered': q},
'facets': {'uri': {'terms': {'field': 'uri'}}},
'size': 0
})
stats['num_uris'] = len(uris_res['facets']['uri']['terms'])
return stats
Update for compatibility with pyes==0.19.1
|
from flask import g
from annotator.annotation import Annotation as Annotation_
from annotator.authz import permissions_filter
class Annotation(Annotation_):
@classmethod
def stats_for_user(cls, user):
stats = {}
q = {'query': {'match_all': {}},
'filter': {'and': [permissions_filter(g.user),
{'or': [{'term': {'user': user.id}},
{'term': {'user.id': user.id}}]}]}}
stats['num_annotations'] = cls.es.conn.count({'filtered': q})['count']
uris_res = cls.es.conn.search_raw({
'query': {'filtered': q},
'facets': {'uri': {'terms': {'field': 'uri'}}},
'size': 0
})
stats['num_uris'] = len(uris_res['facets']['uri']['terms'])
return stats
|
<commit_before>from flask import g
from annotator.annotation import Annotation as Annotation_
from annotator.authz import permissions_filter
class Annotation(Annotation_):
@classmethod
def stats_for_user(cls, user):
stats = {}
q = {'query': {'match_all': {}},
'filter': {'and': [permissions_filter(g.user),
{'or': [{'term': {'user': user.id}},
{'term': {'user.id': user.id}}]}]}}
stats['num_annotations'] = cls.es.conn.count({'filtered': q})['count']
uris_res = cls.es.conn.search({
'query': {'filtered': q},
'facets': {'uri': {'terms': {'field': 'uri'}}},
'size': 0
})
stats['num_uris'] = len(uris_res['facets']['uri']['terms'])
return stats
<commit_msg>Update for compatibility with pyes==0.19.1<commit_after>
|
from flask import g
from annotator.annotation import Annotation as Annotation_
from annotator.authz import permissions_filter
class Annotation(Annotation_):
@classmethod
def stats_for_user(cls, user):
stats = {}
q = {'query': {'match_all': {}},
'filter': {'and': [permissions_filter(g.user),
{'or': [{'term': {'user': user.id}},
{'term': {'user.id': user.id}}]}]}}
stats['num_annotations'] = cls.es.conn.count({'filtered': q})['count']
uris_res = cls.es.conn.search_raw({
'query': {'filtered': q},
'facets': {'uri': {'terms': {'field': 'uri'}}},
'size': 0
})
stats['num_uris'] = len(uris_res['facets']['uri']['terms'])
return stats
|
from flask import g
from annotator.annotation import Annotation as Annotation_
from annotator.authz import permissions_filter
class Annotation(Annotation_):
@classmethod
def stats_for_user(cls, user):
stats = {}
q = {'query': {'match_all': {}},
'filter': {'and': [permissions_filter(g.user),
{'or': [{'term': {'user': user.id}},
{'term': {'user.id': user.id}}]}]}}
stats['num_annotations'] = cls.es.conn.count({'filtered': q})['count']
uris_res = cls.es.conn.search({
'query': {'filtered': q},
'facets': {'uri': {'terms': {'field': 'uri'}}},
'size': 0
})
stats['num_uris'] = len(uris_res['facets']['uri']['terms'])
return stats
Update for compatibility with pyes==0.19.1from flask import g
from annotator.annotation import Annotation as Annotation_
from annotator.authz import permissions_filter
class Annotation(Annotation_):
@classmethod
def stats_for_user(cls, user):
stats = {}
q = {'query': {'match_all': {}},
'filter': {'and': [permissions_filter(g.user),
{'or': [{'term': {'user': user.id}},
{'term': {'user.id': user.id}}]}]}}
stats['num_annotations'] = cls.es.conn.count({'filtered': q})['count']
uris_res = cls.es.conn.search_raw({
'query': {'filtered': q},
'facets': {'uri': {'terms': {'field': 'uri'}}},
'size': 0
})
stats['num_uris'] = len(uris_res['facets']['uri']['terms'])
return stats
|
<commit_before>from flask import g
from annotator.annotation import Annotation as Annotation_
from annotator.authz import permissions_filter
class Annotation(Annotation_):
@classmethod
def stats_for_user(cls, user):
stats = {}
q = {'query': {'match_all': {}},
'filter': {'and': [permissions_filter(g.user),
{'or': [{'term': {'user': user.id}},
{'term': {'user.id': user.id}}]}]}}
stats['num_annotations'] = cls.es.conn.count({'filtered': q})['count']
uris_res = cls.es.conn.search({
'query': {'filtered': q},
'facets': {'uri': {'terms': {'field': 'uri'}}},
'size': 0
})
stats['num_uris'] = len(uris_res['facets']['uri']['terms'])
return stats
<commit_msg>Update for compatibility with pyes==0.19.1<commit_after>from flask import g
from annotator.annotation import Annotation as Annotation_
from annotator.authz import permissions_filter
class Annotation(Annotation_):
@classmethod
def stats_for_user(cls, user):
stats = {}
q = {'query': {'match_all': {}},
'filter': {'and': [permissions_filter(g.user),
{'or': [{'term': {'user': user.id}},
{'term': {'user.id': user.id}}]}]}}
stats['num_annotations'] = cls.es.conn.count({'filtered': q})['count']
uris_res = cls.es.conn.search_raw({
'query': {'filtered': q},
'facets': {'uri': {'terms': {'field': 'uri'}}},
'size': 0
})
stats['num_uris'] = len(uris_res['facets']['uri']['terms'])
return stats
|
d7a227ae5f0f53b5c620864df08c7b883402e968
|
netmiko/brocade/brocade_nos_ssh.py
|
netmiko/brocade/brocade_nos_ssh.py
|
"""Support for Brocade NOS/VDX."""
from __future__ import unicode_literals
import time
from netmiko.cisco_base_connection import CiscoSSHConnection
class BrocadeNosSSH(CiscoSSHConnection):
"""Support for Brocade NOS/VDX."""
def enable(self, *args, **kwargs):
"""No enable mode on Brocade VDX."""
pass
def exit_enable_mode(self, *args, **kwargs):
"""No enable mode on Brocade VDX."""
pass
def special_login_handler(self, delay_factor=1):
"""Adding a delay after login."""
delay_factor = self.select_delay_factor(delay_factor)
self.write_channel(self.RETURN)
time.sleep(1 * delay_factor)
|
"""Support for Brocade NOS/VDX."""
from __future__ import unicode_literals
import time
from netmiko.cisco_base_connection import CiscoSSHConnection
class BrocadeNosSSH(CiscoSSHConnection):
"""Support for Brocade NOS/VDX."""
def enable(self, *args, **kwargs):
"""No enable mode on Brocade VDX."""
pass
def exit_enable_mode(self, *args, **kwargs):
"""No enable mode on Brocade VDX."""
pass
def special_login_handler(self, delay_factor=1):
"""Adding a delay after login."""
delay_factor = self.select_delay_factor(delay_factor)
self.write_channel(self.RETURN)
time.sleep(1 * delay_factor)
def save_config(self):
"""Save Config for Brocade VDX."""
self.send_command('copy running-config startup-config', '[Y/N]')
self.send_command('y')
|
Add save_config for brocade VDX
|
Add save_config for brocade VDX
|
Python
|
mit
|
ktbyers/netmiko,ktbyers/netmiko
|
"""Support for Brocade NOS/VDX."""
from __future__ import unicode_literals
import time
from netmiko.cisco_base_connection import CiscoSSHConnection
class BrocadeNosSSH(CiscoSSHConnection):
"""Support for Brocade NOS/VDX."""
def enable(self, *args, **kwargs):
"""No enable mode on Brocade VDX."""
pass
def exit_enable_mode(self, *args, **kwargs):
"""No enable mode on Brocade VDX."""
pass
def special_login_handler(self, delay_factor=1):
"""Adding a delay after login."""
delay_factor = self.select_delay_factor(delay_factor)
self.write_channel(self.RETURN)
time.sleep(1 * delay_factor)
Add save_config for brocade VDX
|
"""Support for Brocade NOS/VDX."""
from __future__ import unicode_literals
import time
from netmiko.cisco_base_connection import CiscoSSHConnection
class BrocadeNosSSH(CiscoSSHConnection):
"""Support for Brocade NOS/VDX."""
def enable(self, *args, **kwargs):
"""No enable mode on Brocade VDX."""
pass
def exit_enable_mode(self, *args, **kwargs):
"""No enable mode on Brocade VDX."""
pass
def special_login_handler(self, delay_factor=1):
"""Adding a delay after login."""
delay_factor = self.select_delay_factor(delay_factor)
self.write_channel(self.RETURN)
time.sleep(1 * delay_factor)
def save_config(self):
"""Save Config for Brocade VDX."""
self.send_command('copy running-config startup-config', '[Y/N]')
self.send_command('y')
|
<commit_before>"""Support for Brocade NOS/VDX."""
from __future__ import unicode_literals
import time
from netmiko.cisco_base_connection import CiscoSSHConnection
class BrocadeNosSSH(CiscoSSHConnection):
"""Support for Brocade NOS/VDX."""
def enable(self, *args, **kwargs):
"""No enable mode on Brocade VDX."""
pass
def exit_enable_mode(self, *args, **kwargs):
"""No enable mode on Brocade VDX."""
pass
def special_login_handler(self, delay_factor=1):
"""Adding a delay after login."""
delay_factor = self.select_delay_factor(delay_factor)
self.write_channel(self.RETURN)
time.sleep(1 * delay_factor)
<commit_msg>Add save_config for brocade VDX<commit_after>
|
"""Support for Brocade NOS/VDX."""
from __future__ import unicode_literals
import time
from netmiko.cisco_base_connection import CiscoSSHConnection
class BrocadeNosSSH(CiscoSSHConnection):
"""Support for Brocade NOS/VDX."""
def enable(self, *args, **kwargs):
"""No enable mode on Brocade VDX."""
pass
def exit_enable_mode(self, *args, **kwargs):
"""No enable mode on Brocade VDX."""
pass
def special_login_handler(self, delay_factor=1):
"""Adding a delay after login."""
delay_factor = self.select_delay_factor(delay_factor)
self.write_channel(self.RETURN)
time.sleep(1 * delay_factor)
def save_config(self):
"""Save Config for Brocade VDX."""
self.send_command('copy running-config startup-config', '[Y/N]')
self.send_command('y')
|
"""Support for Brocade NOS/VDX."""
from __future__ import unicode_literals
import time
from netmiko.cisco_base_connection import CiscoSSHConnection
class BrocadeNosSSH(CiscoSSHConnection):
"""Support for Brocade NOS/VDX."""
def enable(self, *args, **kwargs):
"""No enable mode on Brocade VDX."""
pass
def exit_enable_mode(self, *args, **kwargs):
"""No enable mode on Brocade VDX."""
pass
def special_login_handler(self, delay_factor=1):
"""Adding a delay after login."""
delay_factor = self.select_delay_factor(delay_factor)
self.write_channel(self.RETURN)
time.sleep(1 * delay_factor)
Add save_config for brocade VDX"""Support for Brocade NOS/VDX."""
from __future__ import unicode_literals
import time
from netmiko.cisco_base_connection import CiscoSSHConnection
class BrocadeNosSSH(CiscoSSHConnection):
"""Support for Brocade NOS/VDX."""
def enable(self, *args, **kwargs):
"""No enable mode on Brocade VDX."""
pass
def exit_enable_mode(self, *args, **kwargs):
"""No enable mode on Brocade VDX."""
pass
def special_login_handler(self, delay_factor=1):
"""Adding a delay after login."""
delay_factor = self.select_delay_factor(delay_factor)
self.write_channel(self.RETURN)
time.sleep(1 * delay_factor)
def save_config(self):
"""Save Config for Brocade VDX."""
self.send_command('copy running-config startup-config', '[Y/N]')
self.send_command('y')
|
<commit_before>"""Support for Brocade NOS/VDX."""
from __future__ import unicode_literals
import time
from netmiko.cisco_base_connection import CiscoSSHConnection
class BrocadeNosSSH(CiscoSSHConnection):
"""Support for Brocade NOS/VDX."""
def enable(self, *args, **kwargs):
"""No enable mode on Brocade VDX."""
pass
def exit_enable_mode(self, *args, **kwargs):
"""No enable mode on Brocade VDX."""
pass
def special_login_handler(self, delay_factor=1):
"""Adding a delay after login."""
delay_factor = self.select_delay_factor(delay_factor)
self.write_channel(self.RETURN)
time.sleep(1 * delay_factor)
<commit_msg>Add save_config for brocade VDX<commit_after>"""Support for Brocade NOS/VDX."""
from __future__ import unicode_literals
import time
from netmiko.cisco_base_connection import CiscoSSHConnection
class BrocadeNosSSH(CiscoSSHConnection):
"""Support for Brocade NOS/VDX."""
def enable(self, *args, **kwargs):
"""No enable mode on Brocade VDX."""
pass
def exit_enable_mode(self, *args, **kwargs):
"""No enable mode on Brocade VDX."""
pass
def special_login_handler(self, delay_factor=1):
"""Adding a delay after login."""
delay_factor = self.select_delay_factor(delay_factor)
self.write_channel(self.RETURN)
time.sleep(1 * delay_factor)
def save_config(self):
"""Save Config for Brocade VDX."""
self.send_command('copy running-config startup-config', '[Y/N]')
self.send_command('y')
|
74888d07942c0ee9ab8accbe87732380a700f9d0
|
rule.py
|
rule.py
|
class PriceRule:
"""PriceRule is a rule that triggers when a stock price satisfies a condition.
The condition is usually greater, equal or lesser than a given value.
"""
def __init__(self, symbol, condition):
self.symbol = symbol
self.condition = condition
|
Add PriceRule class and init method.
|
Add PriceRule class and init method.
|
Python
|
mit
|
bsmukasa/stock_alerter
|
Add PriceRule class and init method.
|
class PriceRule:
"""PriceRule is a rule that triggers when a stock price satisfies a condition.
The condition is usually greater, equal or lesser than a given value.
"""
def __init__(self, symbol, condition):
self.symbol = symbol
self.condition = condition
|
<commit_before>
<commit_msg>Add PriceRule class and init method.<commit_after>
|
class PriceRule:
"""PriceRule is a rule that triggers when a stock price satisfies a condition.
The condition is usually greater, equal or lesser than a given value.
"""
def __init__(self, symbol, condition):
self.symbol = symbol
self.condition = condition
|
Add PriceRule class and init method.class PriceRule:
"""PriceRule is a rule that triggers when a stock price satisfies a condition.
The condition is usually greater, equal or lesser than a given value.
"""
def __init__(self, symbol, condition):
self.symbol = symbol
self.condition = condition
|
<commit_before>
<commit_msg>Add PriceRule class and init method.<commit_after>class PriceRule:
"""PriceRule is a rule that triggers when a stock price satisfies a condition.
The condition is usually greater, equal or lesser than a given value.
"""
def __init__(self, symbol, condition):
self.symbol = symbol
self.condition = condition
|
|
457a40d3487d59147bcea71dd06f49317167c8d1
|
hash_table.py
|
hash_table.py
|
#!/usr/bin/env python
'''Implementation of a simple hash table.
The table has `hash`, `get` and `set` methods.
The hash function uses a very basic hash algorithm to insert the value
into the table.
'''
class HashItem(object):
def __init__(self, key, value):
self.key = key
self.value = value
class Hash(object):
def __init__(self, size=1024):
self.table = []
for i in range(size):
self.table.append(list())
def hash(self, key):
hash_value = 0
for i in key:
hash_value += ord(key)
return hash_value % len(self.table)
def get(self, key):
hashed_key = self.hash(key)
for k in self.table[hashed_key]:
if k[0] == key:
return k[1]
else:
raise KeyError('Value not found')
def set(self):
pass
|
#!/usr/bin/env python
'''Implementation of a simple hash table.
The table has `hash`, `get` and `set` methods.
The hash function uses a very basic hash algorithm to insert the value
into the table.
'''
class HashItem(object):
def __init__(self, key, value):
self.key = key
self.value = value
class Hash(object):
def __init__(self, size=1024):
self.table = []
for i in range(size):
self.table.append(list())
def hash(self, key):
hash_value = 0
for i in key:
hash_value += ord(key)
return hash_value % len(self.table)
def get(self, key):
hashed_key = self.hash(key)
for k in self.table[hashed_key]:
if k[0] == key:
return k[1]
else:
raise KeyError('Value not found')
def set(self, key, val):
hashed_key = self.hash(key)
self.table[hashed_key].append((key, val))
|
Build out set function of hash table class; still need to deal with outcome of setting multiple values to same key
|
Build out set function of hash table class; still need to deal with outcome of setting multiple values to same key
|
Python
|
mit
|
jwarren116/data-structures-deux
|
#!/usr/bin/env python
'''Implementation of a simple hash table.
The table has `hash`, `get` and `set` methods.
The hash function uses a very basic hash algorithm to insert the value
into the table.
'''
class HashItem(object):
def __init__(self, key, value):
self.key = key
self.value = value
class Hash(object):
def __init__(self, size=1024):
self.table = []
for i in range(size):
self.table.append(list())
def hash(self, key):
hash_value = 0
for i in key:
hash_value += ord(key)
return hash_value % len(self.table)
def get(self, key):
hashed_key = self.hash(key)
for k in self.table[hashed_key]:
if k[0] == key:
return k[1]
else:
raise KeyError('Value not found')
def set(self):
pass
Build out set function of hash table class; still need to deal with outcome of setting multiple values to same key
|
#!/usr/bin/env python
'''Implementation of a simple hash table.
The table has `hash`, `get` and `set` methods.
The hash function uses a very basic hash algorithm to insert the value
into the table.
'''
class HashItem(object):
def __init__(self, key, value):
self.key = key
self.value = value
class Hash(object):
def __init__(self, size=1024):
self.table = []
for i in range(size):
self.table.append(list())
def hash(self, key):
hash_value = 0
for i in key:
hash_value += ord(key)
return hash_value % len(self.table)
def get(self, key):
hashed_key = self.hash(key)
for k in self.table[hashed_key]:
if k[0] == key:
return k[1]
else:
raise KeyError('Value not found')
def set(self, key, val):
hashed_key = self.hash(key)
self.table[hashed_key].append((key, val))
|
<commit_before>#!/usr/bin/env python
'''Implementation of a simple hash table.
The table has `hash`, `get` and `set` methods.
The hash function uses a very basic hash algorithm to insert the value
into the table.
'''
class HashItem(object):
def __init__(self, key, value):
self.key = key
self.value = value
class Hash(object):
def __init__(self, size=1024):
self.table = []
for i in range(size):
self.table.append(list())
def hash(self, key):
hash_value = 0
for i in key:
hash_value += ord(key)
return hash_value % len(self.table)
def get(self, key):
hashed_key = self.hash(key)
for k in self.table[hashed_key]:
if k[0] == key:
return k[1]
else:
raise KeyError('Value not found')
def set(self):
pass
<commit_msg>Build out set function of hash table class; still need to deal with outcome of setting multiple values to same key<commit_after>
|
#!/usr/bin/env python
'''Implementation of a simple hash table.
The table has `hash`, `get` and `set` methods.
The hash function uses a very basic hash algorithm to insert the value
into the table.
'''
class HashItem(object):
def __init__(self, key, value):
self.key = key
self.value = value
class Hash(object):
def __init__(self, size=1024):
self.table = []
for i in range(size):
self.table.append(list())
def hash(self, key):
hash_value = 0
for i in key:
hash_value += ord(key)
return hash_value % len(self.table)
def get(self, key):
hashed_key = self.hash(key)
for k in self.table[hashed_key]:
if k[0] == key:
return k[1]
else:
raise KeyError('Value not found')
def set(self, key, val):
hashed_key = self.hash(key)
self.table[hashed_key].append((key, val))
|
#!/usr/bin/env python
'''Implementation of a simple hash table.
The table has `hash`, `get` and `set` methods.
The hash function uses a very basic hash algorithm to insert the value
into the table.
'''
class HashItem(object):
def __init__(self, key, value):
self.key = key
self.value = value
class Hash(object):
def __init__(self, size=1024):
self.table = []
for i in range(size):
self.table.append(list())
def hash(self, key):
hash_value = 0
for i in key:
hash_value += ord(key)
return hash_value % len(self.table)
def get(self, key):
hashed_key = self.hash(key)
for k in self.table[hashed_key]:
if k[0] == key:
return k[1]
else:
raise KeyError('Value not found')
def set(self):
pass
Build out set function of hash table class; still need to deal with outcome of setting multiple values to same key#!/usr/bin/env python
'''Implementation of a simple hash table.
The table has `hash`, `get` and `set` methods.
The hash function uses a very basic hash algorithm to insert the value
into the table.
'''
class HashItem(object):
def __init__(self, key, value):
self.key = key
self.value = value
class Hash(object):
def __init__(self, size=1024):
self.table = []
for i in range(size):
self.table.append(list())
def hash(self, key):
hash_value = 0
for i in key:
hash_value += ord(key)
return hash_value % len(self.table)
def get(self, key):
hashed_key = self.hash(key)
for k in self.table[hashed_key]:
if k[0] == key:
return k[1]
else:
raise KeyError('Value not found')
def set(self, key, val):
hashed_key = self.hash(key)
self.table[hashed_key].append((key, val))
|
<commit_before>#!/usr/bin/env python
'''Implementation of a simple hash table.
The table has `hash`, `get` and `set` methods.
The hash function uses a very basic hash algorithm to insert the value
into the table.
'''
class HashItem(object):
def __init__(self, key, value):
self.key = key
self.value = value
class Hash(object):
def __init__(self, size=1024):
self.table = []
for i in range(size):
self.table.append(list())
def hash(self, key):
hash_value = 0
for i in key:
hash_value += ord(key)
return hash_value % len(self.table)
def get(self, key):
hashed_key = self.hash(key)
for k in self.table[hashed_key]:
if k[0] == key:
return k[1]
else:
raise KeyError('Value not found')
def set(self):
pass
<commit_msg>Build out set function of hash table class; still need to deal with outcome of setting multiple values to same key<commit_after>#!/usr/bin/env python
'''Implementation of a simple hash table.
The table has `hash`, `get` and `set` methods.
The hash function uses a very basic hash algorithm to insert the value
into the table.
'''
class HashItem(object):
def __init__(self, key, value):
self.key = key
self.value = value
class Hash(object):
def __init__(self, size=1024):
self.table = []
for i in range(size):
self.table.append(list())
def hash(self, key):
hash_value = 0
for i in key:
hash_value += ord(key)
return hash_value % len(self.table)
def get(self, key):
hashed_key = self.hash(key)
for k in self.table[hashed_key]:
if k[0] == key:
return k[1]
else:
raise KeyError('Value not found')
def set(self, key, val):
hashed_key = self.hash(key)
self.table[hashed_key].append((key, val))
|
84783cdcdd52108df359cbe2add8c41b92b97e0b
|
openfisca_web_api/scripts/serve.py
|
openfisca_web_api/scripts/serve.py
|
# -*- coding: utf-8 -*-
import os
import sys
from logging.config import fileConfig
from wsgiref.simple_server import make_server
from paste.deploy import loadapp
hostname = 'localhost'
port = 2000
def main():
conf_file_path = os.path.join(sys.prefix, 'share', 'openfisca', 'openfisca-web-api', 'development-france.ini')
# If openfisca_web_api has been installed with --editable
if not os.path.isfile(conf_file_path):
import pkg_resources
api_sources_path = pkg_resources.get_distribution("openfisca_web_api").location
conf_file_path = os.path.join(api_sources_path, 'development-france.ini')
fileConfig(conf_file_path)
application = loadapp('config:{}'.format(conf_file_path))
httpd = make_server(hostname, port, application)
print u'Serving on http://{}:{}/'.format(hostname, port)
try:
httpd.serve_forever()
except KeyboardInterrupt:
return
if __name__ == '__main__':
sys.exit(main())
|
# -*- coding: utf-8 -*-
import os
import sys
import argparse
from logging.config import fileConfig
from wsgiref.simple_server import make_server
from paste.deploy import loadapp
def main():
parser = argparse.ArgumentParser(description = __doc__)
parser.add_argument('-p', '--port', action = 'store', default = 2000, help = "port to serve on")
args = parser.parse_args()
port = int(args.port)
hostname = 'localhost'
conf_file_path = os.path.join(sys.prefix, 'share', 'openfisca', 'openfisca-web-api', 'development-france.ini')
# If openfisca_web_api has been installed with --editable
if not os.path.isfile(conf_file_path):
import pkg_resources
api_sources_path = pkg_resources.get_distribution("openfisca_web_api").location
conf_file_path = os.path.join(api_sources_path, 'development-france.ini')
fileConfig(conf_file_path)
application = loadapp('config:{}'.format(conf_file_path))
httpd = make_server(hostname, port, application)
print u'Serving on http://{}:{}/'.format(hostname, port)
try:
httpd.serve_forever()
except KeyboardInterrupt:
return
if __name__ == '__main__':
sys.exit(main())
|
Allow port to be changed
|
Allow port to be changed
|
Python
|
agpl-3.0
|
openfisca/openfisca-web-api,openfisca/openfisca-web-api
|
# -*- coding: utf-8 -*-
import os
import sys
from logging.config import fileConfig
from wsgiref.simple_server import make_server
from paste.deploy import loadapp
hostname = 'localhost'
port = 2000
def main():
conf_file_path = os.path.join(sys.prefix, 'share', 'openfisca', 'openfisca-web-api', 'development-france.ini')
# If openfisca_web_api has been installed with --editable
if not os.path.isfile(conf_file_path):
import pkg_resources
api_sources_path = pkg_resources.get_distribution("openfisca_web_api").location
conf_file_path = os.path.join(api_sources_path, 'development-france.ini')
fileConfig(conf_file_path)
application = loadapp('config:{}'.format(conf_file_path))
httpd = make_server(hostname, port, application)
print u'Serving on http://{}:{}/'.format(hostname, port)
try:
httpd.serve_forever()
except KeyboardInterrupt:
return
if __name__ == '__main__':
sys.exit(main())
Allow port to be changed
|
# -*- coding: utf-8 -*-
import os
import sys
import argparse
from logging.config import fileConfig
from wsgiref.simple_server import make_server
from paste.deploy import loadapp
def main():
parser = argparse.ArgumentParser(description = __doc__)
parser.add_argument('-p', '--port', action = 'store', default = 2000, help = "port to serve on")
args = parser.parse_args()
port = int(args.port)
hostname = 'localhost'
conf_file_path = os.path.join(sys.prefix, 'share', 'openfisca', 'openfisca-web-api', 'development-france.ini')
# If openfisca_web_api has been installed with --editable
if not os.path.isfile(conf_file_path):
import pkg_resources
api_sources_path = pkg_resources.get_distribution("openfisca_web_api").location
conf_file_path = os.path.join(api_sources_path, 'development-france.ini')
fileConfig(conf_file_path)
application = loadapp('config:{}'.format(conf_file_path))
httpd = make_server(hostname, port, application)
print u'Serving on http://{}:{}/'.format(hostname, port)
try:
httpd.serve_forever()
except KeyboardInterrupt:
return
if __name__ == '__main__':
sys.exit(main())
|
<commit_before># -*- coding: utf-8 -*-
import os
import sys
from logging.config import fileConfig
from wsgiref.simple_server import make_server
from paste.deploy import loadapp
hostname = 'localhost'
port = 2000
def main():
conf_file_path = os.path.join(sys.prefix, 'share', 'openfisca', 'openfisca-web-api', 'development-france.ini')
# If openfisca_web_api has been installed with --editable
if not os.path.isfile(conf_file_path):
import pkg_resources
api_sources_path = pkg_resources.get_distribution("openfisca_web_api").location
conf_file_path = os.path.join(api_sources_path, 'development-france.ini')
fileConfig(conf_file_path)
application = loadapp('config:{}'.format(conf_file_path))
httpd = make_server(hostname, port, application)
print u'Serving on http://{}:{}/'.format(hostname, port)
try:
httpd.serve_forever()
except KeyboardInterrupt:
return
if __name__ == '__main__':
sys.exit(main())
<commit_msg>Allow port to be changed<commit_after>
|
# -*- coding: utf-8 -*-
import os
import sys
import argparse
from logging.config import fileConfig
from wsgiref.simple_server import make_server
from paste.deploy import loadapp
def main():
parser = argparse.ArgumentParser(description = __doc__)
parser.add_argument('-p', '--port', action = 'store', default = 2000, help = "port to serve on")
args = parser.parse_args()
port = int(args.port)
hostname = 'localhost'
conf_file_path = os.path.join(sys.prefix, 'share', 'openfisca', 'openfisca-web-api', 'development-france.ini')
# If openfisca_web_api has been installed with --editable
if not os.path.isfile(conf_file_path):
import pkg_resources
api_sources_path = pkg_resources.get_distribution("openfisca_web_api").location
conf_file_path = os.path.join(api_sources_path, 'development-france.ini')
fileConfig(conf_file_path)
application = loadapp('config:{}'.format(conf_file_path))
httpd = make_server(hostname, port, application)
print u'Serving on http://{}:{}/'.format(hostname, port)
try:
httpd.serve_forever()
except KeyboardInterrupt:
return
if __name__ == '__main__':
sys.exit(main())
|
# -*- coding: utf-8 -*-
import os
import sys
from logging.config import fileConfig
from wsgiref.simple_server import make_server
from paste.deploy import loadapp
hostname = 'localhost'
port = 2000
def main():
conf_file_path = os.path.join(sys.prefix, 'share', 'openfisca', 'openfisca-web-api', 'development-france.ini')
# If openfisca_web_api has been installed with --editable
if not os.path.isfile(conf_file_path):
import pkg_resources
api_sources_path = pkg_resources.get_distribution("openfisca_web_api").location
conf_file_path = os.path.join(api_sources_path, 'development-france.ini')
fileConfig(conf_file_path)
application = loadapp('config:{}'.format(conf_file_path))
httpd = make_server(hostname, port, application)
print u'Serving on http://{}:{}/'.format(hostname, port)
try:
httpd.serve_forever()
except KeyboardInterrupt:
return
if __name__ == '__main__':
sys.exit(main())
Allow port to be changed# -*- coding: utf-8 -*-
import os
import sys
import argparse
from logging.config import fileConfig
from wsgiref.simple_server import make_server
from paste.deploy import loadapp
def main():
parser = argparse.ArgumentParser(description = __doc__)
parser.add_argument('-p', '--port', action = 'store', default = 2000, help = "port to serve on")
args = parser.parse_args()
port = int(args.port)
hostname = 'localhost'
conf_file_path = os.path.join(sys.prefix, 'share', 'openfisca', 'openfisca-web-api', 'development-france.ini')
# If openfisca_web_api has been installed with --editable
if not os.path.isfile(conf_file_path):
import pkg_resources
api_sources_path = pkg_resources.get_distribution("openfisca_web_api").location
conf_file_path = os.path.join(api_sources_path, 'development-france.ini')
fileConfig(conf_file_path)
application = loadapp('config:{}'.format(conf_file_path))
httpd = make_server(hostname, port, application)
print u'Serving on http://{}:{}/'.format(hostname, port)
try:
httpd.serve_forever()
except KeyboardInterrupt:
return
if __name__ == '__main__':
sys.exit(main())
|
<commit_before># -*- coding: utf-8 -*-
import os
import sys
from logging.config import fileConfig
from wsgiref.simple_server import make_server
from paste.deploy import loadapp
hostname = 'localhost'
port = 2000
def main():
conf_file_path = os.path.join(sys.prefix, 'share', 'openfisca', 'openfisca-web-api', 'development-france.ini')
# If openfisca_web_api has been installed with --editable
if not os.path.isfile(conf_file_path):
import pkg_resources
api_sources_path = pkg_resources.get_distribution("openfisca_web_api").location
conf_file_path = os.path.join(api_sources_path, 'development-france.ini')
fileConfig(conf_file_path)
application = loadapp('config:{}'.format(conf_file_path))
httpd = make_server(hostname, port, application)
print u'Serving on http://{}:{}/'.format(hostname, port)
try:
httpd.serve_forever()
except KeyboardInterrupt:
return
if __name__ == '__main__':
sys.exit(main())
<commit_msg>Allow port to be changed<commit_after># -*- coding: utf-8 -*-
import os
import sys
import argparse
from logging.config import fileConfig
from wsgiref.simple_server import make_server
from paste.deploy import loadapp
def main():
parser = argparse.ArgumentParser(description = __doc__)
parser.add_argument('-p', '--port', action = 'store', default = 2000, help = "port to serve on")
args = parser.parse_args()
port = int(args.port)
hostname = 'localhost'
conf_file_path = os.path.join(sys.prefix, 'share', 'openfisca', 'openfisca-web-api', 'development-france.ini')
# If openfisca_web_api has been installed with --editable
if not os.path.isfile(conf_file_path):
import pkg_resources
api_sources_path = pkg_resources.get_distribution("openfisca_web_api").location
conf_file_path = os.path.join(api_sources_path, 'development-france.ini')
fileConfig(conf_file_path)
application = loadapp('config:{}'.format(conf_file_path))
httpd = make_server(hostname, port, application)
print u'Serving on http://{}:{}/'.format(hostname, port)
try:
httpd.serve_forever()
except KeyboardInterrupt:
return
if __name__ == '__main__':
sys.exit(main())
|
8dae2049c96932855cc0162437d799e258f94a53
|
test/absolute_import/local_module.py
|
test/absolute_import/local_module.py
|
"""
This is a module that imports the *standard library* unittest,
despite there being a local "unittest" module. It specifies that it
wants the stdlib one with the ``absolute_import`` __future__ import.
The twisted equivalent of this module is ``twisted.trial._synctest``.
"""
from __future__ import absolute_import
import unittest # this is stdlib unittest, but jedi gets the local one
class Assertions(unittest.TestCase):
pass
|
"""
This is a module that imports the *standard library* unittest,
despite there being a local "unittest" module. It specifies that it
wants the stdlib one with the ``absolute_import`` __future__ import.
The twisted equivalent of this module is ``twisted.trial._synctest``.
"""
from __future__ import absolute_import
import unittest
class Assertions(unittest.TestCase):
pass
|
Fix inaccuracy in test comment, since jedi now does the right thing
|
Fix inaccuracy in test comment, since jedi now does the right thing
|
Python
|
mit
|
dwillmer/jedi,flurischt/jedi,mfussenegger/jedi,tjwei/jedi,flurischt/jedi,jonashaag/jedi,jonashaag/jedi,mfussenegger/jedi,tjwei/jedi,WoLpH/jedi,WoLpH/jedi,dwillmer/jedi
|
"""
This is a module that imports the *standard library* unittest,
despite there being a local "unittest" module. It specifies that it
wants the stdlib one with the ``absolute_import`` __future__ import.
The twisted equivalent of this module is ``twisted.trial._synctest``.
"""
from __future__ import absolute_import
import unittest # this is stdlib unittest, but jedi gets the local one
class Assertions(unittest.TestCase):
pass
Fix inaccuracy in test comment, since jedi now does the right thing
|
"""
This is a module that imports the *standard library* unittest,
despite there being a local "unittest" module. It specifies that it
wants the stdlib one with the ``absolute_import`` __future__ import.
The twisted equivalent of this module is ``twisted.trial._synctest``.
"""
from __future__ import absolute_import
import unittest
class Assertions(unittest.TestCase):
pass
|
<commit_before>"""
This is a module that imports the *standard library* unittest,
despite there being a local "unittest" module. It specifies that it
wants the stdlib one with the ``absolute_import`` __future__ import.
The twisted equivalent of this module is ``twisted.trial._synctest``.
"""
from __future__ import absolute_import
import unittest # this is stdlib unittest, but jedi gets the local one
class Assertions(unittest.TestCase):
pass
<commit_msg>Fix inaccuracy in test comment, since jedi now does the right thing<commit_after>
|
"""
This is a module that imports the *standard library* unittest,
despite there being a local "unittest" module. It specifies that it
wants the stdlib one with the ``absolute_import`` __future__ import.
The twisted equivalent of this module is ``twisted.trial._synctest``.
"""
from __future__ import absolute_import
import unittest
class Assertions(unittest.TestCase):
pass
|
"""
This is a module that imports the *standard library* unittest,
despite there being a local "unittest" module. It specifies that it
wants the stdlib one with the ``absolute_import`` __future__ import.
The twisted equivalent of this module is ``twisted.trial._synctest``.
"""
from __future__ import absolute_import
import unittest # this is stdlib unittest, but jedi gets the local one
class Assertions(unittest.TestCase):
pass
Fix inaccuracy in test comment, since jedi now does the right thing"""
This is a module that imports the *standard library* unittest,
despite there being a local "unittest" module. It specifies that it
wants the stdlib one with the ``absolute_import`` __future__ import.
The twisted equivalent of this module is ``twisted.trial._synctest``.
"""
from __future__ import absolute_import
import unittest
class Assertions(unittest.TestCase):
pass
|
<commit_before>"""
This is a module that imports the *standard library* unittest,
despite there being a local "unittest" module. It specifies that it
wants the stdlib one with the ``absolute_import`` __future__ import.
The twisted equivalent of this module is ``twisted.trial._synctest``.
"""
from __future__ import absolute_import
import unittest # this is stdlib unittest, but jedi gets the local one
class Assertions(unittest.TestCase):
pass
<commit_msg>Fix inaccuracy in test comment, since jedi now does the right thing<commit_after>"""
This is a module that imports the *standard library* unittest,
despite there being a local "unittest" module. It specifies that it
wants the stdlib one with the ``absolute_import`` __future__ import.
The twisted equivalent of this module is ``twisted.trial._synctest``.
"""
from __future__ import absolute_import
import unittest
class Assertions(unittest.TestCase):
pass
|
e697e9887fa681918c9b10367ee2319969f591d0
|
test/auth/test_client_credentials.py
|
test/auth/test_client_credentials.py
|
from oauthlib.oauth2 import InvalidClientError
import pytest
from test import configure_mendeley, cassette
def test_should_get_authenticated_session():
mendeley = configure_mendeley()
auth = mendeley.start_client_credentials_flow()
with cassette('fixtures/auth/client_credentials/get_authenticated_session.yaml'):
session = auth.authenticate()
assert session.token['access_token']
assert session.host == 'https://api.mendeley.com'
def test_should_throw_exception_on_incorrect_credentials():
mendeley = configure_mendeley()
mendeley.client_secret += '-invalid'
auth = mendeley.start_client_credentials_flow()
with cassette('fixtures/auth/client_credentials/incorrect_credentials.yaml'), pytest.raises(InvalidClientError):
auth.authenticate()
|
from oauthlib.oauth2 import InvalidClientError
import pytest
from test import configure_mendeley, cassette
def test_should_get_authenticated_session():
mendeley = configure_mendeley()
auth = mendeley.start_client_credentials_flow()
with cassette('fixtures/auth/client_credentials/get_authenticated_session.yaml'):
session = auth.authenticate()
assert session.token['access_token']
assert session.host == 'https://api.mendeley.com'
def test_should_throw_exception_on_incorrect_credentials():
mendeley = configure_mendeley()
mendeley.client_secret += '-invalid'
auth = mendeley.start_client_credentials_flow()
# We should never get an access token back
# and the OAuth library should be unhappy about that
with cassette('fixtures/auth/client_credentials/incorrect_credentials.yaml'), pytest.raises(MissingTokenError):
auth.authenticate()
|
Check for right kind of error in invalid creds test
|
Check for right kind of error in invalid creds test
|
Python
|
apache-2.0
|
Mendeley/mendeley-python-sdk
|
from oauthlib.oauth2 import InvalidClientError
import pytest
from test import configure_mendeley, cassette
def test_should_get_authenticated_session():
mendeley = configure_mendeley()
auth = mendeley.start_client_credentials_flow()
with cassette('fixtures/auth/client_credentials/get_authenticated_session.yaml'):
session = auth.authenticate()
assert session.token['access_token']
assert session.host == 'https://api.mendeley.com'
def test_should_throw_exception_on_incorrect_credentials():
mendeley = configure_mendeley()
mendeley.client_secret += '-invalid'
auth = mendeley.start_client_credentials_flow()
with cassette('fixtures/auth/client_credentials/incorrect_credentials.yaml'), pytest.raises(InvalidClientError):
auth.authenticate()
Check for right kind of error in invalid creds test
|
from oauthlib.oauth2 import InvalidClientError
import pytest
from test import configure_mendeley, cassette
def test_should_get_authenticated_session():
mendeley = configure_mendeley()
auth = mendeley.start_client_credentials_flow()
with cassette('fixtures/auth/client_credentials/get_authenticated_session.yaml'):
session = auth.authenticate()
assert session.token['access_token']
assert session.host == 'https://api.mendeley.com'
def test_should_throw_exception_on_incorrect_credentials():
mendeley = configure_mendeley()
mendeley.client_secret += '-invalid'
auth = mendeley.start_client_credentials_flow()
# We should never get an access token back
# and the OAuth library should be unhappy about that
with cassette('fixtures/auth/client_credentials/incorrect_credentials.yaml'), pytest.raises(MissingTokenError):
auth.authenticate()
|
<commit_before>from oauthlib.oauth2 import InvalidClientError
import pytest
from test import configure_mendeley, cassette
def test_should_get_authenticated_session():
mendeley = configure_mendeley()
auth = mendeley.start_client_credentials_flow()
with cassette('fixtures/auth/client_credentials/get_authenticated_session.yaml'):
session = auth.authenticate()
assert session.token['access_token']
assert session.host == 'https://api.mendeley.com'
def test_should_throw_exception_on_incorrect_credentials():
mendeley = configure_mendeley()
mendeley.client_secret += '-invalid'
auth = mendeley.start_client_credentials_flow()
with cassette('fixtures/auth/client_credentials/incorrect_credentials.yaml'), pytest.raises(InvalidClientError):
auth.authenticate()
<commit_msg>Check for right kind of error in invalid creds test<commit_after>
|
from oauthlib.oauth2 import InvalidClientError
import pytest
from test import configure_mendeley, cassette
def test_should_get_authenticated_session():
mendeley = configure_mendeley()
auth = mendeley.start_client_credentials_flow()
with cassette('fixtures/auth/client_credentials/get_authenticated_session.yaml'):
session = auth.authenticate()
assert session.token['access_token']
assert session.host == 'https://api.mendeley.com'
def test_should_throw_exception_on_incorrect_credentials():
mendeley = configure_mendeley()
mendeley.client_secret += '-invalid'
auth = mendeley.start_client_credentials_flow()
# We should never get an access token back
# and the OAuth library should be unhappy about that
with cassette('fixtures/auth/client_credentials/incorrect_credentials.yaml'), pytest.raises(MissingTokenError):
auth.authenticate()
|
from oauthlib.oauth2 import InvalidClientError
import pytest
from test import configure_mendeley, cassette
def test_should_get_authenticated_session():
mendeley = configure_mendeley()
auth = mendeley.start_client_credentials_flow()
with cassette('fixtures/auth/client_credentials/get_authenticated_session.yaml'):
session = auth.authenticate()
assert session.token['access_token']
assert session.host == 'https://api.mendeley.com'
def test_should_throw_exception_on_incorrect_credentials():
mendeley = configure_mendeley()
mendeley.client_secret += '-invalid'
auth = mendeley.start_client_credentials_flow()
with cassette('fixtures/auth/client_credentials/incorrect_credentials.yaml'), pytest.raises(InvalidClientError):
auth.authenticate()
Check for right kind of error in invalid creds testfrom oauthlib.oauth2 import InvalidClientError
import pytest
from test import configure_mendeley, cassette
def test_should_get_authenticated_session():
mendeley = configure_mendeley()
auth = mendeley.start_client_credentials_flow()
with cassette('fixtures/auth/client_credentials/get_authenticated_session.yaml'):
session = auth.authenticate()
assert session.token['access_token']
assert session.host == 'https://api.mendeley.com'
def test_should_throw_exception_on_incorrect_credentials():
mendeley = configure_mendeley()
mendeley.client_secret += '-invalid'
auth = mendeley.start_client_credentials_flow()
# We should never get an access token back
# and the OAuth library should be unhappy about that
with cassette('fixtures/auth/client_credentials/incorrect_credentials.yaml'), pytest.raises(MissingTokenError):
auth.authenticate()
|
<commit_before>from oauthlib.oauth2 import InvalidClientError
import pytest
from test import configure_mendeley, cassette
def test_should_get_authenticated_session():
mendeley = configure_mendeley()
auth = mendeley.start_client_credentials_flow()
with cassette('fixtures/auth/client_credentials/get_authenticated_session.yaml'):
session = auth.authenticate()
assert session.token['access_token']
assert session.host == 'https://api.mendeley.com'
def test_should_throw_exception_on_incorrect_credentials():
mendeley = configure_mendeley()
mendeley.client_secret += '-invalid'
auth = mendeley.start_client_credentials_flow()
with cassette('fixtures/auth/client_credentials/incorrect_credentials.yaml'), pytest.raises(InvalidClientError):
auth.authenticate()
<commit_msg>Check for right kind of error in invalid creds test<commit_after>from oauthlib.oauth2 import InvalidClientError
import pytest
from test import configure_mendeley, cassette
def test_should_get_authenticated_session():
mendeley = configure_mendeley()
auth = mendeley.start_client_credentials_flow()
with cassette('fixtures/auth/client_credentials/get_authenticated_session.yaml'):
session = auth.authenticate()
assert session.token['access_token']
assert session.host == 'https://api.mendeley.com'
def test_should_throw_exception_on_incorrect_credentials():
mendeley = configure_mendeley()
mendeley.client_secret += '-invalid'
auth = mendeley.start_client_credentials_flow()
# We should never get an access token back
# and the OAuth library should be unhappy about that
with cassette('fixtures/auth/client_credentials/incorrect_credentials.yaml'), pytest.raises(MissingTokenError):
auth.authenticate()
|
634e389ed260b404327e303afb4f5a1dc931ee36
|
storm/db.py
|
storm/db.py
|
from random import randrange
import time
from storm import error
class Connection(object):
def __init__(self, host='localhost', port=None, database=None, user=None, password=None):
self.host = host
self.port = port
self.database = database
self.user = user
self.password = password
class ConnectionPool(object):
def __init__(self, connection, count=10, lifetime=3600):
self.connection = connection
self.count = count
self.lifetime = lifetime
self.db_connections = [];
def create_new_connection(self):
cls = self.get_db_class()
instance = cls(self.connection)
self.db_connections.append(instance)
return instance
def get_db(self):
if len(self.db_connections) < self.count:
return self.create_new_connection()
index = randrange(0, len(self.db_connections))
connection = self.db_connections[index]
if (time.time() - connection.start_time) > self.lifetime:
removed = self.db_connections.pop(index)
removed.close()
return self.create_new_connection()
return self.db_connections[index]
def get_db_class(self):
raise NotImplementedError('The "get_db_class" method is not implemented')
class Database(object):
def __init__(self, connection):
if not isinstance(connection, Connection):
raise error.StormError('connection must be instance of storm.db.Connection')
self.connection = connection
self.is_connected = False
self.start_time = time.time()
|
import time
from storm import error
from tornado import gen
class Connection(object):
def __init__(self, host='localhost', port=None, database=None, user=None, password=None):
self.host = host
self.port = port
self.database = database
self.user = user
self.password = password
class ConnectionPool(object):
def __init__(self, connection, count=10, lifetime=3600):
self.connection = connection
self.count = count
self.lifetime = lifetime
@gen.coroutine
def get_db(self, callback=None):
raise NotImplementedError('The "get_db" method is not implemented')
def get_db_class(self):
raise NotImplementedError('The "get_db_class" method is not implemented')
class Database(object):
def __init__(self, connection):
if not isinstance(connection, Connection):
raise error.StormError('connection must be instance of storm.db.Connection')
self.connection = connection
self.is_connected = False
self.start_time = time.time()
|
Make connection pool less smart
|
Make connection pool less smart
You have to extend it and implement your own get_db function to use a
connection pool now
|
Python
|
mit
|
liujiantong/storm,ccampbell/storm
|
from random import randrange
import time
from storm import error
class Connection(object):
def __init__(self, host='localhost', port=None, database=None, user=None, password=None):
self.host = host
self.port = port
self.database = database
self.user = user
self.password = password
class ConnectionPool(object):
def __init__(self, connection, count=10, lifetime=3600):
self.connection = connection
self.count = count
self.lifetime = lifetime
self.db_connections = [];
def create_new_connection(self):
cls = self.get_db_class()
instance = cls(self.connection)
self.db_connections.append(instance)
return instance
def get_db(self):
if len(self.db_connections) < self.count:
return self.create_new_connection()
index = randrange(0, len(self.db_connections))
connection = self.db_connections[index]
if (time.time() - connection.start_time) > self.lifetime:
removed = self.db_connections.pop(index)
removed.close()
return self.create_new_connection()
return self.db_connections[index]
def get_db_class(self):
raise NotImplementedError('The "get_db_class" method is not implemented')
class Database(object):
def __init__(self, connection):
if not isinstance(connection, Connection):
raise error.StormError('connection must be instance of storm.db.Connection')
self.connection = connection
self.is_connected = False
self.start_time = time.time()
Make connection pool less smart
You have to extend it and implement your own get_db function to use a
connection pool now
|
import time
from storm import error
from tornado import gen
class Connection(object):
def __init__(self, host='localhost', port=None, database=None, user=None, password=None):
self.host = host
self.port = port
self.database = database
self.user = user
self.password = password
class ConnectionPool(object):
def __init__(self, connection, count=10, lifetime=3600):
self.connection = connection
self.count = count
self.lifetime = lifetime
@gen.coroutine
def get_db(self, callback=None):
raise NotImplementedError('The "get_db" method is not implemented')
def get_db_class(self):
raise NotImplementedError('The "get_db_class" method is not implemented')
class Database(object):
def __init__(self, connection):
if not isinstance(connection, Connection):
raise error.StormError('connection must be instance of storm.db.Connection')
self.connection = connection
self.is_connected = False
self.start_time = time.time()
|
<commit_before>from random import randrange
import time
from storm import error
class Connection(object):
def __init__(self, host='localhost', port=None, database=None, user=None, password=None):
self.host = host
self.port = port
self.database = database
self.user = user
self.password = password
class ConnectionPool(object):
def __init__(self, connection, count=10, lifetime=3600):
self.connection = connection
self.count = count
self.lifetime = lifetime
self.db_connections = [];
def create_new_connection(self):
cls = self.get_db_class()
instance = cls(self.connection)
self.db_connections.append(instance)
return instance
def get_db(self):
if len(self.db_connections) < self.count:
return self.create_new_connection()
index = randrange(0, len(self.db_connections))
connection = self.db_connections[index]
if (time.time() - connection.start_time) > self.lifetime:
removed = self.db_connections.pop(index)
removed.close()
return self.create_new_connection()
return self.db_connections[index]
def get_db_class(self):
raise NotImplementedError('The "get_db_class" method is not implemented')
class Database(object):
def __init__(self, connection):
if not isinstance(connection, Connection):
raise error.StormError('connection must be instance of storm.db.Connection')
self.connection = connection
self.is_connected = False
self.start_time = time.time()
<commit_msg>Make connection pool less smart
You have to extend it and implement your own get_db function to use a
connection pool now<commit_after>
|
import time
from storm import error
from tornado import gen
class Connection(object):
def __init__(self, host='localhost', port=None, database=None, user=None, password=None):
self.host = host
self.port = port
self.database = database
self.user = user
self.password = password
class ConnectionPool(object):
def __init__(self, connection, count=10, lifetime=3600):
self.connection = connection
self.count = count
self.lifetime = lifetime
@gen.coroutine
def get_db(self, callback=None):
raise NotImplementedError('The "get_db" method is not implemented')
def get_db_class(self):
raise NotImplementedError('The "get_db_class" method is not implemented')
class Database(object):
def __init__(self, connection):
if not isinstance(connection, Connection):
raise error.StormError('connection must be instance of storm.db.Connection')
self.connection = connection
self.is_connected = False
self.start_time = time.time()
|
from random import randrange
import time
from storm import error
class Connection(object):
def __init__(self, host='localhost', port=None, database=None, user=None, password=None):
self.host = host
self.port = port
self.database = database
self.user = user
self.password = password
class ConnectionPool(object):
def __init__(self, connection, count=10, lifetime=3600):
self.connection = connection
self.count = count
self.lifetime = lifetime
self.db_connections = [];
def create_new_connection(self):
cls = self.get_db_class()
instance = cls(self.connection)
self.db_connections.append(instance)
return instance
def get_db(self):
if len(self.db_connections) < self.count:
return self.create_new_connection()
index = randrange(0, len(self.db_connections))
connection = self.db_connections[index]
if (time.time() - connection.start_time) > self.lifetime:
removed = self.db_connections.pop(index)
removed.close()
return self.create_new_connection()
return self.db_connections[index]
def get_db_class(self):
raise NotImplementedError('The "get_db_class" method is not implemented')
class Database(object):
def __init__(self, connection):
if not isinstance(connection, Connection):
raise error.StormError('connection must be instance of storm.db.Connection')
self.connection = connection
self.is_connected = False
self.start_time = time.time()
Make connection pool less smart
You have to extend it and implement your own get_db function to use a
connection pool nowimport time
from storm import error
from tornado import gen
class Connection(object):
def __init__(self, host='localhost', port=None, database=None, user=None, password=None):
self.host = host
self.port = port
self.database = database
self.user = user
self.password = password
class ConnectionPool(object):
def __init__(self, connection, count=10, lifetime=3600):
self.connection = connection
self.count = count
self.lifetime = lifetime
@gen.coroutine
def get_db(self, callback=None):
raise NotImplementedError('The "get_db" method is not implemented')
def get_db_class(self):
raise NotImplementedError('The "get_db_class" method is not implemented')
class Database(object):
def __init__(self, connection):
if not isinstance(connection, Connection):
raise error.StormError('connection must be instance of storm.db.Connection')
self.connection = connection
self.is_connected = False
self.start_time = time.time()
|
<commit_before>from random import randrange
import time
from storm import error
class Connection(object):
def __init__(self, host='localhost', port=None, database=None, user=None, password=None):
self.host = host
self.port = port
self.database = database
self.user = user
self.password = password
class ConnectionPool(object):
def __init__(self, connection, count=10, lifetime=3600):
self.connection = connection
self.count = count
self.lifetime = lifetime
self.db_connections = [];
def create_new_connection(self):
cls = self.get_db_class()
instance = cls(self.connection)
self.db_connections.append(instance)
return instance
def get_db(self):
if len(self.db_connections) < self.count:
return self.create_new_connection()
index = randrange(0, len(self.db_connections))
connection = self.db_connections[index]
if (time.time() - connection.start_time) > self.lifetime:
removed = self.db_connections.pop(index)
removed.close()
return self.create_new_connection()
return self.db_connections[index]
def get_db_class(self):
raise NotImplementedError('The "get_db_class" method is not implemented')
class Database(object):
def __init__(self, connection):
if not isinstance(connection, Connection):
raise error.StormError('connection must be instance of storm.db.Connection')
self.connection = connection
self.is_connected = False
self.start_time = time.time()
<commit_msg>Make connection pool less smart
You have to extend it and implement your own get_db function to use a
connection pool now<commit_after>import time
from storm import error
from tornado import gen
class Connection(object):
def __init__(self, host='localhost', port=None, database=None, user=None, password=None):
self.host = host
self.port = port
self.database = database
self.user = user
self.password = password
class ConnectionPool(object):
def __init__(self, connection, count=10, lifetime=3600):
self.connection = connection
self.count = count
self.lifetime = lifetime
@gen.coroutine
def get_db(self, callback=None):
raise NotImplementedError('The "get_db" method is not implemented')
def get_db_class(self):
raise NotImplementedError('The "get_db_class" method is not implemented')
class Database(object):
def __init__(self, connection):
if not isinstance(connection, Connection):
raise error.StormError('connection must be instance of storm.db.Connection')
self.connection = connection
self.is_connected = False
self.start_time = time.time()
|
2f65eba48e5bdeac85b12cac014cb648d068da46
|
tests/test_utils.py
|
tests/test_utils.py
|
import unittest
from app import create_app, db
from app.utils import get_or_create
from app.models import User
class TestUtils(unittest.TestCase):
def setUp(self):
self.app = create_app("testing")
self.app_ctx = self.app.app_context()
self.app_ctx.push()
db.create_all()
def tearDown(self):
db.session.remove()
db.drop_all()
self.app_ctx.pop()
def test_get_or_create(self):
user1, created1 = get_or_create(User, name="foo", social_id="bar")
db.session.add(user1)
db.session.commit()
user2, created2 = get_or_create(User, name="foo", social_id="bar")
self.assertTrue(created1)
self.assertFalse(created2)
self.assertEquals(user1, user2)
|
import unittest
from app import create_app, db
from app.utils import get_or_create, is_safe_url
from app.models import User
class TestUtils(unittest.TestCase):
def setUp(self):
self.app = create_app("testing")
self.app_ctx = self.app.app_context()
self.app_ctx.push()
db.create_all()
def tearDown(self):
db.session.remove()
db.drop_all()
self.app_ctx.pop()
def test_get_or_create(self):
user1, created1 = get_or_create(User, name="foo", social_id="bar")
db.session.add(user1)
db.session.commit()
user2, created2 = get_or_create(User, name="foo", social_id="bar")
self.assertTrue(created1)
self.assertFalse(created2)
self.assertEquals(user1, user2)
def test_is_safe_url(self):
with self.app.test_request_context():
self.assertFalse(is_safe_url("http://externalsite.com"))
self.assertTrue(is_safe_url("http://" + self.app.config["SERVER_NAME"]))
self.assertTrue(is_safe_url("safe_internal_link"))
|
Add unit test for is_safe_url utility function
|
Add unit test for is_safe_url utility function
|
Python
|
mit
|
Encrylize/MyDictionary,Encrylize/MyDictionary,Encrylize/MyDictionary
|
import unittest
from app import create_app, db
from app.utils import get_or_create
from app.models import User
class TestUtils(unittest.TestCase):
def setUp(self):
self.app = create_app("testing")
self.app_ctx = self.app.app_context()
self.app_ctx.push()
db.create_all()
def tearDown(self):
db.session.remove()
db.drop_all()
self.app_ctx.pop()
def test_get_or_create(self):
user1, created1 = get_or_create(User, name="foo", social_id="bar")
db.session.add(user1)
db.session.commit()
user2, created2 = get_or_create(User, name="foo", social_id="bar")
self.assertTrue(created1)
self.assertFalse(created2)
self.assertEquals(user1, user2)Add unit test for is_safe_url utility function
|
import unittest
from app import create_app, db
from app.utils import get_or_create, is_safe_url
from app.models import User
class TestUtils(unittest.TestCase):
def setUp(self):
self.app = create_app("testing")
self.app_ctx = self.app.app_context()
self.app_ctx.push()
db.create_all()
def tearDown(self):
db.session.remove()
db.drop_all()
self.app_ctx.pop()
def test_get_or_create(self):
user1, created1 = get_or_create(User, name="foo", social_id="bar")
db.session.add(user1)
db.session.commit()
user2, created2 = get_or_create(User, name="foo", social_id="bar")
self.assertTrue(created1)
self.assertFalse(created2)
self.assertEquals(user1, user2)
def test_is_safe_url(self):
with self.app.test_request_context():
self.assertFalse(is_safe_url("http://externalsite.com"))
self.assertTrue(is_safe_url("http://" + self.app.config["SERVER_NAME"]))
self.assertTrue(is_safe_url("safe_internal_link"))
|
<commit_before>import unittest
from app import create_app, db
from app.utils import get_or_create
from app.models import User
class TestUtils(unittest.TestCase):
def setUp(self):
self.app = create_app("testing")
self.app_ctx = self.app.app_context()
self.app_ctx.push()
db.create_all()
def tearDown(self):
db.session.remove()
db.drop_all()
self.app_ctx.pop()
def test_get_or_create(self):
user1, created1 = get_or_create(User, name="foo", social_id="bar")
db.session.add(user1)
db.session.commit()
user2, created2 = get_or_create(User, name="foo", social_id="bar")
self.assertTrue(created1)
self.assertFalse(created2)
self.assertEquals(user1, user2)<commit_msg>Add unit test for is_safe_url utility function<commit_after>
|
import unittest
from app import create_app, db
from app.utils import get_or_create, is_safe_url
from app.models import User
class TestUtils(unittest.TestCase):
def setUp(self):
self.app = create_app("testing")
self.app_ctx = self.app.app_context()
self.app_ctx.push()
db.create_all()
def tearDown(self):
db.session.remove()
db.drop_all()
self.app_ctx.pop()
def test_get_or_create(self):
user1, created1 = get_or_create(User, name="foo", social_id="bar")
db.session.add(user1)
db.session.commit()
user2, created2 = get_or_create(User, name="foo", social_id="bar")
self.assertTrue(created1)
self.assertFalse(created2)
self.assertEquals(user1, user2)
def test_is_safe_url(self):
with self.app.test_request_context():
self.assertFalse(is_safe_url("http://externalsite.com"))
self.assertTrue(is_safe_url("http://" + self.app.config["SERVER_NAME"]))
self.assertTrue(is_safe_url("safe_internal_link"))
|
import unittest
from app import create_app, db
from app.utils import get_or_create
from app.models import User
class TestUtils(unittest.TestCase):
def setUp(self):
self.app = create_app("testing")
self.app_ctx = self.app.app_context()
self.app_ctx.push()
db.create_all()
def tearDown(self):
db.session.remove()
db.drop_all()
self.app_ctx.pop()
def test_get_or_create(self):
user1, created1 = get_or_create(User, name="foo", social_id="bar")
db.session.add(user1)
db.session.commit()
user2, created2 = get_or_create(User, name="foo", social_id="bar")
self.assertTrue(created1)
self.assertFalse(created2)
self.assertEquals(user1, user2)Add unit test for is_safe_url utility functionimport unittest
from app import create_app, db
from app.utils import get_or_create, is_safe_url
from app.models import User
class TestUtils(unittest.TestCase):
def setUp(self):
self.app = create_app("testing")
self.app_ctx = self.app.app_context()
self.app_ctx.push()
db.create_all()
def tearDown(self):
db.session.remove()
db.drop_all()
self.app_ctx.pop()
def test_get_or_create(self):
user1, created1 = get_or_create(User, name="foo", social_id="bar")
db.session.add(user1)
db.session.commit()
user2, created2 = get_or_create(User, name="foo", social_id="bar")
self.assertTrue(created1)
self.assertFalse(created2)
self.assertEquals(user1, user2)
def test_is_safe_url(self):
with self.app.test_request_context():
self.assertFalse(is_safe_url("http://externalsite.com"))
self.assertTrue(is_safe_url("http://" + self.app.config["SERVER_NAME"]))
self.assertTrue(is_safe_url("safe_internal_link"))
|
<commit_before>import unittest
from app import create_app, db
from app.utils import get_or_create
from app.models import User
class TestUtils(unittest.TestCase):
def setUp(self):
self.app = create_app("testing")
self.app_ctx = self.app.app_context()
self.app_ctx.push()
db.create_all()
def tearDown(self):
db.session.remove()
db.drop_all()
self.app_ctx.pop()
def test_get_or_create(self):
user1, created1 = get_or_create(User, name="foo", social_id="bar")
db.session.add(user1)
db.session.commit()
user2, created2 = get_or_create(User, name="foo", social_id="bar")
self.assertTrue(created1)
self.assertFalse(created2)
self.assertEquals(user1, user2)<commit_msg>Add unit test for is_safe_url utility function<commit_after>import unittest
from app import create_app, db
from app.utils import get_or_create, is_safe_url
from app.models import User
class TestUtils(unittest.TestCase):
def setUp(self):
self.app = create_app("testing")
self.app_ctx = self.app.app_context()
self.app_ctx.push()
db.create_all()
def tearDown(self):
db.session.remove()
db.drop_all()
self.app_ctx.pop()
def test_get_or_create(self):
user1, created1 = get_or_create(User, name="foo", social_id="bar")
db.session.add(user1)
db.session.commit()
user2, created2 = get_or_create(User, name="foo", social_id="bar")
self.assertTrue(created1)
self.assertFalse(created2)
self.assertEquals(user1, user2)
def test_is_safe_url(self):
with self.app.test_request_context():
self.assertFalse(is_safe_url("http://externalsite.com"))
self.assertTrue(is_safe_url("http://" + self.app.config["SERVER_NAME"]))
self.assertTrue(is_safe_url("safe_internal_link"))
|
b33654567ad3588ba51874ef109a9ee8efc0b0f0
|
tests/functional/firefox/test_hello.py
|
tests/functional/firefox/test_hello.py
|
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import pytest
from pages.firefox.hello import HelloPage
@pytest.mark.smoke
@pytest.mark.nondestructive
def test_play_video(base_url, selenium):
page = HelloPage(base_url, selenium).open()
video = page.play_video()
assert video.is_displayed
video.close()
@pytest.mark.skip_if_not_firefox
@pytest.mark.smoke
@pytest.mark.nondestructive
def test_try_hello_button_is_displayed(base_url, selenium):
page = HelloPage(base_url, selenium).open()
assert page.is_try_hello_button_displayed
assert not page.is_download_button_displayed
@pytest.mark.skip_if_firefox
@pytest.mark.smoke
@pytest.mark.nondestructive
def test_download_button_is_displayed(base_url, selenium):
page = HelloPage(base_url, selenium).open()
assert page.is_download_button_displayed
assert not page.is_try_hello_button_displayed
|
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import pytest
from pages.firefox.hello import HelloPage
@pytest.mark.smoke
@pytest.mark.nondestructive
def test_play_video(base_url, selenium):
page = HelloPage(base_url, selenium).open()
video = page.play_video()
assert video.is_displayed
video.close()
@pytest.mark.skip_if_not_firefox
@pytest.mark.smoke
@pytest.mark.nondestructive
def test_try_hello_button_is_displayed(base_url, selenium):
page = HelloPage(base_url, selenium).open()
assert page.is_try_hello_button_displayed
@pytest.mark.skip_if_firefox
@pytest.mark.smoke
@pytest.mark.nondestructive
def test_download_button_is_displayed(base_url, selenium):
page = HelloPage(base_url, selenium).open()
assert page.is_download_button_displayed
assert not page.is_try_hello_button_displayed
|
Fix failing Firefox Hello test
|
Fix failing Firefox Hello test
|
Python
|
mpl-2.0
|
sgarrity/bedrock,TheJJ100100/bedrock,alexgibson/bedrock,schalkneethling/bedrock,TheJJ100100/bedrock,gerv/bedrock,mozilla/bedrock,flodolo/bedrock,kyoshino/bedrock,TheoChevalier/bedrock,mozilla/bedrock,sgarrity/bedrock,craigcook/bedrock,pascalchevrel/bedrock,alexgibson/bedrock,sylvestre/bedrock,Sancus/bedrock,ericawright/bedrock,TheJJ100100/bedrock,analytics-pros/mozilla-bedrock,flodolo/bedrock,glogiotatidis/bedrock,MichaelKohler/bedrock,mkmelin/bedrock,mozilla/bedrock,CSCI-462-01-2017/bedrock,jpetto/bedrock,alexgibson/bedrock,alexgibson/bedrock,flodolo/bedrock,sylvestre/bedrock,glogiotatidis/bedrock,schalkneethling/bedrock,hoosteeno/bedrock,jgmize/bedrock,Sancus/bedrock,jpetto/bedrock,schalkneethling/bedrock,hoosteeno/bedrock,mkmelin/bedrock,TheoChevalier/bedrock,gerv/bedrock,hoosteeno/bedrock,TheJJ100100/bedrock,analytics-pros/mozilla-bedrock,hoosteeno/bedrock,flodolo/bedrock,sgarrity/bedrock,mkmelin/bedrock,TheoChevalier/bedrock,pascalchevrel/bedrock,craigcook/bedrock,ericawright/bedrock,Sancus/bedrock,MichaelKohler/bedrock,jpetto/bedrock,schalkneethling/bedrock,mkmelin/bedrock,jpetto/bedrock,CSCI-462-01-2017/bedrock,sgarrity/bedrock,glogiotatidis/bedrock,mozilla/bedrock,Sancus/bedrock,jgmize/bedrock,pascalchevrel/bedrock,TheoChevalier/bedrock,craigcook/bedrock,MichaelKohler/bedrock,CSCI-462-01-2017/bedrock,craigcook/bedrock,kyoshino/bedrock,jgmize/bedrock,jgmize/bedrock,gerv/bedrock,sylvestre/bedrock,gerv/bedrock,CSCI-462-01-2017/bedrock,pascalchevrel/bedrock,ericawright/bedrock,kyoshino/bedrock,analytics-pros/mozilla-bedrock,ericawright/bedrock,analytics-pros/mozilla-bedrock,MichaelKohler/bedrock,kyoshino/bedrock,sylvestre/bedrock,glogiotatidis/bedrock
|
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import pytest
from pages.firefox.hello import HelloPage
@pytest.mark.smoke
@pytest.mark.nondestructive
def test_play_video(base_url, selenium):
page = HelloPage(base_url, selenium).open()
video = page.play_video()
assert video.is_displayed
video.close()
@pytest.mark.skip_if_not_firefox
@pytest.mark.smoke
@pytest.mark.nondestructive
def test_try_hello_button_is_displayed(base_url, selenium):
page = HelloPage(base_url, selenium).open()
assert page.is_try_hello_button_displayed
assert not page.is_download_button_displayed
@pytest.mark.skip_if_firefox
@pytest.mark.smoke
@pytest.mark.nondestructive
def test_download_button_is_displayed(base_url, selenium):
page = HelloPage(base_url, selenium).open()
assert page.is_download_button_displayed
assert not page.is_try_hello_button_displayed
Fix failing Firefox Hello test
|
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import pytest
from pages.firefox.hello import HelloPage
@pytest.mark.smoke
@pytest.mark.nondestructive
def test_play_video(base_url, selenium):
page = HelloPage(base_url, selenium).open()
video = page.play_video()
assert video.is_displayed
video.close()
@pytest.mark.skip_if_not_firefox
@pytest.mark.smoke
@pytest.mark.nondestructive
def test_try_hello_button_is_displayed(base_url, selenium):
page = HelloPage(base_url, selenium).open()
assert page.is_try_hello_button_displayed
@pytest.mark.skip_if_firefox
@pytest.mark.smoke
@pytest.mark.nondestructive
def test_download_button_is_displayed(base_url, selenium):
page = HelloPage(base_url, selenium).open()
assert page.is_download_button_displayed
assert not page.is_try_hello_button_displayed
|
<commit_before># This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import pytest
from pages.firefox.hello import HelloPage
@pytest.mark.smoke
@pytest.mark.nondestructive
def test_play_video(base_url, selenium):
page = HelloPage(base_url, selenium).open()
video = page.play_video()
assert video.is_displayed
video.close()
@pytest.mark.skip_if_not_firefox
@pytest.mark.smoke
@pytest.mark.nondestructive
def test_try_hello_button_is_displayed(base_url, selenium):
page = HelloPage(base_url, selenium).open()
assert page.is_try_hello_button_displayed
assert not page.is_download_button_displayed
@pytest.mark.skip_if_firefox
@pytest.mark.smoke
@pytest.mark.nondestructive
def test_download_button_is_displayed(base_url, selenium):
page = HelloPage(base_url, selenium).open()
assert page.is_download_button_displayed
assert not page.is_try_hello_button_displayed
<commit_msg>Fix failing Firefox Hello test<commit_after>
|
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import pytest
from pages.firefox.hello import HelloPage
@pytest.mark.smoke
@pytest.mark.nondestructive
def test_play_video(base_url, selenium):
page = HelloPage(base_url, selenium).open()
video = page.play_video()
assert video.is_displayed
video.close()
@pytest.mark.skip_if_not_firefox
@pytest.mark.smoke
@pytest.mark.nondestructive
def test_try_hello_button_is_displayed(base_url, selenium):
page = HelloPage(base_url, selenium).open()
assert page.is_try_hello_button_displayed
@pytest.mark.skip_if_firefox
@pytest.mark.smoke
@pytest.mark.nondestructive
def test_download_button_is_displayed(base_url, selenium):
page = HelloPage(base_url, selenium).open()
assert page.is_download_button_displayed
assert not page.is_try_hello_button_displayed
|
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import pytest
from pages.firefox.hello import HelloPage
@pytest.mark.smoke
@pytest.mark.nondestructive
def test_play_video(base_url, selenium):
page = HelloPage(base_url, selenium).open()
video = page.play_video()
assert video.is_displayed
video.close()
@pytest.mark.skip_if_not_firefox
@pytest.mark.smoke
@pytest.mark.nondestructive
def test_try_hello_button_is_displayed(base_url, selenium):
page = HelloPage(base_url, selenium).open()
assert page.is_try_hello_button_displayed
assert not page.is_download_button_displayed
@pytest.mark.skip_if_firefox
@pytest.mark.smoke
@pytest.mark.nondestructive
def test_download_button_is_displayed(base_url, selenium):
page = HelloPage(base_url, selenium).open()
assert page.is_download_button_displayed
assert not page.is_try_hello_button_displayed
Fix failing Firefox Hello test# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import pytest
from pages.firefox.hello import HelloPage
@pytest.mark.smoke
@pytest.mark.nondestructive
def test_play_video(base_url, selenium):
page = HelloPage(base_url, selenium).open()
video = page.play_video()
assert video.is_displayed
video.close()
@pytest.mark.skip_if_not_firefox
@pytest.mark.smoke
@pytest.mark.nondestructive
def test_try_hello_button_is_displayed(base_url, selenium):
page = HelloPage(base_url, selenium).open()
assert page.is_try_hello_button_displayed
@pytest.mark.skip_if_firefox
@pytest.mark.smoke
@pytest.mark.nondestructive
def test_download_button_is_displayed(base_url, selenium):
page = HelloPage(base_url, selenium).open()
assert page.is_download_button_displayed
assert not page.is_try_hello_button_displayed
|
<commit_before># This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import pytest
from pages.firefox.hello import HelloPage
@pytest.mark.smoke
@pytest.mark.nondestructive
def test_play_video(base_url, selenium):
page = HelloPage(base_url, selenium).open()
video = page.play_video()
assert video.is_displayed
video.close()
@pytest.mark.skip_if_not_firefox
@pytest.mark.smoke
@pytest.mark.nondestructive
def test_try_hello_button_is_displayed(base_url, selenium):
page = HelloPage(base_url, selenium).open()
assert page.is_try_hello_button_displayed
assert not page.is_download_button_displayed
@pytest.mark.skip_if_firefox
@pytest.mark.smoke
@pytest.mark.nondestructive
def test_download_button_is_displayed(base_url, selenium):
page = HelloPage(base_url, selenium).open()
assert page.is_download_button_displayed
assert not page.is_try_hello_button_displayed
<commit_msg>Fix failing Firefox Hello test<commit_after># This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import pytest
from pages.firefox.hello import HelloPage
@pytest.mark.smoke
@pytest.mark.nondestructive
def test_play_video(base_url, selenium):
page = HelloPage(base_url, selenium).open()
video = page.play_video()
assert video.is_displayed
video.close()
@pytest.mark.skip_if_not_firefox
@pytest.mark.smoke
@pytest.mark.nondestructive
def test_try_hello_button_is_displayed(base_url, selenium):
page = HelloPage(base_url, selenium).open()
assert page.is_try_hello_button_displayed
@pytest.mark.skip_if_firefox
@pytest.mark.smoke
@pytest.mark.nondestructive
def test_download_button_is_displayed(base_url, selenium):
page = HelloPage(base_url, selenium).open()
assert page.is_download_button_displayed
assert not page.is_try_hello_button_displayed
|
df790275ba9f06296f800ecd913eca8393c300c6
|
psyparse/handler/base_handler.py
|
psyparse/handler/base_handler.py
|
class BaseHandler(object):
"""
An abstract hanlder class to help define how a handler should behave. No
methods are actually implemented and will raise a not-implemented error
if an instance of a handler subclass does not implement any of the
following methods.
"""
def new(self, entry):
"""Create a new entry"""
raise ("""'new' method not defined in handler subclass""")
def update(self, entry, attribute, new_value):
"""Update a given entry. This is useful when properties of a given
entry are only discovered sometime later in parsing."""
raise("""'update' method not defined in handler subclass""")
|
class BaseHandler(object):
"""
An abstract hanlder class to help define how a handler should behave. No
methods are actually implemented and will raise a not-implemented error
if an instance of a handler subclass does not implement any of the
following methods.
"""
def new(self, entry):
"""Create a new entry"""
raise Exception("""'new' method not defined in handler subclass""")
def update(self, entry, attribute, new_value):
"""Update a given entry. This is useful when properties of a given
entry are only discovered sometime later in parsing."""
raise Exception("""'update' method not defined in handler subclass""")
|
Fix bug in exception throwing (it caused an exception!).
|
Fix bug in exception throwing (it caused an exception!).
|
Python
|
mit
|
tnez/PsyParse
|
class BaseHandler(object):
"""
An abstract hanlder class to help define how a handler should behave. No
methods are actually implemented and will raise a not-implemented error
if an instance of a handler subclass does not implement any of the
following methods.
"""
def new(self, entry):
"""Create a new entry"""
raise ("""'new' method not defined in handler subclass""")
def update(self, entry, attribute, new_value):
"""Update a given entry. This is useful when properties of a given
entry are only discovered sometime later in parsing."""
raise("""'update' method not defined in handler subclass""")
Fix bug in exception throwing (it caused an exception!).
|
class BaseHandler(object):
"""
An abstract hanlder class to help define how a handler should behave. No
methods are actually implemented and will raise a not-implemented error
if an instance of a handler subclass does not implement any of the
following methods.
"""
def new(self, entry):
"""Create a new entry"""
raise Exception("""'new' method not defined in handler subclass""")
def update(self, entry, attribute, new_value):
"""Update a given entry. This is useful when properties of a given
entry are only discovered sometime later in parsing."""
raise Exception("""'update' method not defined in handler subclass""")
|
<commit_before>class BaseHandler(object):
"""
An abstract hanlder class to help define how a handler should behave. No
methods are actually implemented and will raise a not-implemented error
if an instance of a handler subclass does not implement any of the
following methods.
"""
def new(self, entry):
"""Create a new entry"""
raise ("""'new' method not defined in handler subclass""")
def update(self, entry, attribute, new_value):
"""Update a given entry. This is useful when properties of a given
entry are only discovered sometime later in parsing."""
raise("""'update' method not defined in handler subclass""")
<commit_msg>Fix bug in exception throwing (it caused an exception!).<commit_after>
|
class BaseHandler(object):
"""
An abstract hanlder class to help define how a handler should behave. No
methods are actually implemented and will raise a not-implemented error
if an instance of a handler subclass does not implement any of the
following methods.
"""
def new(self, entry):
"""Create a new entry"""
raise Exception("""'new' method not defined in handler subclass""")
def update(self, entry, attribute, new_value):
"""Update a given entry. This is useful when properties of a given
entry are only discovered sometime later in parsing."""
raise Exception("""'update' method not defined in handler subclass""")
|
class BaseHandler(object):
"""
An abstract hanlder class to help define how a handler should behave. No
methods are actually implemented and will raise a not-implemented error
if an instance of a handler subclass does not implement any of the
following methods.
"""
def new(self, entry):
"""Create a new entry"""
raise ("""'new' method not defined in handler subclass""")
def update(self, entry, attribute, new_value):
"""Update a given entry. This is useful when properties of a given
entry are only discovered sometime later in parsing."""
raise("""'update' method not defined in handler subclass""")
Fix bug in exception throwing (it caused an exception!).class BaseHandler(object):
"""
An abstract hanlder class to help define how a handler should behave. No
methods are actually implemented and will raise a not-implemented error
if an instance of a handler subclass does not implement any of the
following methods.
"""
def new(self, entry):
"""Create a new entry"""
raise Exception("""'new' method not defined in handler subclass""")
def update(self, entry, attribute, new_value):
"""Update a given entry. This is useful when properties of a given
entry are only discovered sometime later in parsing."""
raise Exception("""'update' method not defined in handler subclass""")
|
<commit_before>class BaseHandler(object):
"""
An abstract hanlder class to help define how a handler should behave. No
methods are actually implemented and will raise a not-implemented error
if an instance of a handler subclass does not implement any of the
following methods.
"""
def new(self, entry):
"""Create a new entry"""
raise ("""'new' method not defined in handler subclass""")
def update(self, entry, attribute, new_value):
"""Update a given entry. This is useful when properties of a given
entry are only discovered sometime later in parsing."""
raise("""'update' method not defined in handler subclass""")
<commit_msg>Fix bug in exception throwing (it caused an exception!).<commit_after>class BaseHandler(object):
"""
An abstract hanlder class to help define how a handler should behave. No
methods are actually implemented and will raise a not-implemented error
if an instance of a handler subclass does not implement any of the
following methods.
"""
def new(self, entry):
"""Create a new entry"""
raise Exception("""'new' method not defined in handler subclass""")
def update(self, entry, attribute, new_value):
"""Update a given entry. This is useful when properties of a given
entry are only discovered sometime later in parsing."""
raise Exception("""'update' method not defined in handler subclass""")
|
567d7c57def91c95620e8e5b1acda640b9c48a9d
|
src/startGUI.py
|
src/startGUI.py
|
# -*- coding: utf-8 -*-
import util.colored_exceptions
from gui import main_window
from core import volumes, control
from PySide import QtGui
import sys
import os
import core.calculation
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
control = control.Control()
window = main_window.MainWindow(control)
app.setOrganizationName("Forschungszentrum Jülich GmbH")
app.setOrganizationDomain("fz-juelich.de")
app.setApplicationName("pyMolDyn 2")
# filename = '../xyz/generated2.xyz'
# filename = '../xyz/generated.xyz'
# filename = '../xyz/traject_200.xyz'
# filename = '../xyz/GST_111_196_bulk.xyz'
filename = '../xyz/structure_c.xyz'
# filename = '../xyz/hexagonal.xyz'
control = window.control
settings = core.calculation.CalculationSettings([filename], [0], 32, domains=False, surface_cavities=False, center_cavities=False)
control.calculate(settings)
control.update()
window.updatestatus()
sys.exit(app.exec_())
|
# -*- coding: utf-8 -*-
import util.colored_exceptions
from gui import main_window
from core import volumes, control
from PySide import QtGui
from PySide import QtCore
import signal
import sys
import os
import core.calculation
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
control = control.Control()
window = main_window.MainWindow(control)
app.setOrganizationName("Forschungszentrum Jülich GmbH")
app.setOrganizationDomain("fz-juelich.de")
app.setApplicationName("pyMolDyn 2")
# filename = '../xyz/generated2.xyz'
# filename = '../xyz/generated.xyz'
# filename = '../xyz/traject_200.xyz'
# filename = '../xyz/GST_111_196_bulk.xyz'
filename = '../xyz/structure_c.xyz'
# filename = '../xyz/hexagonal.xyz'
control = window.control
settings = core.calculation.CalculationSettings([filename], [0], 32, domains=False, surface_cavities=False, center_cavities=False)
control.calculate(settings)
control.update()
window.updatestatus()
# Let the Python interpreter run every 50ms...
timer = QtCore.QTimer()
timer.start(50)
timer.timeout.connect(lambda: None)
# ... to allow it to quit the application on SIGINT (Ctrl-C)
signal.signal(signal.SIGINT, lambda *args: app.quit())
sys.exit(app.exec_())
|
Allow quitting the application with SIGINT (Ctrl-C)
|
Allow quitting the application with SIGINT (Ctrl-C)
|
Python
|
mit
|
sciapp/pyMolDyn,sciapp/pyMolDyn,sciapp/pyMolDyn,sciapp/pyMolDyn,sciapp/pyMolDyn
|
# -*- coding: utf-8 -*-
import util.colored_exceptions
from gui import main_window
from core import volumes, control
from PySide import QtGui
import sys
import os
import core.calculation
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
control = control.Control()
window = main_window.MainWindow(control)
app.setOrganizationName("Forschungszentrum Jülich GmbH")
app.setOrganizationDomain("fz-juelich.de")
app.setApplicationName("pyMolDyn 2")
# filename = '../xyz/generated2.xyz'
# filename = '../xyz/generated.xyz'
# filename = '../xyz/traject_200.xyz'
# filename = '../xyz/GST_111_196_bulk.xyz'
filename = '../xyz/structure_c.xyz'
# filename = '../xyz/hexagonal.xyz'
control = window.control
settings = core.calculation.CalculationSettings([filename], [0], 32, domains=False, surface_cavities=False, center_cavities=False)
control.calculate(settings)
control.update()
window.updatestatus()
sys.exit(app.exec_())
Allow quitting the application with SIGINT (Ctrl-C)
|
# -*- coding: utf-8 -*-
import util.colored_exceptions
from gui import main_window
from core import volumes, control
from PySide import QtGui
from PySide import QtCore
import signal
import sys
import os
import core.calculation
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
control = control.Control()
window = main_window.MainWindow(control)
app.setOrganizationName("Forschungszentrum Jülich GmbH")
app.setOrganizationDomain("fz-juelich.de")
app.setApplicationName("pyMolDyn 2")
# filename = '../xyz/generated2.xyz'
# filename = '../xyz/generated.xyz'
# filename = '../xyz/traject_200.xyz'
# filename = '../xyz/GST_111_196_bulk.xyz'
filename = '../xyz/structure_c.xyz'
# filename = '../xyz/hexagonal.xyz'
control = window.control
settings = core.calculation.CalculationSettings([filename], [0], 32, domains=False, surface_cavities=False, center_cavities=False)
control.calculate(settings)
control.update()
window.updatestatus()
# Let the Python interpreter run every 50ms...
timer = QtCore.QTimer()
timer.start(50)
timer.timeout.connect(lambda: None)
# ... to allow it to quit the application on SIGINT (Ctrl-C)
signal.signal(signal.SIGINT, lambda *args: app.quit())
sys.exit(app.exec_())
|
<commit_before># -*- coding: utf-8 -*-
import util.colored_exceptions
from gui import main_window
from core import volumes, control
from PySide import QtGui
import sys
import os
import core.calculation
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
control = control.Control()
window = main_window.MainWindow(control)
app.setOrganizationName("Forschungszentrum Jülich GmbH")
app.setOrganizationDomain("fz-juelich.de")
app.setApplicationName("pyMolDyn 2")
# filename = '../xyz/generated2.xyz'
# filename = '../xyz/generated.xyz'
# filename = '../xyz/traject_200.xyz'
# filename = '../xyz/GST_111_196_bulk.xyz'
filename = '../xyz/structure_c.xyz'
# filename = '../xyz/hexagonal.xyz'
control = window.control
settings = core.calculation.CalculationSettings([filename], [0], 32, domains=False, surface_cavities=False, center_cavities=False)
control.calculate(settings)
control.update()
window.updatestatus()
sys.exit(app.exec_())
<commit_msg>Allow quitting the application with SIGINT (Ctrl-C)<commit_after>
|
# -*- coding: utf-8 -*-
import util.colored_exceptions
from gui import main_window
from core import volumes, control
from PySide import QtGui
from PySide import QtCore
import signal
import sys
import os
import core.calculation
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
control = control.Control()
window = main_window.MainWindow(control)
app.setOrganizationName("Forschungszentrum Jülich GmbH")
app.setOrganizationDomain("fz-juelich.de")
app.setApplicationName("pyMolDyn 2")
# filename = '../xyz/generated2.xyz'
# filename = '../xyz/generated.xyz'
# filename = '../xyz/traject_200.xyz'
# filename = '../xyz/GST_111_196_bulk.xyz'
filename = '../xyz/structure_c.xyz'
# filename = '../xyz/hexagonal.xyz'
control = window.control
settings = core.calculation.CalculationSettings([filename], [0], 32, domains=False, surface_cavities=False, center_cavities=False)
control.calculate(settings)
control.update()
window.updatestatus()
# Let the Python interpreter run every 50ms...
timer = QtCore.QTimer()
timer.start(50)
timer.timeout.connect(lambda: None)
# ... to allow it to quit the application on SIGINT (Ctrl-C)
signal.signal(signal.SIGINT, lambda *args: app.quit())
sys.exit(app.exec_())
|
# -*- coding: utf-8 -*-
import util.colored_exceptions
from gui import main_window
from core import volumes, control
from PySide import QtGui
import sys
import os
import core.calculation
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
control = control.Control()
window = main_window.MainWindow(control)
app.setOrganizationName("Forschungszentrum Jülich GmbH")
app.setOrganizationDomain("fz-juelich.de")
app.setApplicationName("pyMolDyn 2")
# filename = '../xyz/generated2.xyz'
# filename = '../xyz/generated.xyz'
# filename = '../xyz/traject_200.xyz'
# filename = '../xyz/GST_111_196_bulk.xyz'
filename = '../xyz/structure_c.xyz'
# filename = '../xyz/hexagonal.xyz'
control = window.control
settings = core.calculation.CalculationSettings([filename], [0], 32, domains=False, surface_cavities=False, center_cavities=False)
control.calculate(settings)
control.update()
window.updatestatus()
sys.exit(app.exec_())
Allow quitting the application with SIGINT (Ctrl-C)# -*- coding: utf-8 -*-
import util.colored_exceptions
from gui import main_window
from core import volumes, control
from PySide import QtGui
from PySide import QtCore
import signal
import sys
import os
import core.calculation
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
control = control.Control()
window = main_window.MainWindow(control)
app.setOrganizationName("Forschungszentrum Jülich GmbH")
app.setOrganizationDomain("fz-juelich.de")
app.setApplicationName("pyMolDyn 2")
# filename = '../xyz/generated2.xyz'
# filename = '../xyz/generated.xyz'
# filename = '../xyz/traject_200.xyz'
# filename = '../xyz/GST_111_196_bulk.xyz'
filename = '../xyz/structure_c.xyz'
# filename = '../xyz/hexagonal.xyz'
control = window.control
settings = core.calculation.CalculationSettings([filename], [0], 32, domains=False, surface_cavities=False, center_cavities=False)
control.calculate(settings)
control.update()
window.updatestatus()
# Let the Python interpreter run every 50ms...
timer = QtCore.QTimer()
timer.start(50)
timer.timeout.connect(lambda: None)
# ... to allow it to quit the application on SIGINT (Ctrl-C)
signal.signal(signal.SIGINT, lambda *args: app.quit())
sys.exit(app.exec_())
|
<commit_before># -*- coding: utf-8 -*-
import util.colored_exceptions
from gui import main_window
from core import volumes, control
from PySide import QtGui
import sys
import os
import core.calculation
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
control = control.Control()
window = main_window.MainWindow(control)
app.setOrganizationName("Forschungszentrum Jülich GmbH")
app.setOrganizationDomain("fz-juelich.de")
app.setApplicationName("pyMolDyn 2")
# filename = '../xyz/generated2.xyz'
# filename = '../xyz/generated.xyz'
# filename = '../xyz/traject_200.xyz'
# filename = '../xyz/GST_111_196_bulk.xyz'
filename = '../xyz/structure_c.xyz'
# filename = '../xyz/hexagonal.xyz'
control = window.control
settings = core.calculation.CalculationSettings([filename], [0], 32, domains=False, surface_cavities=False, center_cavities=False)
control.calculate(settings)
control.update()
window.updatestatus()
sys.exit(app.exec_())
<commit_msg>Allow quitting the application with SIGINT (Ctrl-C)<commit_after># -*- coding: utf-8 -*-
import util.colored_exceptions
from gui import main_window
from core import volumes, control
from PySide import QtGui
from PySide import QtCore
import signal
import sys
import os
import core.calculation
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
control = control.Control()
window = main_window.MainWindow(control)
app.setOrganizationName("Forschungszentrum Jülich GmbH")
app.setOrganizationDomain("fz-juelich.de")
app.setApplicationName("pyMolDyn 2")
# filename = '../xyz/generated2.xyz'
# filename = '../xyz/generated.xyz'
# filename = '../xyz/traject_200.xyz'
# filename = '../xyz/GST_111_196_bulk.xyz'
filename = '../xyz/structure_c.xyz'
# filename = '../xyz/hexagonal.xyz'
control = window.control
settings = core.calculation.CalculationSettings([filename], [0], 32, domains=False, surface_cavities=False, center_cavities=False)
control.calculate(settings)
control.update()
window.updatestatus()
# Let the Python interpreter run every 50ms...
timer = QtCore.QTimer()
timer.start(50)
timer.timeout.connect(lambda: None)
# ... to allow it to quit the application on SIGINT (Ctrl-C)
signal.signal(signal.SIGINT, lambda *args: app.quit())
sys.exit(app.exec_())
|
370c49eba30253f259454884441e9921b51719ab
|
dudebot/ai.py
|
dudebot/ai.py
|
class BotAI(object):
def set_nickname(self, nickname):
self.nickname = nickname
def initialise(self, init_params_as_dict):
pass
def respond(self, sender_nickname, message):
pass
class Echo(BotAI):
def respond(self, sender_nickname, message):
return True, message
|
class BotAI(object):
def set_nickname(self, nickname):
self.nickname = nickname
def initialise(self, init_params_as_dict):
pass
def respond(self, sender_nickname, message):
return False, ''
class message_must_begin_with_prefix(object):
"""A simple decorator so that a bot AI can ignore all messages that don't
begin with the given prefix.
That way you can have your dude bot only respond to messages that, for
example, begin with 'dude '.
"""
def __init__(self, desired_prefix):
self.desired_prefix = desired_prefix
def __call__(self, func):
def wrapped_func(botai, sender_nickname, message, *args, **kwargs):
if message.startswith(self.desired_prefix):
return func(botai, sender_nickname, message, *args, **kwargs)
else:
return False, ''
return wrapped_func
def message_must_begin_with_nickname(func):
"""A simple decorator so that a bot AI can ignore all messages that don't
begin with the bot AI's nickname.
"""
def wrapped_func(botai, sender_nickname, message, *args, **kwargs):
if message.startswith(botai.nickname):
return func(botai, sender_nickname, message, *args, **kwargs)
else:
return False, ''
return wrapped_func
class Echo(BotAI):
def respond(self, sender_nickname, message):
return True, message
|
Add some decorators to make life easier.
|
Add some decorators to make life easier.
|
Python
|
bsd-2-clause
|
sujaymansingh/dudebot
|
class BotAI(object):
def set_nickname(self, nickname):
self.nickname = nickname
def initialise(self, init_params_as_dict):
pass
def respond(self, sender_nickname, message):
pass
class Echo(BotAI):
def respond(self, sender_nickname, message):
return True, message
Add some decorators to make life easier.
|
class BotAI(object):
def set_nickname(self, nickname):
self.nickname = nickname
def initialise(self, init_params_as_dict):
pass
def respond(self, sender_nickname, message):
return False, ''
class message_must_begin_with_prefix(object):
"""A simple decorator so that a bot AI can ignore all messages that don't
begin with the given prefix.
That way you can have your dude bot only respond to messages that, for
example, begin with 'dude '.
"""
def __init__(self, desired_prefix):
self.desired_prefix = desired_prefix
def __call__(self, func):
def wrapped_func(botai, sender_nickname, message, *args, **kwargs):
if message.startswith(self.desired_prefix):
return func(botai, sender_nickname, message, *args, **kwargs)
else:
return False, ''
return wrapped_func
def message_must_begin_with_nickname(func):
"""A simple decorator so that a bot AI can ignore all messages that don't
begin with the bot AI's nickname.
"""
def wrapped_func(botai, sender_nickname, message, *args, **kwargs):
if message.startswith(botai.nickname):
return func(botai, sender_nickname, message, *args, **kwargs)
else:
return False, ''
return wrapped_func
class Echo(BotAI):
def respond(self, sender_nickname, message):
return True, message
|
<commit_before>class BotAI(object):
def set_nickname(self, nickname):
self.nickname = nickname
def initialise(self, init_params_as_dict):
pass
def respond(self, sender_nickname, message):
pass
class Echo(BotAI):
def respond(self, sender_nickname, message):
return True, message
<commit_msg>Add some decorators to make life easier.<commit_after>
|
class BotAI(object):
def set_nickname(self, nickname):
self.nickname = nickname
def initialise(self, init_params_as_dict):
pass
def respond(self, sender_nickname, message):
return False, ''
class message_must_begin_with_prefix(object):
"""A simple decorator so that a bot AI can ignore all messages that don't
begin with the given prefix.
That way you can have your dude bot only respond to messages that, for
example, begin with 'dude '.
"""
def __init__(self, desired_prefix):
self.desired_prefix = desired_prefix
def __call__(self, func):
def wrapped_func(botai, sender_nickname, message, *args, **kwargs):
if message.startswith(self.desired_prefix):
return func(botai, sender_nickname, message, *args, **kwargs)
else:
return False, ''
return wrapped_func
def message_must_begin_with_nickname(func):
"""A simple decorator so that a bot AI can ignore all messages that don't
begin with the bot AI's nickname.
"""
def wrapped_func(botai, sender_nickname, message, *args, **kwargs):
if message.startswith(botai.nickname):
return func(botai, sender_nickname, message, *args, **kwargs)
else:
return False, ''
return wrapped_func
class Echo(BotAI):
def respond(self, sender_nickname, message):
return True, message
|
class BotAI(object):
def set_nickname(self, nickname):
self.nickname = nickname
def initialise(self, init_params_as_dict):
pass
def respond(self, sender_nickname, message):
pass
class Echo(BotAI):
def respond(self, sender_nickname, message):
return True, message
Add some decorators to make life easier.class BotAI(object):
def set_nickname(self, nickname):
self.nickname = nickname
def initialise(self, init_params_as_dict):
pass
def respond(self, sender_nickname, message):
return False, ''
class message_must_begin_with_prefix(object):
"""A simple decorator so that a bot AI can ignore all messages that don't
begin with the given prefix.
That way you can have your dude bot only respond to messages that, for
example, begin with 'dude '.
"""
def __init__(self, desired_prefix):
self.desired_prefix = desired_prefix
def __call__(self, func):
def wrapped_func(botai, sender_nickname, message, *args, **kwargs):
if message.startswith(self.desired_prefix):
return func(botai, sender_nickname, message, *args, **kwargs)
else:
return False, ''
return wrapped_func
def message_must_begin_with_nickname(func):
"""A simple decorator so that a bot AI can ignore all messages that don't
begin with the bot AI's nickname.
"""
def wrapped_func(botai, sender_nickname, message, *args, **kwargs):
if message.startswith(botai.nickname):
return func(botai, sender_nickname, message, *args, **kwargs)
else:
return False, ''
return wrapped_func
class Echo(BotAI):
def respond(self, sender_nickname, message):
return True, message
|
<commit_before>class BotAI(object):
def set_nickname(self, nickname):
self.nickname = nickname
def initialise(self, init_params_as_dict):
pass
def respond(self, sender_nickname, message):
pass
class Echo(BotAI):
def respond(self, sender_nickname, message):
return True, message
<commit_msg>Add some decorators to make life easier.<commit_after>class BotAI(object):
def set_nickname(self, nickname):
self.nickname = nickname
def initialise(self, init_params_as_dict):
pass
def respond(self, sender_nickname, message):
return False, ''
class message_must_begin_with_prefix(object):
"""A simple decorator so that a bot AI can ignore all messages that don't
begin with the given prefix.
That way you can have your dude bot only respond to messages that, for
example, begin with 'dude '.
"""
def __init__(self, desired_prefix):
self.desired_prefix = desired_prefix
def __call__(self, func):
def wrapped_func(botai, sender_nickname, message, *args, **kwargs):
if message.startswith(self.desired_prefix):
return func(botai, sender_nickname, message, *args, **kwargs)
else:
return False, ''
return wrapped_func
def message_must_begin_with_nickname(func):
"""A simple decorator so that a bot AI can ignore all messages that don't
begin with the bot AI's nickname.
"""
def wrapped_func(botai, sender_nickname, message, *args, **kwargs):
if message.startswith(botai.nickname):
return func(botai, sender_nickname, message, *args, **kwargs)
else:
return False, ''
return wrapped_func
class Echo(BotAI):
def respond(self, sender_nickname, message):
return True, message
|
96a08a9c7b11ce96de1c2034efcc19622c4eb419
|
drillion/ship_keys.py
|
drillion/ship_keys.py
|
from pyglet.window import key
PLAYER_SHIP_KEYS = dict(left=[key.A, key.LEFT], right=[key.D, key.RIGHT],
thrust=[key.W, key.UP], fire=[key.S, key.DOWN])
PLAYER_1_SHIP_KEYS = dict(left=[key.A], right=[key.D], thrust=[key.W],
fire=[key.S])
PLAYER_2_SHIP_KEYS = dict(left=[key.LEFT], right=[key.RIGHT],
thrust=[key.UP], fire=[key.DOWN])
|
from pyglet.window import key
PLAYER_SHIP_KEYS = dict(left=[key.A, key.J], right=[key.D, key.L],
thrust=[key.W, key.I], fire=[key.S, key.K])
PLAYER_1_SHIP_KEYS = dict(left=[key.A], right=[key.D], thrust=[key.W],
fire=[key.S])
PLAYER_2_SHIP_KEYS = dict(left=[key.J], right=[key.L], thrust=[key.I],
fire=[key.K])
|
Change second ship controls to IJKL
|
Change second ship controls to IJKL
|
Python
|
mit
|
elemel/drillion
|
from pyglet.window import key
PLAYER_SHIP_KEYS = dict(left=[key.A, key.LEFT], right=[key.D, key.RIGHT],
thrust=[key.W, key.UP], fire=[key.S, key.DOWN])
PLAYER_1_SHIP_KEYS = dict(left=[key.A], right=[key.D], thrust=[key.W],
fire=[key.S])
PLAYER_2_SHIP_KEYS = dict(left=[key.LEFT], right=[key.RIGHT],
thrust=[key.UP], fire=[key.DOWN])
Change second ship controls to IJKL
|
from pyglet.window import key
PLAYER_SHIP_KEYS = dict(left=[key.A, key.J], right=[key.D, key.L],
thrust=[key.W, key.I], fire=[key.S, key.K])
PLAYER_1_SHIP_KEYS = dict(left=[key.A], right=[key.D], thrust=[key.W],
fire=[key.S])
PLAYER_2_SHIP_KEYS = dict(left=[key.J], right=[key.L], thrust=[key.I],
fire=[key.K])
|
<commit_before>from pyglet.window import key
PLAYER_SHIP_KEYS = dict(left=[key.A, key.LEFT], right=[key.D, key.RIGHT],
thrust=[key.W, key.UP], fire=[key.S, key.DOWN])
PLAYER_1_SHIP_KEYS = dict(left=[key.A], right=[key.D], thrust=[key.W],
fire=[key.S])
PLAYER_2_SHIP_KEYS = dict(left=[key.LEFT], right=[key.RIGHT],
thrust=[key.UP], fire=[key.DOWN])
<commit_msg>Change second ship controls to IJKL<commit_after>
|
from pyglet.window import key
PLAYER_SHIP_KEYS = dict(left=[key.A, key.J], right=[key.D, key.L],
thrust=[key.W, key.I], fire=[key.S, key.K])
PLAYER_1_SHIP_KEYS = dict(left=[key.A], right=[key.D], thrust=[key.W],
fire=[key.S])
PLAYER_2_SHIP_KEYS = dict(left=[key.J], right=[key.L], thrust=[key.I],
fire=[key.K])
|
from pyglet.window import key
PLAYER_SHIP_KEYS = dict(left=[key.A, key.LEFT], right=[key.D, key.RIGHT],
thrust=[key.W, key.UP], fire=[key.S, key.DOWN])
PLAYER_1_SHIP_KEYS = dict(left=[key.A], right=[key.D], thrust=[key.W],
fire=[key.S])
PLAYER_2_SHIP_KEYS = dict(left=[key.LEFT], right=[key.RIGHT],
thrust=[key.UP], fire=[key.DOWN])
Change second ship controls to IJKLfrom pyglet.window import key
PLAYER_SHIP_KEYS = dict(left=[key.A, key.J], right=[key.D, key.L],
thrust=[key.W, key.I], fire=[key.S, key.K])
PLAYER_1_SHIP_KEYS = dict(left=[key.A], right=[key.D], thrust=[key.W],
fire=[key.S])
PLAYER_2_SHIP_KEYS = dict(left=[key.J], right=[key.L], thrust=[key.I],
fire=[key.K])
|
<commit_before>from pyglet.window import key
PLAYER_SHIP_KEYS = dict(left=[key.A, key.LEFT], right=[key.D, key.RIGHT],
thrust=[key.W, key.UP], fire=[key.S, key.DOWN])
PLAYER_1_SHIP_KEYS = dict(left=[key.A], right=[key.D], thrust=[key.W],
fire=[key.S])
PLAYER_2_SHIP_KEYS = dict(left=[key.LEFT], right=[key.RIGHT],
thrust=[key.UP], fire=[key.DOWN])
<commit_msg>Change second ship controls to IJKL<commit_after>from pyglet.window import key
PLAYER_SHIP_KEYS = dict(left=[key.A, key.J], right=[key.D, key.L],
thrust=[key.W, key.I], fire=[key.S, key.K])
PLAYER_1_SHIP_KEYS = dict(left=[key.A], right=[key.D], thrust=[key.W],
fire=[key.S])
PLAYER_2_SHIP_KEYS = dict(left=[key.J], right=[key.L], thrust=[key.I],
fire=[key.K])
|
074e711dd58e432c39906c1fe6f7e9944407b1e5
|
changes/api/snapshot_details.py
|
changes/api/snapshot_details.py
|
from __future__ import absolute_import
from flask.ext.restful import reqparse
from changes.api.base import APIView
from changes.config import db
from changes.db.utils import create_or_update
from changes.models import ProjectOption, Snapshot, SnapshotStatus
class SnapshotDetailsAPIView(APIView):
parser = reqparse.RequestParser()
parser.add_argument('status', choices=SnapshotStatus._member_names_)
parser.add_argument('set_current', type=bool)
def get(self, snapshot_id):
snapshot = Snapshot.query.get(snapshot_id)
if snapshot is None:
return '', 404
return self.respond(snapshot)
def post(self, snapshot_id):
snapshot = Snapshot.query.get(snapshot_id)
if snapshot is None:
return '', 404
args = self.parser.parse_args()
if args.status:
snapshot.status = SnapshotStatus[args.status]
if args.set_current and snapshot.status != SnapshotStatus.active:
return '{"error": "Cannot set inactive current snapshot"}', 400
db.session.add(snapshot)
db.session.commit()
if args.set_current:
# TODO(adegtiar): improve logic for picking current snapshot.
create_or_update(ProjectOption, where={
'project': snapshot.project,
'name': 'snapshot.current',
}, values={
'value': snapshot.id.hex,
})
return self.respond(snapshot)
|
from __future__ import absolute_import
from flask.ext.restful import reqparse
from changes.api.base import APIView
from changes.api.serializer.models.snapshot import SnapshotWithImagesSerializer
from changes.config import db
from changes.db.utils import create_or_update
from changes.models import ProjectOption, Snapshot, SnapshotStatus
class SnapshotDetailsAPIView(APIView):
parser = reqparse.RequestParser()
parser.add_argument('status', choices=SnapshotStatus._member_names_)
parser.add_argument('set_current', type=bool)
def get(self, snapshot_id):
snapshot = Snapshot.query.get(snapshot_id)
if snapshot is None:
return '', 404
return self.respond(snapshot, serializers={
Snapshot: SnapshotWithImagesSerializer(),
})
def post(self, snapshot_id):
snapshot = Snapshot.query.get(snapshot_id)
if snapshot is None:
return '', 404
args = self.parser.parse_args()
if args.status:
snapshot.status = SnapshotStatus[args.status]
if args.set_current and snapshot.status != SnapshotStatus.active:
return '{"error": "Cannot set inactive current snapshot"}', 400
db.session.add(snapshot)
db.session.commit()
if args.set_current:
# TODO(adegtiar): improve logic for picking current snapshot.
create_or_update(ProjectOption, where={
'project': snapshot.project,
'name': 'snapshot.current',
}, values={
'value': snapshot.id.hex,
})
return self.respond(snapshot)
|
Add images to snapshot details
|
Add images to snapshot details
|
Python
|
apache-2.0
|
dropbox/changes,bowlofstew/changes,bowlofstew/changes,dropbox/changes,wfxiang08/changes,wfxiang08/changes,bowlofstew/changes,wfxiang08/changes,dropbox/changes,wfxiang08/changes,dropbox/changes,bowlofstew/changes
|
from __future__ import absolute_import
from flask.ext.restful import reqparse
from changes.api.base import APIView
from changes.config import db
from changes.db.utils import create_or_update
from changes.models import ProjectOption, Snapshot, SnapshotStatus
class SnapshotDetailsAPIView(APIView):
parser = reqparse.RequestParser()
parser.add_argument('status', choices=SnapshotStatus._member_names_)
parser.add_argument('set_current', type=bool)
def get(self, snapshot_id):
snapshot = Snapshot.query.get(snapshot_id)
if snapshot is None:
return '', 404
return self.respond(snapshot)
def post(self, snapshot_id):
snapshot = Snapshot.query.get(snapshot_id)
if snapshot is None:
return '', 404
args = self.parser.parse_args()
if args.status:
snapshot.status = SnapshotStatus[args.status]
if args.set_current and snapshot.status != SnapshotStatus.active:
return '{"error": "Cannot set inactive current snapshot"}', 400
db.session.add(snapshot)
db.session.commit()
if args.set_current:
# TODO(adegtiar): improve logic for picking current snapshot.
create_or_update(ProjectOption, where={
'project': snapshot.project,
'name': 'snapshot.current',
}, values={
'value': snapshot.id.hex,
})
return self.respond(snapshot)
Add images to snapshot details
|
from __future__ import absolute_import
from flask.ext.restful import reqparse
from changes.api.base import APIView
from changes.api.serializer.models.snapshot import SnapshotWithImagesSerializer
from changes.config import db
from changes.db.utils import create_or_update
from changes.models import ProjectOption, Snapshot, SnapshotStatus
class SnapshotDetailsAPIView(APIView):
parser = reqparse.RequestParser()
parser.add_argument('status', choices=SnapshotStatus._member_names_)
parser.add_argument('set_current', type=bool)
def get(self, snapshot_id):
snapshot = Snapshot.query.get(snapshot_id)
if snapshot is None:
return '', 404
return self.respond(snapshot, serializers={
Snapshot: SnapshotWithImagesSerializer(),
})
def post(self, snapshot_id):
snapshot = Snapshot.query.get(snapshot_id)
if snapshot is None:
return '', 404
args = self.parser.parse_args()
if args.status:
snapshot.status = SnapshotStatus[args.status]
if args.set_current and snapshot.status != SnapshotStatus.active:
return '{"error": "Cannot set inactive current snapshot"}', 400
db.session.add(snapshot)
db.session.commit()
if args.set_current:
# TODO(adegtiar): improve logic for picking current snapshot.
create_or_update(ProjectOption, where={
'project': snapshot.project,
'name': 'snapshot.current',
}, values={
'value': snapshot.id.hex,
})
return self.respond(snapshot)
|
<commit_before>from __future__ import absolute_import
from flask.ext.restful import reqparse
from changes.api.base import APIView
from changes.config import db
from changes.db.utils import create_or_update
from changes.models import ProjectOption, Snapshot, SnapshotStatus
class SnapshotDetailsAPIView(APIView):
parser = reqparse.RequestParser()
parser.add_argument('status', choices=SnapshotStatus._member_names_)
parser.add_argument('set_current', type=bool)
def get(self, snapshot_id):
snapshot = Snapshot.query.get(snapshot_id)
if snapshot is None:
return '', 404
return self.respond(snapshot)
def post(self, snapshot_id):
snapshot = Snapshot.query.get(snapshot_id)
if snapshot is None:
return '', 404
args = self.parser.parse_args()
if args.status:
snapshot.status = SnapshotStatus[args.status]
if args.set_current and snapshot.status != SnapshotStatus.active:
return '{"error": "Cannot set inactive current snapshot"}', 400
db.session.add(snapshot)
db.session.commit()
if args.set_current:
# TODO(adegtiar): improve logic for picking current snapshot.
create_or_update(ProjectOption, where={
'project': snapshot.project,
'name': 'snapshot.current',
}, values={
'value': snapshot.id.hex,
})
return self.respond(snapshot)
<commit_msg>Add images to snapshot details<commit_after>
|
from __future__ import absolute_import
from flask.ext.restful import reqparse
from changes.api.base import APIView
from changes.api.serializer.models.snapshot import SnapshotWithImagesSerializer
from changes.config import db
from changes.db.utils import create_or_update
from changes.models import ProjectOption, Snapshot, SnapshotStatus
class SnapshotDetailsAPIView(APIView):
parser = reqparse.RequestParser()
parser.add_argument('status', choices=SnapshotStatus._member_names_)
parser.add_argument('set_current', type=bool)
def get(self, snapshot_id):
snapshot = Snapshot.query.get(snapshot_id)
if snapshot is None:
return '', 404
return self.respond(snapshot, serializers={
Snapshot: SnapshotWithImagesSerializer(),
})
def post(self, snapshot_id):
snapshot = Snapshot.query.get(snapshot_id)
if snapshot is None:
return '', 404
args = self.parser.parse_args()
if args.status:
snapshot.status = SnapshotStatus[args.status]
if args.set_current and snapshot.status != SnapshotStatus.active:
return '{"error": "Cannot set inactive current snapshot"}', 400
db.session.add(snapshot)
db.session.commit()
if args.set_current:
# TODO(adegtiar): improve logic for picking current snapshot.
create_or_update(ProjectOption, where={
'project': snapshot.project,
'name': 'snapshot.current',
}, values={
'value': snapshot.id.hex,
})
return self.respond(snapshot)
|
from __future__ import absolute_import
from flask.ext.restful import reqparse
from changes.api.base import APIView
from changes.config import db
from changes.db.utils import create_or_update
from changes.models import ProjectOption, Snapshot, SnapshotStatus
class SnapshotDetailsAPIView(APIView):
parser = reqparse.RequestParser()
parser.add_argument('status', choices=SnapshotStatus._member_names_)
parser.add_argument('set_current', type=bool)
def get(self, snapshot_id):
snapshot = Snapshot.query.get(snapshot_id)
if snapshot is None:
return '', 404
return self.respond(snapshot)
def post(self, snapshot_id):
snapshot = Snapshot.query.get(snapshot_id)
if snapshot is None:
return '', 404
args = self.parser.parse_args()
if args.status:
snapshot.status = SnapshotStatus[args.status]
if args.set_current and snapshot.status != SnapshotStatus.active:
return '{"error": "Cannot set inactive current snapshot"}', 400
db.session.add(snapshot)
db.session.commit()
if args.set_current:
# TODO(adegtiar): improve logic for picking current snapshot.
create_or_update(ProjectOption, where={
'project': snapshot.project,
'name': 'snapshot.current',
}, values={
'value': snapshot.id.hex,
})
return self.respond(snapshot)
Add images to snapshot detailsfrom __future__ import absolute_import
from flask.ext.restful import reqparse
from changes.api.base import APIView
from changes.api.serializer.models.snapshot import SnapshotWithImagesSerializer
from changes.config import db
from changes.db.utils import create_or_update
from changes.models import ProjectOption, Snapshot, SnapshotStatus
class SnapshotDetailsAPIView(APIView):
parser = reqparse.RequestParser()
parser.add_argument('status', choices=SnapshotStatus._member_names_)
parser.add_argument('set_current', type=bool)
def get(self, snapshot_id):
snapshot = Snapshot.query.get(snapshot_id)
if snapshot is None:
return '', 404
return self.respond(snapshot, serializers={
Snapshot: SnapshotWithImagesSerializer(),
})
def post(self, snapshot_id):
snapshot = Snapshot.query.get(snapshot_id)
if snapshot is None:
return '', 404
args = self.parser.parse_args()
if args.status:
snapshot.status = SnapshotStatus[args.status]
if args.set_current and snapshot.status != SnapshotStatus.active:
return '{"error": "Cannot set inactive current snapshot"}', 400
db.session.add(snapshot)
db.session.commit()
if args.set_current:
# TODO(adegtiar): improve logic for picking current snapshot.
create_or_update(ProjectOption, where={
'project': snapshot.project,
'name': 'snapshot.current',
}, values={
'value': snapshot.id.hex,
})
return self.respond(snapshot)
|
<commit_before>from __future__ import absolute_import
from flask.ext.restful import reqparse
from changes.api.base import APIView
from changes.config import db
from changes.db.utils import create_or_update
from changes.models import ProjectOption, Snapshot, SnapshotStatus
class SnapshotDetailsAPIView(APIView):
parser = reqparse.RequestParser()
parser.add_argument('status', choices=SnapshotStatus._member_names_)
parser.add_argument('set_current', type=bool)
def get(self, snapshot_id):
snapshot = Snapshot.query.get(snapshot_id)
if snapshot is None:
return '', 404
return self.respond(snapshot)
def post(self, snapshot_id):
snapshot = Snapshot.query.get(snapshot_id)
if snapshot is None:
return '', 404
args = self.parser.parse_args()
if args.status:
snapshot.status = SnapshotStatus[args.status]
if args.set_current and snapshot.status != SnapshotStatus.active:
return '{"error": "Cannot set inactive current snapshot"}', 400
db.session.add(snapshot)
db.session.commit()
if args.set_current:
# TODO(adegtiar): improve logic for picking current snapshot.
create_or_update(ProjectOption, where={
'project': snapshot.project,
'name': 'snapshot.current',
}, values={
'value': snapshot.id.hex,
})
return self.respond(snapshot)
<commit_msg>Add images to snapshot details<commit_after>from __future__ import absolute_import
from flask.ext.restful import reqparse
from changes.api.base import APIView
from changes.api.serializer.models.snapshot import SnapshotWithImagesSerializer
from changes.config import db
from changes.db.utils import create_or_update
from changes.models import ProjectOption, Snapshot, SnapshotStatus
class SnapshotDetailsAPIView(APIView):
parser = reqparse.RequestParser()
parser.add_argument('status', choices=SnapshotStatus._member_names_)
parser.add_argument('set_current', type=bool)
def get(self, snapshot_id):
snapshot = Snapshot.query.get(snapshot_id)
if snapshot is None:
return '', 404
return self.respond(snapshot, serializers={
Snapshot: SnapshotWithImagesSerializer(),
})
def post(self, snapshot_id):
snapshot = Snapshot.query.get(snapshot_id)
if snapshot is None:
return '', 404
args = self.parser.parse_args()
if args.status:
snapshot.status = SnapshotStatus[args.status]
if args.set_current and snapshot.status != SnapshotStatus.active:
return '{"error": "Cannot set inactive current snapshot"}', 400
db.session.add(snapshot)
db.session.commit()
if args.set_current:
# TODO(adegtiar): improve logic for picking current snapshot.
create_or_update(ProjectOption, where={
'project': snapshot.project,
'name': 'snapshot.current',
}, values={
'value': snapshot.id.hex,
})
return self.respond(snapshot)
|
2b9efb699d557cbd47d54b10bb6ff8be24596ab4
|
src/nodeconductor_assembly_waldur/packages/tests/unittests/test_models.py
|
src/nodeconductor_assembly_waldur/packages/tests/unittests/test_models.py
|
from decimal import Decimal
import random
from django.test import TestCase
from .. import factories
from ... import models
class PackageTemplateTest(TestCase):
def test_package_price_is_based_on_components(self):
package_template = factories.PackageTemplateFactory(components=[])
total = Decimal('0.00')
for t in models.PackageTemplate.get_required_component_types():
component = package_template.components.get(type=t)
component.amount = random.randint(1, 10)
component.price = Decimal('4.95')
component.save()
total += component.amount * component.price
self.assertEqual(package_template.price, total)
|
from decimal import Decimal
import random
from django.test import TestCase
from .. import factories
from ... import models
class PackageTemplateTest(TestCase):
def test_package_price_is_based_on_components(self):
package_template = factories.PackageTemplateFactory()
total = Decimal('0.00')
for t in models.PackageTemplate.get_required_component_types():
component = package_template.components.get(type=t)
component.amount = random.randint(1, 10)
component.price = Decimal('4.95')
component.save()
total += component.amount * component.price
self.assertEqual(package_template.price, total)
|
Update test according to factory usage
|
Update test according to factory usage
|
Python
|
mit
|
opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind
|
from decimal import Decimal
import random
from django.test import TestCase
from .. import factories
from ... import models
class PackageTemplateTest(TestCase):
def test_package_price_is_based_on_components(self):
package_template = factories.PackageTemplateFactory(components=[])
total = Decimal('0.00')
for t in models.PackageTemplate.get_required_component_types():
component = package_template.components.get(type=t)
component.amount = random.randint(1, 10)
component.price = Decimal('4.95')
component.save()
total += component.amount * component.price
self.assertEqual(package_template.price, total)
Update test according to factory usage
|
from decimal import Decimal
import random
from django.test import TestCase
from .. import factories
from ... import models
class PackageTemplateTest(TestCase):
def test_package_price_is_based_on_components(self):
package_template = factories.PackageTemplateFactory()
total = Decimal('0.00')
for t in models.PackageTemplate.get_required_component_types():
component = package_template.components.get(type=t)
component.amount = random.randint(1, 10)
component.price = Decimal('4.95')
component.save()
total += component.amount * component.price
self.assertEqual(package_template.price, total)
|
<commit_before>from decimal import Decimal
import random
from django.test import TestCase
from .. import factories
from ... import models
class PackageTemplateTest(TestCase):
def test_package_price_is_based_on_components(self):
package_template = factories.PackageTemplateFactory(components=[])
total = Decimal('0.00')
for t in models.PackageTemplate.get_required_component_types():
component = package_template.components.get(type=t)
component.amount = random.randint(1, 10)
component.price = Decimal('4.95')
component.save()
total += component.amount * component.price
self.assertEqual(package_template.price, total)
<commit_msg>Update test according to factory usage<commit_after>
|
from decimal import Decimal
import random
from django.test import TestCase
from .. import factories
from ... import models
class PackageTemplateTest(TestCase):
def test_package_price_is_based_on_components(self):
package_template = factories.PackageTemplateFactory()
total = Decimal('0.00')
for t in models.PackageTemplate.get_required_component_types():
component = package_template.components.get(type=t)
component.amount = random.randint(1, 10)
component.price = Decimal('4.95')
component.save()
total += component.amount * component.price
self.assertEqual(package_template.price, total)
|
from decimal import Decimal
import random
from django.test import TestCase
from .. import factories
from ... import models
class PackageTemplateTest(TestCase):
def test_package_price_is_based_on_components(self):
package_template = factories.PackageTemplateFactory(components=[])
total = Decimal('0.00')
for t in models.PackageTemplate.get_required_component_types():
component = package_template.components.get(type=t)
component.amount = random.randint(1, 10)
component.price = Decimal('4.95')
component.save()
total += component.amount * component.price
self.assertEqual(package_template.price, total)
Update test according to factory usagefrom decimal import Decimal
import random
from django.test import TestCase
from .. import factories
from ... import models
class PackageTemplateTest(TestCase):
def test_package_price_is_based_on_components(self):
package_template = factories.PackageTemplateFactory()
total = Decimal('0.00')
for t in models.PackageTemplate.get_required_component_types():
component = package_template.components.get(type=t)
component.amount = random.randint(1, 10)
component.price = Decimal('4.95')
component.save()
total += component.amount * component.price
self.assertEqual(package_template.price, total)
|
<commit_before>from decimal import Decimal
import random
from django.test import TestCase
from .. import factories
from ... import models
class PackageTemplateTest(TestCase):
def test_package_price_is_based_on_components(self):
package_template = factories.PackageTemplateFactory(components=[])
total = Decimal('0.00')
for t in models.PackageTemplate.get_required_component_types():
component = package_template.components.get(type=t)
component.amount = random.randint(1, 10)
component.price = Decimal('4.95')
component.save()
total += component.amount * component.price
self.assertEqual(package_template.price, total)
<commit_msg>Update test according to factory usage<commit_after>from decimal import Decimal
import random
from django.test import TestCase
from .. import factories
from ... import models
class PackageTemplateTest(TestCase):
def test_package_price_is_based_on_components(self):
package_template = factories.PackageTemplateFactory()
total = Decimal('0.00')
for t in models.PackageTemplate.get_required_component_types():
component = package_template.components.get(type=t)
component.amount = random.randint(1, 10)
component.price = Decimal('4.95')
component.save()
total += component.amount * component.price
self.assertEqual(package_template.price, total)
|
8c773a53902860409f83ff445402eb56d6376a88
|
app/utils/settings.py
|
app/utils/settings.py
|
from app.models import Setting
class AppSettings(dict):
def __init__(self):
super().__init__()
self.update({setting.name: setting.value for setting in Setting.query.all()})
self.__setitem__('posts_per_page', int(self.__getitem__('posts_per_page')))
def __setitem__(self, key, value):
super().__setitem__(key, value)
setting = Setting.query.filter_by(name=key).first()
if setting is not None:
setting.value = value
else:
setting = Setting(name=key, value=value)
setting.save()
def __setattr__(self, key, value):
self.__setitem__(key, value)
|
from app.models import Setting
class AppSettings(dict):
def __init__(self):
super().__init__()
self.update({setting.name: setting.value for setting in Setting.query.all()})
try:
self.__setitem__('posts_per_page', int(self.__getitem__('posts_per_page')))
except KeyError:
pass
def __setitem__(self, key, value):
super().__setitem__(key, value)
setting = Setting.query.filter_by(name=key).first()
if setting is not None:
setting.value = value
else:
setting = Setting(name=key, value=value)
setting.save()
def __setattr__(self, key, value):
self.__setitem__(key, value)
|
Add error handling for posts_per_page type conversion
|
Add error handling for posts_per_page type conversion
|
Python
|
mit
|
Encrylize/flask-blogger,Encrylize/flask-blogger,Encrylize/flask-blogger
|
from app.models import Setting
class AppSettings(dict):
def __init__(self):
super().__init__()
self.update({setting.name: setting.value for setting in Setting.query.all()})
self.__setitem__('posts_per_page', int(self.__getitem__('posts_per_page')))
def __setitem__(self, key, value):
super().__setitem__(key, value)
setting = Setting.query.filter_by(name=key).first()
if setting is not None:
setting.value = value
else:
setting = Setting(name=key, value=value)
setting.save()
def __setattr__(self, key, value):
self.__setitem__(key, value)
Add error handling for posts_per_page type conversion
|
from app.models import Setting
class AppSettings(dict):
def __init__(self):
super().__init__()
self.update({setting.name: setting.value for setting in Setting.query.all()})
try:
self.__setitem__('posts_per_page', int(self.__getitem__('posts_per_page')))
except KeyError:
pass
def __setitem__(self, key, value):
super().__setitem__(key, value)
setting = Setting.query.filter_by(name=key).first()
if setting is not None:
setting.value = value
else:
setting = Setting(name=key, value=value)
setting.save()
def __setattr__(self, key, value):
self.__setitem__(key, value)
|
<commit_before>from app.models import Setting
class AppSettings(dict):
def __init__(self):
super().__init__()
self.update({setting.name: setting.value for setting in Setting.query.all()})
self.__setitem__('posts_per_page', int(self.__getitem__('posts_per_page')))
def __setitem__(self, key, value):
super().__setitem__(key, value)
setting = Setting.query.filter_by(name=key).first()
if setting is not None:
setting.value = value
else:
setting = Setting(name=key, value=value)
setting.save()
def __setattr__(self, key, value):
self.__setitem__(key, value)
<commit_msg>Add error handling for posts_per_page type conversion<commit_after>
|
from app.models import Setting
class AppSettings(dict):
def __init__(self):
super().__init__()
self.update({setting.name: setting.value for setting in Setting.query.all()})
try:
self.__setitem__('posts_per_page', int(self.__getitem__('posts_per_page')))
except KeyError:
pass
def __setitem__(self, key, value):
super().__setitem__(key, value)
setting = Setting.query.filter_by(name=key).first()
if setting is not None:
setting.value = value
else:
setting = Setting(name=key, value=value)
setting.save()
def __setattr__(self, key, value):
self.__setitem__(key, value)
|
from app.models import Setting
class AppSettings(dict):
def __init__(self):
super().__init__()
self.update({setting.name: setting.value for setting in Setting.query.all()})
self.__setitem__('posts_per_page', int(self.__getitem__('posts_per_page')))
def __setitem__(self, key, value):
super().__setitem__(key, value)
setting = Setting.query.filter_by(name=key).first()
if setting is not None:
setting.value = value
else:
setting = Setting(name=key, value=value)
setting.save()
def __setattr__(self, key, value):
self.__setitem__(key, value)
Add error handling for posts_per_page type conversionfrom app.models import Setting
class AppSettings(dict):
def __init__(self):
super().__init__()
self.update({setting.name: setting.value for setting in Setting.query.all()})
try:
self.__setitem__('posts_per_page', int(self.__getitem__('posts_per_page')))
except KeyError:
pass
def __setitem__(self, key, value):
super().__setitem__(key, value)
setting = Setting.query.filter_by(name=key).first()
if setting is not None:
setting.value = value
else:
setting = Setting(name=key, value=value)
setting.save()
def __setattr__(self, key, value):
self.__setitem__(key, value)
|
<commit_before>from app.models import Setting
class AppSettings(dict):
def __init__(self):
super().__init__()
self.update({setting.name: setting.value for setting in Setting.query.all()})
self.__setitem__('posts_per_page', int(self.__getitem__('posts_per_page')))
def __setitem__(self, key, value):
super().__setitem__(key, value)
setting = Setting.query.filter_by(name=key).first()
if setting is not None:
setting.value = value
else:
setting = Setting(name=key, value=value)
setting.save()
def __setattr__(self, key, value):
self.__setitem__(key, value)
<commit_msg>Add error handling for posts_per_page type conversion<commit_after>from app.models import Setting
class AppSettings(dict):
def __init__(self):
super().__init__()
self.update({setting.name: setting.value for setting in Setting.query.all()})
try:
self.__setitem__('posts_per_page', int(self.__getitem__('posts_per_page')))
except KeyError:
pass
def __setitem__(self, key, value):
super().__setitem__(key, value)
setting = Setting.query.filter_by(name=key).first()
if setting is not None:
setting.value = value
else:
setting = Setting(name=key, value=value)
setting.save()
def __setattr__(self, key, value):
self.__setitem__(key, value)
|
7dd467f474675c2c2535b6c3b925340b72959089
|
tests/settings.py
|
tests/settings.py
|
import os
CONNECT_ARGS = []
CONNECT_KWARGS = {}
LIVE_TEST = 'HOST' in os.environ
if LIVE_TEST:
HOST = os.environ['HOST']
DATABASE = os.environ.get('DATABASE', 'test')
USER = os.environ.get('SQLUSER', 'sa')
PASSWORD = os.environ.get('SQLPASSWORD', 'sa')
USE_MARS = bool(os.environ.get('USE_MARS', True))
SKIP_SQL_AUTH = bool(os.environ.get('SKIP_SQL_AUTH'))
import pytds
CONNECT_KWARGS = {
'server': HOST,
'database': DATABASE,
'user': USER,
'password': PASSWORD,
'use_mars': USE_MARS,
'bytes_to_unicode': True,
}
if 'tds_version' in os.environ:
CONNECT_KWARGS['tds_version'] = getattr(pytds, os.environ['tds_version'])
if 'auth' in os.environ:
import pytds.login
CONNECT_KWARGS['auth'] = getattr(pytds.login, os.environ['auth'])()
if 'bytes_to_unicode' in os.environ:
CONNECT_KWARGS['bytes_to_unicode'] = bool(os.environ.get('bytes_to_unicode'))
|
import os
CONNECT_ARGS = []
CONNECT_KWARGS = {}
LIVE_TEST = 'HOST' in os.environ
if LIVE_TEST:
HOST = os.environ['HOST']
DATABASE = os.environ.get('DATABASE', 'test')
USER = os.environ.get('SQLUSER', 'sa')
PASSWORD = os.environ.get('SQLPASSWORD', 'sa')
USE_MARS = bool(os.environ.get('USE_MARS', True))
SKIP_SQL_AUTH = bool(os.environ.get('SKIP_SQL_AUTH'))
import pytds
CONNECT_KWARGS = {
'server': HOST,
'database': DATABASE,
'user': USER,
'password': PASSWORD,
'use_mars': USE_MARS,
'bytes_to_unicode': True,
'pooling': True,
}
if 'tds_version' in os.environ:
CONNECT_KWARGS['tds_version'] = getattr(pytds, os.environ['tds_version'])
if 'auth' in os.environ:
import pytds.login
CONNECT_KWARGS['auth'] = getattr(pytds.login, os.environ['auth'])()
if 'bytes_to_unicode' in os.environ:
CONNECT_KWARGS['bytes_to_unicode'] = bool(os.environ.get('bytes_to_unicode'))
|
Use connection pool by default during testing
|
Use connection pool by default during testing
|
Python
|
mit
|
m32/pytds,m32/pytds,denisenkom/pytds,tpow/pytds,denisenkom/pytds,tpow/pytds
|
import os
CONNECT_ARGS = []
CONNECT_KWARGS = {}
LIVE_TEST = 'HOST' in os.environ
if LIVE_TEST:
HOST = os.environ['HOST']
DATABASE = os.environ.get('DATABASE', 'test')
USER = os.environ.get('SQLUSER', 'sa')
PASSWORD = os.environ.get('SQLPASSWORD', 'sa')
USE_MARS = bool(os.environ.get('USE_MARS', True))
SKIP_SQL_AUTH = bool(os.environ.get('SKIP_SQL_AUTH'))
import pytds
CONNECT_KWARGS = {
'server': HOST,
'database': DATABASE,
'user': USER,
'password': PASSWORD,
'use_mars': USE_MARS,
'bytes_to_unicode': True,
}
if 'tds_version' in os.environ:
CONNECT_KWARGS['tds_version'] = getattr(pytds, os.environ['tds_version'])
if 'auth' in os.environ:
import pytds.login
CONNECT_KWARGS['auth'] = getattr(pytds.login, os.environ['auth'])()
if 'bytes_to_unicode' in os.environ:
CONNECT_KWARGS['bytes_to_unicode'] = bool(os.environ.get('bytes_to_unicode'))
Use connection pool by default during testing
|
import os
CONNECT_ARGS = []
CONNECT_KWARGS = {}
LIVE_TEST = 'HOST' in os.environ
if LIVE_TEST:
HOST = os.environ['HOST']
DATABASE = os.environ.get('DATABASE', 'test')
USER = os.environ.get('SQLUSER', 'sa')
PASSWORD = os.environ.get('SQLPASSWORD', 'sa')
USE_MARS = bool(os.environ.get('USE_MARS', True))
SKIP_SQL_AUTH = bool(os.environ.get('SKIP_SQL_AUTH'))
import pytds
CONNECT_KWARGS = {
'server': HOST,
'database': DATABASE,
'user': USER,
'password': PASSWORD,
'use_mars': USE_MARS,
'bytes_to_unicode': True,
'pooling': True,
}
if 'tds_version' in os.environ:
CONNECT_KWARGS['tds_version'] = getattr(pytds, os.environ['tds_version'])
if 'auth' in os.environ:
import pytds.login
CONNECT_KWARGS['auth'] = getattr(pytds.login, os.environ['auth'])()
if 'bytes_to_unicode' in os.environ:
CONNECT_KWARGS['bytes_to_unicode'] = bool(os.environ.get('bytes_to_unicode'))
|
<commit_before>import os
CONNECT_ARGS = []
CONNECT_KWARGS = {}
LIVE_TEST = 'HOST' in os.environ
if LIVE_TEST:
HOST = os.environ['HOST']
DATABASE = os.environ.get('DATABASE', 'test')
USER = os.environ.get('SQLUSER', 'sa')
PASSWORD = os.environ.get('SQLPASSWORD', 'sa')
USE_MARS = bool(os.environ.get('USE_MARS', True))
SKIP_SQL_AUTH = bool(os.environ.get('SKIP_SQL_AUTH'))
import pytds
CONNECT_KWARGS = {
'server': HOST,
'database': DATABASE,
'user': USER,
'password': PASSWORD,
'use_mars': USE_MARS,
'bytes_to_unicode': True,
}
if 'tds_version' in os.environ:
CONNECT_KWARGS['tds_version'] = getattr(pytds, os.environ['tds_version'])
if 'auth' in os.environ:
import pytds.login
CONNECT_KWARGS['auth'] = getattr(pytds.login, os.environ['auth'])()
if 'bytes_to_unicode' in os.environ:
CONNECT_KWARGS['bytes_to_unicode'] = bool(os.environ.get('bytes_to_unicode'))
<commit_msg>Use connection pool by default during testing<commit_after>
|
import os
CONNECT_ARGS = []
CONNECT_KWARGS = {}
LIVE_TEST = 'HOST' in os.environ
if LIVE_TEST:
HOST = os.environ['HOST']
DATABASE = os.environ.get('DATABASE', 'test')
USER = os.environ.get('SQLUSER', 'sa')
PASSWORD = os.environ.get('SQLPASSWORD', 'sa')
USE_MARS = bool(os.environ.get('USE_MARS', True))
SKIP_SQL_AUTH = bool(os.environ.get('SKIP_SQL_AUTH'))
import pytds
CONNECT_KWARGS = {
'server': HOST,
'database': DATABASE,
'user': USER,
'password': PASSWORD,
'use_mars': USE_MARS,
'bytes_to_unicode': True,
'pooling': True,
}
if 'tds_version' in os.environ:
CONNECT_KWARGS['tds_version'] = getattr(pytds, os.environ['tds_version'])
if 'auth' in os.environ:
import pytds.login
CONNECT_KWARGS['auth'] = getattr(pytds.login, os.environ['auth'])()
if 'bytes_to_unicode' in os.environ:
CONNECT_KWARGS['bytes_to_unicode'] = bool(os.environ.get('bytes_to_unicode'))
|
import os
CONNECT_ARGS = []
CONNECT_KWARGS = {}
LIVE_TEST = 'HOST' in os.environ
if LIVE_TEST:
HOST = os.environ['HOST']
DATABASE = os.environ.get('DATABASE', 'test')
USER = os.environ.get('SQLUSER', 'sa')
PASSWORD = os.environ.get('SQLPASSWORD', 'sa')
USE_MARS = bool(os.environ.get('USE_MARS', True))
SKIP_SQL_AUTH = bool(os.environ.get('SKIP_SQL_AUTH'))
import pytds
CONNECT_KWARGS = {
'server': HOST,
'database': DATABASE,
'user': USER,
'password': PASSWORD,
'use_mars': USE_MARS,
'bytes_to_unicode': True,
}
if 'tds_version' in os.environ:
CONNECT_KWARGS['tds_version'] = getattr(pytds, os.environ['tds_version'])
if 'auth' in os.environ:
import pytds.login
CONNECT_KWARGS['auth'] = getattr(pytds.login, os.environ['auth'])()
if 'bytes_to_unicode' in os.environ:
CONNECT_KWARGS['bytes_to_unicode'] = bool(os.environ.get('bytes_to_unicode'))
Use connection pool by default during testingimport os
CONNECT_ARGS = []
CONNECT_KWARGS = {}
LIVE_TEST = 'HOST' in os.environ
if LIVE_TEST:
HOST = os.environ['HOST']
DATABASE = os.environ.get('DATABASE', 'test')
USER = os.environ.get('SQLUSER', 'sa')
PASSWORD = os.environ.get('SQLPASSWORD', 'sa')
USE_MARS = bool(os.environ.get('USE_MARS', True))
SKIP_SQL_AUTH = bool(os.environ.get('SKIP_SQL_AUTH'))
import pytds
CONNECT_KWARGS = {
'server': HOST,
'database': DATABASE,
'user': USER,
'password': PASSWORD,
'use_mars': USE_MARS,
'bytes_to_unicode': True,
'pooling': True,
}
if 'tds_version' in os.environ:
CONNECT_KWARGS['tds_version'] = getattr(pytds, os.environ['tds_version'])
if 'auth' in os.environ:
import pytds.login
CONNECT_KWARGS['auth'] = getattr(pytds.login, os.environ['auth'])()
if 'bytes_to_unicode' in os.environ:
CONNECT_KWARGS['bytes_to_unicode'] = bool(os.environ.get('bytes_to_unicode'))
|
<commit_before>import os
CONNECT_ARGS = []
CONNECT_KWARGS = {}
LIVE_TEST = 'HOST' in os.environ
if LIVE_TEST:
HOST = os.environ['HOST']
DATABASE = os.environ.get('DATABASE', 'test')
USER = os.environ.get('SQLUSER', 'sa')
PASSWORD = os.environ.get('SQLPASSWORD', 'sa')
USE_MARS = bool(os.environ.get('USE_MARS', True))
SKIP_SQL_AUTH = bool(os.environ.get('SKIP_SQL_AUTH'))
import pytds
CONNECT_KWARGS = {
'server': HOST,
'database': DATABASE,
'user': USER,
'password': PASSWORD,
'use_mars': USE_MARS,
'bytes_to_unicode': True,
}
if 'tds_version' in os.environ:
CONNECT_KWARGS['tds_version'] = getattr(pytds, os.environ['tds_version'])
if 'auth' in os.environ:
import pytds.login
CONNECT_KWARGS['auth'] = getattr(pytds.login, os.environ['auth'])()
if 'bytes_to_unicode' in os.environ:
CONNECT_KWARGS['bytes_to_unicode'] = bool(os.environ.get('bytes_to_unicode'))
<commit_msg>Use connection pool by default during testing<commit_after>import os
CONNECT_ARGS = []
CONNECT_KWARGS = {}
LIVE_TEST = 'HOST' in os.environ
if LIVE_TEST:
HOST = os.environ['HOST']
DATABASE = os.environ.get('DATABASE', 'test')
USER = os.environ.get('SQLUSER', 'sa')
PASSWORD = os.environ.get('SQLPASSWORD', 'sa')
USE_MARS = bool(os.environ.get('USE_MARS', True))
SKIP_SQL_AUTH = bool(os.environ.get('SKIP_SQL_AUTH'))
import pytds
CONNECT_KWARGS = {
'server': HOST,
'database': DATABASE,
'user': USER,
'password': PASSWORD,
'use_mars': USE_MARS,
'bytes_to_unicode': True,
'pooling': True,
}
if 'tds_version' in os.environ:
CONNECT_KWARGS['tds_version'] = getattr(pytds, os.environ['tds_version'])
if 'auth' in os.environ:
import pytds.login
CONNECT_KWARGS['auth'] = getattr(pytds.login, os.environ['auth'])()
if 'bytes_to_unicode' in os.environ:
CONNECT_KWARGS['bytes_to_unicode'] = bool(os.environ.get('bytes_to_unicode'))
|
69e081afd1d2b24d40a4992c6af4538aba86ca1c
|
brew_journal/brew_journal/urls.py
|
brew_journal/brew_journal/urls.py
|
from django.conf.urls import patterns, include, url
from brew_journal.views import IndexView
from rest_framework_nested import routers
from authentication.views import AccountViewSet, LoginView
router = routers.SimpleRouter()
router.register(r'account', AccountViewSet)
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'brew_journal.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^api/v1/', include(router.urls)),
url(r'^api/v1/auth/login/$', LoginView.as_view(), name='login'),
# Default index view. Must be last to avoid accidentially catching other URLs
url(r'^$', IndexView.as_view(), name='index'),
)
|
from django.conf.urls import patterns, include, url
from brew_journal.views import IndexView
from rest_framework_nested import routers
from authentication.views import AccountViewSet, LoginView
router = routers.SimpleRouter()
router.register(r'account', AccountViewSet)
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'brew_journal.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^api/v1/', include(router.urls)),
url(r'^api/v1/auth/login/$', LoginView.as_view(), name='login'),
# Default index view. Must be last to avoid accidentially catching other URLs
url(r'^.*$', IndexView.as_view(), name='index'),
)
|
Reset the base url matching regex to correctly reroute to the home page when provided an unknown url
|
Reset the base url matching regex to correctly reroute to the home page when provided an unknown url
|
Python
|
apache-2.0
|
moonboy13/brew-journal,moonboy13/brew-journal,moonboy13/brew-journal
|
from django.conf.urls import patterns, include, url
from brew_journal.views import IndexView
from rest_framework_nested import routers
from authentication.views import AccountViewSet, LoginView
router = routers.SimpleRouter()
router.register(r'account', AccountViewSet)
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'brew_journal.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^api/v1/', include(router.urls)),
url(r'^api/v1/auth/login/$', LoginView.as_view(), name='login'),
# Default index view. Must be last to avoid accidentially catching other URLs
url(r'^$', IndexView.as_view(), name='index'),
)
Reset the base url matching regex to correctly reroute to the home page when provided an unknown url
|
from django.conf.urls import patterns, include, url
from brew_journal.views import IndexView
from rest_framework_nested import routers
from authentication.views import AccountViewSet, LoginView
router = routers.SimpleRouter()
router.register(r'account', AccountViewSet)
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'brew_journal.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^api/v1/', include(router.urls)),
url(r'^api/v1/auth/login/$', LoginView.as_view(), name='login'),
# Default index view. Must be last to avoid accidentially catching other URLs
url(r'^.*$', IndexView.as_view(), name='index'),
)
|
<commit_before>from django.conf.urls import patterns, include, url
from brew_journal.views import IndexView
from rest_framework_nested import routers
from authentication.views import AccountViewSet, LoginView
router = routers.SimpleRouter()
router.register(r'account', AccountViewSet)
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'brew_journal.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^api/v1/', include(router.urls)),
url(r'^api/v1/auth/login/$', LoginView.as_view(), name='login'),
# Default index view. Must be last to avoid accidentially catching other URLs
url(r'^$', IndexView.as_view(), name='index'),
)
<commit_msg>Reset the base url matching regex to correctly reroute to the home page when provided an unknown url<commit_after>
|
from django.conf.urls import patterns, include, url
from brew_journal.views import IndexView
from rest_framework_nested import routers
from authentication.views import AccountViewSet, LoginView
router = routers.SimpleRouter()
router.register(r'account', AccountViewSet)
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'brew_journal.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^api/v1/', include(router.urls)),
url(r'^api/v1/auth/login/$', LoginView.as_view(), name='login'),
# Default index view. Must be last to avoid accidentially catching other URLs
url(r'^.*$', IndexView.as_view(), name='index'),
)
|
from django.conf.urls import patterns, include, url
from brew_journal.views import IndexView
from rest_framework_nested import routers
from authentication.views import AccountViewSet, LoginView
router = routers.SimpleRouter()
router.register(r'account', AccountViewSet)
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'brew_journal.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^api/v1/', include(router.urls)),
url(r'^api/v1/auth/login/$', LoginView.as_view(), name='login'),
# Default index view. Must be last to avoid accidentially catching other URLs
url(r'^$', IndexView.as_view(), name='index'),
)
Reset the base url matching regex to correctly reroute to the home page when provided an unknown urlfrom django.conf.urls import patterns, include, url
from brew_journal.views import IndexView
from rest_framework_nested import routers
from authentication.views import AccountViewSet, LoginView
router = routers.SimpleRouter()
router.register(r'account', AccountViewSet)
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'brew_journal.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^api/v1/', include(router.urls)),
url(r'^api/v1/auth/login/$', LoginView.as_view(), name='login'),
# Default index view. Must be last to avoid accidentially catching other URLs
url(r'^.*$', IndexView.as_view(), name='index'),
)
|
<commit_before>from django.conf.urls import patterns, include, url
from brew_journal.views import IndexView
from rest_framework_nested import routers
from authentication.views import AccountViewSet, LoginView
router = routers.SimpleRouter()
router.register(r'account', AccountViewSet)
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'brew_journal.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^api/v1/', include(router.urls)),
url(r'^api/v1/auth/login/$', LoginView.as_view(), name='login'),
# Default index view. Must be last to avoid accidentially catching other URLs
url(r'^$', IndexView.as_view(), name='index'),
)
<commit_msg>Reset the base url matching regex to correctly reroute to the home page when provided an unknown url<commit_after>from django.conf.urls import patterns, include, url
from brew_journal.views import IndexView
from rest_framework_nested import routers
from authentication.views import AccountViewSet, LoginView
router = routers.SimpleRouter()
router.register(r'account', AccountViewSet)
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'brew_journal.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^api/v1/', include(router.urls)),
url(r'^api/v1/auth/login/$', LoginView.as_view(), name='login'),
# Default index view. Must be last to avoid accidentially catching other URLs
url(r'^.*$', IndexView.as_view(), name='index'),
)
|
6d84cdb641d2d873118cb6cb26c5a7521ae40bd8
|
dcclient/dcclient.py
|
dcclient/dcclient.py
|
""" Main class from dcclient. Manages XML interaction, as well as switch and
creates the actual networks
"""
import rpc
from xml_manager.manager import ManagedXml
from oslo.config import cfg
class Manager:
def __init__(self):
self.rpc = rpc.RPC(cfg.CONF.ml2_datacom.dm_username,
cfg.CONF.ml2_datacom.dm_password,
cfg.CONF.ml2_datacom.dm_host,
cfg.CONF.ml2_datacom.dm_method)
self.xml = ManagedXml()
def _update(self):
self.rpc.send_xml(self.xml.xml.as_xml_text())
def create_network(self, vlan):
""" Creates a new network on the switch, if it does not exist already.
"""
self.xml.addVlan(vlan)
self._update()
|
""" Main class from dcclient. Manages XML interaction, as well as switch and
creates the actual networks
"""
import rpc
from xml_manager.manager import ManagedXml
from neutron.openstack.common import log as logger
from oslo.config import cfg
LOG = logger.getLogger(__name__)
class Manager:
def __init__(self):
self.rpc = rpc.RPC(cfg.CONF.ml2_datacom.dm_username,
cfg.CONF.ml2_datacom.dm_password,
cfg.CONF.ml2_datacom.dm_host,
cfg.CONF.ml2_datacom.dm_method)
self.xml = ManagedXml()
def _update(self):
self.rpc.send_xml(self.xml.xml.as_xml_text())
def create_network(self, vlan):
""" Creates a new network on the switch, if it does not exist already.
"""
try:
self.xml.addVlan(vlan)
self._update()
except:
LOG.info("Trying to create already existing network %d:", vlan)
|
Add error treatment for existing network
|
Add error treatment for existing network
|
Python
|
apache-2.0
|
NeutronUfscarDatacom/DriverDatacom
|
""" Main class from dcclient. Manages XML interaction, as well as switch and
creates the actual networks
"""
import rpc
from xml_manager.manager import ManagedXml
from oslo.config import cfg
class Manager:
def __init__(self):
self.rpc = rpc.RPC(cfg.CONF.ml2_datacom.dm_username,
cfg.CONF.ml2_datacom.dm_password,
cfg.CONF.ml2_datacom.dm_host,
cfg.CONF.ml2_datacom.dm_method)
self.xml = ManagedXml()
def _update(self):
self.rpc.send_xml(self.xml.xml.as_xml_text())
def create_network(self, vlan):
""" Creates a new network on the switch, if it does not exist already.
"""
self.xml.addVlan(vlan)
self._update()
Add error treatment for existing network
|
""" Main class from dcclient. Manages XML interaction, as well as switch and
creates the actual networks
"""
import rpc
from xml_manager.manager import ManagedXml
from neutron.openstack.common import log as logger
from oslo.config import cfg
LOG = logger.getLogger(__name__)
class Manager:
def __init__(self):
self.rpc = rpc.RPC(cfg.CONF.ml2_datacom.dm_username,
cfg.CONF.ml2_datacom.dm_password,
cfg.CONF.ml2_datacom.dm_host,
cfg.CONF.ml2_datacom.dm_method)
self.xml = ManagedXml()
def _update(self):
self.rpc.send_xml(self.xml.xml.as_xml_text())
def create_network(self, vlan):
""" Creates a new network on the switch, if it does not exist already.
"""
try:
self.xml.addVlan(vlan)
self._update()
except:
LOG.info("Trying to create already existing network %d:", vlan)
|
<commit_before>""" Main class from dcclient. Manages XML interaction, as well as switch and
creates the actual networks
"""
import rpc
from xml_manager.manager import ManagedXml
from oslo.config import cfg
class Manager:
def __init__(self):
self.rpc = rpc.RPC(cfg.CONF.ml2_datacom.dm_username,
cfg.CONF.ml2_datacom.dm_password,
cfg.CONF.ml2_datacom.dm_host,
cfg.CONF.ml2_datacom.dm_method)
self.xml = ManagedXml()
def _update(self):
self.rpc.send_xml(self.xml.xml.as_xml_text())
def create_network(self, vlan):
""" Creates a new network on the switch, if it does not exist already.
"""
self.xml.addVlan(vlan)
self._update()
<commit_msg>Add error treatment for existing network<commit_after>
|
""" Main class from dcclient. Manages XML interaction, as well as switch and
creates the actual networks
"""
import rpc
from xml_manager.manager import ManagedXml
from neutron.openstack.common import log as logger
from oslo.config import cfg
LOG = logger.getLogger(__name__)
class Manager:
def __init__(self):
self.rpc = rpc.RPC(cfg.CONF.ml2_datacom.dm_username,
cfg.CONF.ml2_datacom.dm_password,
cfg.CONF.ml2_datacom.dm_host,
cfg.CONF.ml2_datacom.dm_method)
self.xml = ManagedXml()
def _update(self):
self.rpc.send_xml(self.xml.xml.as_xml_text())
def create_network(self, vlan):
""" Creates a new network on the switch, if it does not exist already.
"""
try:
self.xml.addVlan(vlan)
self._update()
except:
LOG.info("Trying to create already existing network %d:", vlan)
|
""" Main class from dcclient. Manages XML interaction, as well as switch and
creates the actual networks
"""
import rpc
from xml_manager.manager import ManagedXml
from oslo.config import cfg
class Manager:
def __init__(self):
self.rpc = rpc.RPC(cfg.CONF.ml2_datacom.dm_username,
cfg.CONF.ml2_datacom.dm_password,
cfg.CONF.ml2_datacom.dm_host,
cfg.CONF.ml2_datacom.dm_method)
self.xml = ManagedXml()
def _update(self):
self.rpc.send_xml(self.xml.xml.as_xml_text())
def create_network(self, vlan):
""" Creates a new network on the switch, if it does not exist already.
"""
self.xml.addVlan(vlan)
self._update()
Add error treatment for existing network""" Main class from dcclient. Manages XML interaction, as well as switch and
creates the actual networks
"""
import rpc
from xml_manager.manager import ManagedXml
from neutron.openstack.common import log as logger
from oslo.config import cfg
LOG = logger.getLogger(__name__)
class Manager:
def __init__(self):
self.rpc = rpc.RPC(cfg.CONF.ml2_datacom.dm_username,
cfg.CONF.ml2_datacom.dm_password,
cfg.CONF.ml2_datacom.dm_host,
cfg.CONF.ml2_datacom.dm_method)
self.xml = ManagedXml()
def _update(self):
self.rpc.send_xml(self.xml.xml.as_xml_text())
def create_network(self, vlan):
""" Creates a new network on the switch, if it does not exist already.
"""
try:
self.xml.addVlan(vlan)
self._update()
except:
LOG.info("Trying to create already existing network %d:", vlan)
|
<commit_before>""" Main class from dcclient. Manages XML interaction, as well as switch and
creates the actual networks
"""
import rpc
from xml_manager.manager import ManagedXml
from oslo.config import cfg
class Manager:
def __init__(self):
self.rpc = rpc.RPC(cfg.CONF.ml2_datacom.dm_username,
cfg.CONF.ml2_datacom.dm_password,
cfg.CONF.ml2_datacom.dm_host,
cfg.CONF.ml2_datacom.dm_method)
self.xml = ManagedXml()
def _update(self):
self.rpc.send_xml(self.xml.xml.as_xml_text())
def create_network(self, vlan):
""" Creates a new network on the switch, if it does not exist already.
"""
self.xml.addVlan(vlan)
self._update()
<commit_msg>Add error treatment for existing network<commit_after>""" Main class from dcclient. Manages XML interaction, as well as switch and
creates the actual networks
"""
import rpc
from xml_manager.manager import ManagedXml
from neutron.openstack.common import log as logger
from oslo.config import cfg
LOG = logger.getLogger(__name__)
class Manager:
def __init__(self):
self.rpc = rpc.RPC(cfg.CONF.ml2_datacom.dm_username,
cfg.CONF.ml2_datacom.dm_password,
cfg.CONF.ml2_datacom.dm_host,
cfg.CONF.ml2_datacom.dm_method)
self.xml = ManagedXml()
def _update(self):
self.rpc.send_xml(self.xml.xml.as_xml_text())
def create_network(self, vlan):
""" Creates a new network on the switch, if it does not exist already.
"""
try:
self.xml.addVlan(vlan)
self._update()
except:
LOG.info("Trying to create already existing network %d:", vlan)
|
e98f9fcc8537835b5a00bd0b6a755d7980a197de
|
template_tests/tests.py
|
template_tests/tests.py
|
import re
import os
from django.test import TestCase
from .utils import get_template_dirs
re_url = re.compile(r'\shref="(?P<url>(?!https?:|mailto:|\?|{|#)[^"]*)"')
class TestTemplates(TestCase):
def assertValidURLs(self, filename):
with open(filename) as f:
urls = [m.group('url') for m in re_url.finditer(f.read())]
self.failIf(urls, "%s contains hardcoded URLs: %r" % (
filename,
urls,
))
idx = 0
for x in get_template_dirs():
for root, _, filenames in os.walk(x):
for y in filenames:
def wrapper(self, filename=os.path.join(root, y)):
self.assertValidURLs(filename)
idx += 1
locals()['test_template_idx_%04d' % idx] = wrapper
|
import re
import os
from django.test import TestCase
from django.utils.text import slugify
from .utils import get_template_dirs
re_url = re.compile(r'\shref="(?P<url>(?!https?:|mailto:|\?|{|#)[^"]*)"')
class TestTemplatesMeta(type):
def __new__(cls, name, bases, attrs):
def generate(template):
def fn(self):
self.assertValidURLs(template)
return fn
for x in get_template_dirs():
for root, _, templates in os.walk(x):
for y in templates:
template = os.path.join(root, y)
attrs['test_%s' % slugify(template)] = generate(template)
return super(TestTemplatesMeta, cls).__new__(cls, name, bases, attrs)
class TestTemplates(TestCase):
__metaclass__ = TestTemplatesMeta
def assertValidURLs(self, template):
with open(template) as f:
urls = [m.group('url') for m in re_url.finditer(f.read())]
self.failIf(urls, "%s contains hardcoded URLs: %r" % (
template,
urls,
))
|
Use a metaclass instead of dirty dict()-mangling.
|
Use a metaclass instead of dirty dict()-mangling.
|
Python
|
bsd-3-clause
|
lamby/django-template-tests
|
import re
import os
from django.test import TestCase
from .utils import get_template_dirs
re_url = re.compile(r'\shref="(?P<url>(?!https?:|mailto:|\?|{|#)[^"]*)"')
class TestTemplates(TestCase):
def assertValidURLs(self, filename):
with open(filename) as f:
urls = [m.group('url') for m in re_url.finditer(f.read())]
self.failIf(urls, "%s contains hardcoded URLs: %r" % (
filename,
urls,
))
idx = 0
for x in get_template_dirs():
for root, _, filenames in os.walk(x):
for y in filenames:
def wrapper(self, filename=os.path.join(root, y)):
self.assertValidURLs(filename)
idx += 1
locals()['test_template_idx_%04d' % idx] = wrapper
Use a metaclass instead of dirty dict()-mangling.
|
import re
import os
from django.test import TestCase
from django.utils.text import slugify
from .utils import get_template_dirs
re_url = re.compile(r'\shref="(?P<url>(?!https?:|mailto:|\?|{|#)[^"]*)"')
class TestTemplatesMeta(type):
def __new__(cls, name, bases, attrs):
def generate(template):
def fn(self):
self.assertValidURLs(template)
return fn
for x in get_template_dirs():
for root, _, templates in os.walk(x):
for y in templates:
template = os.path.join(root, y)
attrs['test_%s' % slugify(template)] = generate(template)
return super(TestTemplatesMeta, cls).__new__(cls, name, bases, attrs)
class TestTemplates(TestCase):
__metaclass__ = TestTemplatesMeta
def assertValidURLs(self, template):
with open(template) as f:
urls = [m.group('url') for m in re_url.finditer(f.read())]
self.failIf(urls, "%s contains hardcoded URLs: %r" % (
template,
urls,
))
|
<commit_before>import re
import os
from django.test import TestCase
from .utils import get_template_dirs
re_url = re.compile(r'\shref="(?P<url>(?!https?:|mailto:|\?|{|#)[^"]*)"')
class TestTemplates(TestCase):
def assertValidURLs(self, filename):
with open(filename) as f:
urls = [m.group('url') for m in re_url.finditer(f.read())]
self.failIf(urls, "%s contains hardcoded URLs: %r" % (
filename,
urls,
))
idx = 0
for x in get_template_dirs():
for root, _, filenames in os.walk(x):
for y in filenames:
def wrapper(self, filename=os.path.join(root, y)):
self.assertValidURLs(filename)
idx += 1
locals()['test_template_idx_%04d' % idx] = wrapper
<commit_msg>Use a metaclass instead of dirty dict()-mangling.<commit_after>
|
import re
import os
from django.test import TestCase
from django.utils.text import slugify
from .utils import get_template_dirs
re_url = re.compile(r'\shref="(?P<url>(?!https?:|mailto:|\?|{|#)[^"]*)"')
class TestTemplatesMeta(type):
def __new__(cls, name, bases, attrs):
def generate(template):
def fn(self):
self.assertValidURLs(template)
return fn
for x in get_template_dirs():
for root, _, templates in os.walk(x):
for y in templates:
template = os.path.join(root, y)
attrs['test_%s' % slugify(template)] = generate(template)
return super(TestTemplatesMeta, cls).__new__(cls, name, bases, attrs)
class TestTemplates(TestCase):
__metaclass__ = TestTemplatesMeta
def assertValidURLs(self, template):
with open(template) as f:
urls = [m.group('url') for m in re_url.finditer(f.read())]
self.failIf(urls, "%s contains hardcoded URLs: %r" % (
template,
urls,
))
|
import re
import os
from django.test import TestCase
from .utils import get_template_dirs
re_url = re.compile(r'\shref="(?P<url>(?!https?:|mailto:|\?|{|#)[^"]*)"')
class TestTemplates(TestCase):
def assertValidURLs(self, filename):
with open(filename) as f:
urls = [m.group('url') for m in re_url.finditer(f.read())]
self.failIf(urls, "%s contains hardcoded URLs: %r" % (
filename,
urls,
))
idx = 0
for x in get_template_dirs():
for root, _, filenames in os.walk(x):
for y in filenames:
def wrapper(self, filename=os.path.join(root, y)):
self.assertValidURLs(filename)
idx += 1
locals()['test_template_idx_%04d' % idx] = wrapper
Use a metaclass instead of dirty dict()-mangling.import re
import os
from django.test import TestCase
from django.utils.text import slugify
from .utils import get_template_dirs
re_url = re.compile(r'\shref="(?P<url>(?!https?:|mailto:|\?|{|#)[^"]*)"')
class TestTemplatesMeta(type):
def __new__(cls, name, bases, attrs):
def generate(template):
def fn(self):
self.assertValidURLs(template)
return fn
for x in get_template_dirs():
for root, _, templates in os.walk(x):
for y in templates:
template = os.path.join(root, y)
attrs['test_%s' % slugify(template)] = generate(template)
return super(TestTemplatesMeta, cls).__new__(cls, name, bases, attrs)
class TestTemplates(TestCase):
__metaclass__ = TestTemplatesMeta
def assertValidURLs(self, template):
with open(template) as f:
urls = [m.group('url') for m in re_url.finditer(f.read())]
self.failIf(urls, "%s contains hardcoded URLs: %r" % (
template,
urls,
))
|
<commit_before>import re
import os
from django.test import TestCase
from .utils import get_template_dirs
re_url = re.compile(r'\shref="(?P<url>(?!https?:|mailto:|\?|{|#)[^"]*)"')
class TestTemplates(TestCase):
def assertValidURLs(self, filename):
with open(filename) as f:
urls = [m.group('url') for m in re_url.finditer(f.read())]
self.failIf(urls, "%s contains hardcoded URLs: %r" % (
filename,
urls,
))
idx = 0
for x in get_template_dirs():
for root, _, filenames in os.walk(x):
for y in filenames:
def wrapper(self, filename=os.path.join(root, y)):
self.assertValidURLs(filename)
idx += 1
locals()['test_template_idx_%04d' % idx] = wrapper
<commit_msg>Use a metaclass instead of dirty dict()-mangling.<commit_after>import re
import os
from django.test import TestCase
from django.utils.text import slugify
from .utils import get_template_dirs
re_url = re.compile(r'\shref="(?P<url>(?!https?:|mailto:|\?|{|#)[^"]*)"')
class TestTemplatesMeta(type):
def __new__(cls, name, bases, attrs):
def generate(template):
def fn(self):
self.assertValidURLs(template)
return fn
for x in get_template_dirs():
for root, _, templates in os.walk(x):
for y in templates:
template = os.path.join(root, y)
attrs['test_%s' % slugify(template)] = generate(template)
return super(TestTemplatesMeta, cls).__new__(cls, name, bases, attrs)
class TestTemplates(TestCase):
__metaclass__ = TestTemplatesMeta
def assertValidURLs(self, template):
with open(template) as f:
urls = [m.group('url') for m in re_url.finditer(f.read())]
self.failIf(urls, "%s contains hardcoded URLs: %r" % (
template,
urls,
))
|
57560385ef05ba6a2234e43795a037a487f26cfd
|
djaml/utils.py
|
djaml/utils.py
|
import imp
from os import listdir
from os.path import dirname, splitext
from django.template import loaders
MODULE_EXTENSIONS = tuple([suffix[0] for suffix in imp.get_suffixes()])
def get_django_template_loaders():
return [(loader.__name__.rsplit('.',1)[1], loader)
for loader in get_submodules(loaders)
if hasattr(loader, 'load_template_source')]
def get_submodules(package):
submodules = ("%s.%s" % (package.__name__, module)
for module in package_contents(package))
return [__import__(module, {}, {}, [module.rsplit(".", 1)[-1]])
for module in submodules]
def package_contents(package):
package_path = dirname(loaders.__file__)
contents = set([splitext(module)[0]
for module in listdir(package_path)
if module.endswith(MODULE_EXTENSIONS)])
return contents
|
import imp
from os import listdir
from os.path import dirname, splitext
from django.template import loaders
MODULE_EXTENSIONS = tuple([suffix[0] for suffix in imp.get_suffixes()])
def get_django_template_loaders():
return [(loader.__name__.rsplit('.',1)[1], loader)
for loader in get_submodules(loaders)
if hasattr(loader, 'Loader')]
def get_submodules(package):
submodules = ("%s.%s" % (package.__name__, module)
for module in package_contents(package))
return [__import__(module, {}, {}, [module.rsplit(".", 1)[-1]])
for module in submodules]
def package_contents(package):
package_path = dirname(loaders.__file__)
contents = set([splitext(module)[0]
for module in listdir(package_path)
if module.endswith(MODULE_EXTENSIONS)])
return contents
|
Fix submodule attribute check for Django 1.4 compatibility
|
Fix submodule attribute check for Django 1.4 compatibility
|
Python
|
mit
|
chartjes/djaml
|
import imp
from os import listdir
from os.path import dirname, splitext
from django.template import loaders
MODULE_EXTENSIONS = tuple([suffix[0] for suffix in imp.get_suffixes()])
def get_django_template_loaders():
return [(loader.__name__.rsplit('.',1)[1], loader)
for loader in get_submodules(loaders)
if hasattr(loader, 'load_template_source')]
def get_submodules(package):
submodules = ("%s.%s" % (package.__name__, module)
for module in package_contents(package))
return [__import__(module, {}, {}, [module.rsplit(".", 1)[-1]])
for module in submodules]
def package_contents(package):
package_path = dirname(loaders.__file__)
contents = set([splitext(module)[0]
for module in listdir(package_path)
if module.endswith(MODULE_EXTENSIONS)])
return contents
Fix submodule attribute check for Django 1.4 compatibility
|
import imp
from os import listdir
from os.path import dirname, splitext
from django.template import loaders
MODULE_EXTENSIONS = tuple([suffix[0] for suffix in imp.get_suffixes()])
def get_django_template_loaders():
return [(loader.__name__.rsplit('.',1)[1], loader)
for loader in get_submodules(loaders)
if hasattr(loader, 'Loader')]
def get_submodules(package):
submodules = ("%s.%s" % (package.__name__, module)
for module in package_contents(package))
return [__import__(module, {}, {}, [module.rsplit(".", 1)[-1]])
for module in submodules]
def package_contents(package):
package_path = dirname(loaders.__file__)
contents = set([splitext(module)[0]
for module in listdir(package_path)
if module.endswith(MODULE_EXTENSIONS)])
return contents
|
<commit_before>import imp
from os import listdir
from os.path import dirname, splitext
from django.template import loaders
MODULE_EXTENSIONS = tuple([suffix[0] for suffix in imp.get_suffixes()])
def get_django_template_loaders():
return [(loader.__name__.rsplit('.',1)[1], loader)
for loader in get_submodules(loaders)
if hasattr(loader, 'load_template_source')]
def get_submodules(package):
submodules = ("%s.%s" % (package.__name__, module)
for module in package_contents(package))
return [__import__(module, {}, {}, [module.rsplit(".", 1)[-1]])
for module in submodules]
def package_contents(package):
package_path = dirname(loaders.__file__)
contents = set([splitext(module)[0]
for module in listdir(package_path)
if module.endswith(MODULE_EXTENSIONS)])
return contents
<commit_msg>Fix submodule attribute check for Django 1.4 compatibility<commit_after>
|
import imp
from os import listdir
from os.path import dirname, splitext
from django.template import loaders
MODULE_EXTENSIONS = tuple([suffix[0] for suffix in imp.get_suffixes()])
def get_django_template_loaders():
return [(loader.__name__.rsplit('.',1)[1], loader)
for loader in get_submodules(loaders)
if hasattr(loader, 'Loader')]
def get_submodules(package):
submodules = ("%s.%s" % (package.__name__, module)
for module in package_contents(package))
return [__import__(module, {}, {}, [module.rsplit(".", 1)[-1]])
for module in submodules]
def package_contents(package):
package_path = dirname(loaders.__file__)
contents = set([splitext(module)[0]
for module in listdir(package_path)
if module.endswith(MODULE_EXTENSIONS)])
return contents
|
import imp
from os import listdir
from os.path import dirname, splitext
from django.template import loaders
MODULE_EXTENSIONS = tuple([suffix[0] for suffix in imp.get_suffixes()])
def get_django_template_loaders():
return [(loader.__name__.rsplit('.',1)[1], loader)
for loader in get_submodules(loaders)
if hasattr(loader, 'load_template_source')]
def get_submodules(package):
submodules = ("%s.%s" % (package.__name__, module)
for module in package_contents(package))
return [__import__(module, {}, {}, [module.rsplit(".", 1)[-1]])
for module in submodules]
def package_contents(package):
package_path = dirname(loaders.__file__)
contents = set([splitext(module)[0]
for module in listdir(package_path)
if module.endswith(MODULE_EXTENSIONS)])
return contents
Fix submodule attribute check for Django 1.4 compatibilityimport imp
from os import listdir
from os.path import dirname, splitext
from django.template import loaders
MODULE_EXTENSIONS = tuple([suffix[0] for suffix in imp.get_suffixes()])
def get_django_template_loaders():
return [(loader.__name__.rsplit('.',1)[1], loader)
for loader in get_submodules(loaders)
if hasattr(loader, 'Loader')]
def get_submodules(package):
submodules = ("%s.%s" % (package.__name__, module)
for module in package_contents(package))
return [__import__(module, {}, {}, [module.rsplit(".", 1)[-1]])
for module in submodules]
def package_contents(package):
package_path = dirname(loaders.__file__)
contents = set([splitext(module)[0]
for module in listdir(package_path)
if module.endswith(MODULE_EXTENSIONS)])
return contents
|
<commit_before>import imp
from os import listdir
from os.path import dirname, splitext
from django.template import loaders
MODULE_EXTENSIONS = tuple([suffix[0] for suffix in imp.get_suffixes()])
def get_django_template_loaders():
return [(loader.__name__.rsplit('.',1)[1], loader)
for loader in get_submodules(loaders)
if hasattr(loader, 'load_template_source')]
def get_submodules(package):
submodules = ("%s.%s" % (package.__name__, module)
for module in package_contents(package))
return [__import__(module, {}, {}, [module.rsplit(".", 1)[-1]])
for module in submodules]
def package_contents(package):
package_path = dirname(loaders.__file__)
contents = set([splitext(module)[0]
for module in listdir(package_path)
if module.endswith(MODULE_EXTENSIONS)])
return contents
<commit_msg>Fix submodule attribute check for Django 1.4 compatibility<commit_after>import imp
from os import listdir
from os.path import dirname, splitext
from django.template import loaders
MODULE_EXTENSIONS = tuple([suffix[0] for suffix in imp.get_suffixes()])
def get_django_template_loaders():
return [(loader.__name__.rsplit('.',1)[1], loader)
for loader in get_submodules(loaders)
if hasattr(loader, 'Loader')]
def get_submodules(package):
submodules = ("%s.%s" % (package.__name__, module)
for module in package_contents(package))
return [__import__(module, {}, {}, [module.rsplit(".", 1)[-1]])
for module in submodules]
def package_contents(package):
package_path = dirname(loaders.__file__)
contents = set([splitext(module)[0]
for module in listdir(package_path)
if module.endswith(MODULE_EXTENSIONS)])
return contents
|
db08b3462fc217cfbf3644051f299ef5bbef3d14
|
ckanext/stadtzhtheme/tests/test_validation.py
|
ckanext/stadtzhtheme/tests/test_validation.py
|
import nose
from ckanapi import TestAppCKAN, ValidationError
from ckan.tests import helpers, factories
eq_ = nose.tools.eq_
assert_true = nose.tools.assert_true
class TestValidation(helpers.FunctionalTestBase):
def test_invalid_url(self):
"""Test that an invalid resource url is caught by our validator.
"""
factories.Sysadmin(apikey="my-test-key")
app = self._get_test_app()
demo = TestAppCKAN(app, apikey="my-test-key")
try:
dataset = factories.Dataset()
demo.action.resource_create(
package_id=dataset['name'],
name='Test-File',
url='https://example.com]'
)
except ValidationError as e:
eq_(
e.error_dict['url'],
[u'Bitte eine valide URL angeben']
)
else:
raise AssertionError('ValidationError not raised')
def test_invalid_url_for_upload_resource_type(self):
"""Test that the resource url is not validated if the url_type
is 'upload'.
"""
factories.Sysadmin(apikey="my-test-key")
app = self._get_test_app()
demo = TestAppCKAN(app, apikey="my-test-key")
try:
dataset = factories.Dataset()
demo.action.resource_create(
package_id=dataset['name'],
name='Test-File',
url='https://example.com]',
url_type='upload'
)
except ValidationError:
raise AssertionError('ValidationError raised erroneously')
|
import pytest
from ckanapi import ValidationError
from ckan.tests import helpers, factories
from ckantoolkit import config
@pytest.mark.ckan_config("ckan.plugins", "stadtzhtheme")
@pytest.mark.usefixtures("clean_db", "with_plugins")
class TestValidation(object):
def test_invalid_url(self):
"""Test that an invalid resource url is caught by our validator.
"""
print(config.get('ckan.plugins'))
try:
dataset = factories.Dataset()
helpers.call_action(
'resource_download_permalink',
{},
package_id=dataset['name'],
name='Test-File',
url='https://example.com]'
)
except ValidationError as e:
assert e.error_dict['url'] == [u'Bitte eine valide URL angeben']
else:
raise AssertionError('ValidationError not raised')
def test_invalid_url_for_upload_resource_type(self):
"""Test that the resource url is not validated if the url_type
is 'upload'.
"""
try:
dataset = factories.Dataset()
helpers.call_action(
'resource_create',
package_id=dataset['name'],
name='Test-File',
url='https://example.com]',
url_type='upload'
)
except ValidationError:
raise AssertionError('ValidationError raised erroneously')
|
Update tests to use pytest instead of nose
|
tests: Update tests to use pytest instead of nose
|
Python
|
agpl-3.0
|
opendatazurich/ckanext-stadtzh-theme,opendatazurich/ckanext-stadtzh-theme,opendatazurich/ckanext-stadtzh-theme
|
import nose
from ckanapi import TestAppCKAN, ValidationError
from ckan.tests import helpers, factories
eq_ = nose.tools.eq_
assert_true = nose.tools.assert_true
class TestValidation(helpers.FunctionalTestBase):
def test_invalid_url(self):
"""Test that an invalid resource url is caught by our validator.
"""
factories.Sysadmin(apikey="my-test-key")
app = self._get_test_app()
demo = TestAppCKAN(app, apikey="my-test-key")
try:
dataset = factories.Dataset()
demo.action.resource_create(
package_id=dataset['name'],
name='Test-File',
url='https://example.com]'
)
except ValidationError as e:
eq_(
e.error_dict['url'],
[u'Bitte eine valide URL angeben']
)
else:
raise AssertionError('ValidationError not raised')
def test_invalid_url_for_upload_resource_type(self):
"""Test that the resource url is not validated if the url_type
is 'upload'.
"""
factories.Sysadmin(apikey="my-test-key")
app = self._get_test_app()
demo = TestAppCKAN(app, apikey="my-test-key")
try:
dataset = factories.Dataset()
demo.action.resource_create(
package_id=dataset['name'],
name='Test-File',
url='https://example.com]',
url_type='upload'
)
except ValidationError:
raise AssertionError('ValidationError raised erroneously')
tests: Update tests to use pytest instead of nose
|
import pytest
from ckanapi import ValidationError
from ckan.tests import helpers, factories
from ckantoolkit import config
@pytest.mark.ckan_config("ckan.plugins", "stadtzhtheme")
@pytest.mark.usefixtures("clean_db", "with_plugins")
class TestValidation(object):
def test_invalid_url(self):
"""Test that an invalid resource url is caught by our validator.
"""
print(config.get('ckan.plugins'))
try:
dataset = factories.Dataset()
helpers.call_action(
'resource_download_permalink',
{},
package_id=dataset['name'],
name='Test-File',
url='https://example.com]'
)
except ValidationError as e:
assert e.error_dict['url'] == [u'Bitte eine valide URL angeben']
else:
raise AssertionError('ValidationError not raised')
def test_invalid_url_for_upload_resource_type(self):
"""Test that the resource url is not validated if the url_type
is 'upload'.
"""
try:
dataset = factories.Dataset()
helpers.call_action(
'resource_create',
package_id=dataset['name'],
name='Test-File',
url='https://example.com]',
url_type='upload'
)
except ValidationError:
raise AssertionError('ValidationError raised erroneously')
|
<commit_before>import nose
from ckanapi import TestAppCKAN, ValidationError
from ckan.tests import helpers, factories
eq_ = nose.tools.eq_
assert_true = nose.tools.assert_true
class TestValidation(helpers.FunctionalTestBase):
def test_invalid_url(self):
"""Test that an invalid resource url is caught by our validator.
"""
factories.Sysadmin(apikey="my-test-key")
app = self._get_test_app()
demo = TestAppCKAN(app, apikey="my-test-key")
try:
dataset = factories.Dataset()
demo.action.resource_create(
package_id=dataset['name'],
name='Test-File',
url='https://example.com]'
)
except ValidationError as e:
eq_(
e.error_dict['url'],
[u'Bitte eine valide URL angeben']
)
else:
raise AssertionError('ValidationError not raised')
def test_invalid_url_for_upload_resource_type(self):
"""Test that the resource url is not validated if the url_type
is 'upload'.
"""
factories.Sysadmin(apikey="my-test-key")
app = self._get_test_app()
demo = TestAppCKAN(app, apikey="my-test-key")
try:
dataset = factories.Dataset()
demo.action.resource_create(
package_id=dataset['name'],
name='Test-File',
url='https://example.com]',
url_type='upload'
)
except ValidationError:
raise AssertionError('ValidationError raised erroneously')
<commit_msg>tests: Update tests to use pytest instead of nose<commit_after>
|
import pytest
from ckanapi import ValidationError
from ckan.tests import helpers, factories
from ckantoolkit import config
@pytest.mark.ckan_config("ckan.plugins", "stadtzhtheme")
@pytest.mark.usefixtures("clean_db", "with_plugins")
class TestValidation(object):
def test_invalid_url(self):
"""Test that an invalid resource url is caught by our validator.
"""
print(config.get('ckan.plugins'))
try:
dataset = factories.Dataset()
helpers.call_action(
'resource_download_permalink',
{},
package_id=dataset['name'],
name='Test-File',
url='https://example.com]'
)
except ValidationError as e:
assert e.error_dict['url'] == [u'Bitte eine valide URL angeben']
else:
raise AssertionError('ValidationError not raised')
def test_invalid_url_for_upload_resource_type(self):
"""Test that the resource url is not validated if the url_type
is 'upload'.
"""
try:
dataset = factories.Dataset()
helpers.call_action(
'resource_create',
package_id=dataset['name'],
name='Test-File',
url='https://example.com]',
url_type='upload'
)
except ValidationError:
raise AssertionError('ValidationError raised erroneously')
|
import nose
from ckanapi import TestAppCKAN, ValidationError
from ckan.tests import helpers, factories
eq_ = nose.tools.eq_
assert_true = nose.tools.assert_true
class TestValidation(helpers.FunctionalTestBase):
def test_invalid_url(self):
"""Test that an invalid resource url is caught by our validator.
"""
factories.Sysadmin(apikey="my-test-key")
app = self._get_test_app()
demo = TestAppCKAN(app, apikey="my-test-key")
try:
dataset = factories.Dataset()
demo.action.resource_create(
package_id=dataset['name'],
name='Test-File',
url='https://example.com]'
)
except ValidationError as e:
eq_(
e.error_dict['url'],
[u'Bitte eine valide URL angeben']
)
else:
raise AssertionError('ValidationError not raised')
def test_invalid_url_for_upload_resource_type(self):
"""Test that the resource url is not validated if the url_type
is 'upload'.
"""
factories.Sysadmin(apikey="my-test-key")
app = self._get_test_app()
demo = TestAppCKAN(app, apikey="my-test-key")
try:
dataset = factories.Dataset()
demo.action.resource_create(
package_id=dataset['name'],
name='Test-File',
url='https://example.com]',
url_type='upload'
)
except ValidationError:
raise AssertionError('ValidationError raised erroneously')
tests: Update tests to use pytest instead of noseimport pytest
from ckanapi import ValidationError
from ckan.tests import helpers, factories
from ckantoolkit import config
@pytest.mark.ckan_config("ckan.plugins", "stadtzhtheme")
@pytest.mark.usefixtures("clean_db", "with_plugins")
class TestValidation(object):
def test_invalid_url(self):
"""Test that an invalid resource url is caught by our validator.
"""
print(config.get('ckan.plugins'))
try:
dataset = factories.Dataset()
helpers.call_action(
'resource_download_permalink',
{},
package_id=dataset['name'],
name='Test-File',
url='https://example.com]'
)
except ValidationError as e:
assert e.error_dict['url'] == [u'Bitte eine valide URL angeben']
else:
raise AssertionError('ValidationError not raised')
def test_invalid_url_for_upload_resource_type(self):
"""Test that the resource url is not validated if the url_type
is 'upload'.
"""
try:
dataset = factories.Dataset()
helpers.call_action(
'resource_create',
package_id=dataset['name'],
name='Test-File',
url='https://example.com]',
url_type='upload'
)
except ValidationError:
raise AssertionError('ValidationError raised erroneously')
|
<commit_before>import nose
from ckanapi import TestAppCKAN, ValidationError
from ckan.tests import helpers, factories
eq_ = nose.tools.eq_
assert_true = nose.tools.assert_true
class TestValidation(helpers.FunctionalTestBase):
def test_invalid_url(self):
"""Test that an invalid resource url is caught by our validator.
"""
factories.Sysadmin(apikey="my-test-key")
app = self._get_test_app()
demo = TestAppCKAN(app, apikey="my-test-key")
try:
dataset = factories.Dataset()
demo.action.resource_create(
package_id=dataset['name'],
name='Test-File',
url='https://example.com]'
)
except ValidationError as e:
eq_(
e.error_dict['url'],
[u'Bitte eine valide URL angeben']
)
else:
raise AssertionError('ValidationError not raised')
def test_invalid_url_for_upload_resource_type(self):
"""Test that the resource url is not validated if the url_type
is 'upload'.
"""
factories.Sysadmin(apikey="my-test-key")
app = self._get_test_app()
demo = TestAppCKAN(app, apikey="my-test-key")
try:
dataset = factories.Dataset()
demo.action.resource_create(
package_id=dataset['name'],
name='Test-File',
url='https://example.com]',
url_type='upload'
)
except ValidationError:
raise AssertionError('ValidationError raised erroneously')
<commit_msg>tests: Update tests to use pytest instead of nose<commit_after>import pytest
from ckanapi import ValidationError
from ckan.tests import helpers, factories
from ckantoolkit import config
@pytest.mark.ckan_config("ckan.plugins", "stadtzhtheme")
@pytest.mark.usefixtures("clean_db", "with_plugins")
class TestValidation(object):
def test_invalid_url(self):
"""Test that an invalid resource url is caught by our validator.
"""
print(config.get('ckan.plugins'))
try:
dataset = factories.Dataset()
helpers.call_action(
'resource_download_permalink',
{},
package_id=dataset['name'],
name='Test-File',
url='https://example.com]'
)
except ValidationError as e:
assert e.error_dict['url'] == [u'Bitte eine valide URL angeben']
else:
raise AssertionError('ValidationError not raised')
def test_invalid_url_for_upload_resource_type(self):
"""Test that the resource url is not validated if the url_type
is 'upload'.
"""
try:
dataset = factories.Dataset()
helpers.call_action(
'resource_create',
package_id=dataset['name'],
name='Test-File',
url='https://example.com]',
url_type='upload'
)
except ValidationError:
raise AssertionError('ValidationError raised erroneously')
|
22992aeeb123b061a9c11d812ac7fad6427453eb
|
timpani/themes.py
|
timpani/themes.py
|
import os
import os.path
from . import database
THEME_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "../themes"))
def getCurrentTheme():
databaseConnection = database.ConnectionManager.getConnection("main")
query = (databaseConnection.session
.query(database.tables.Setting)
.filter(database.tables.Setting.name == "theme"))
if query.count() > 0:
themeName = query.first().value
themes = os.listdir(THEME_PATH)
folderName = None
try:
folderName = next(theme for theme in themes if theme.lower() == themeName.lower())
except StopIteration:
return None
themeFile = open(os.path.join(THEME_PATH, folderName, "theme.css"), "r")
theme = themeFile.read()
themeFile.close()
return theme
def getAvailableThemes():
files = os.listdir(THEME_PATH)
for item in files:
path = os.path.join(THEME_PATH, item)
if not os.path.isdir(path):
files.remove(item)
return files
|
import os
import os.path
from . import database
THEME_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "../themes"))
def getCurrentTheme():
databaseConnection = database.ConnectionManager.getConnection("main")
query = (databaseConnection.session
.query(database.tables.Setting)
.filter(database.tables.Setting.name == "theme"))
if query.count() > 0:
themeName = query.first().value
themes = os.listdir(THEME_PATH)
folderName = None
try:
folderName = next(theme for theme in themes if theme.lower() == themeName.lower())
except StopIteration:
return None
themeFile = open(
os.path.join(THEME_PATH, folderName, "theme.css"), "r")
theme = themeFile.read()
themeFile.close()
templateFile = open(
os.path.join(THEME_PATH, folderName, "template.html"), "r")
template = templatefile.read()
templateFile.close()
return {"template": template, "theme": theme}
def getAvailableThemes():
files = os.listdir(THEME_PATH)
for item in files:
path = os.path.join(THEME_PATH, item)
if not os.path.isdir(path):
files.remove(item)
return files
|
Add template support to getCurrentTheme
|
Add template support to getCurrentTheme
|
Python
|
mit
|
ollien/Timpani,ollien/Timpani,ollien/Timpani
|
import os
import os.path
from . import database
THEME_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "../themes"))
def getCurrentTheme():
databaseConnection = database.ConnectionManager.getConnection("main")
query = (databaseConnection.session
.query(database.tables.Setting)
.filter(database.tables.Setting.name == "theme"))
if query.count() > 0:
themeName = query.first().value
themes = os.listdir(THEME_PATH)
folderName = None
try:
folderName = next(theme for theme in themes if theme.lower() == themeName.lower())
except StopIteration:
return None
themeFile = open(os.path.join(THEME_PATH, folderName, "theme.css"), "r")
theme = themeFile.read()
themeFile.close()
return theme
def getAvailableThemes():
files = os.listdir(THEME_PATH)
for item in files:
path = os.path.join(THEME_PATH, item)
if not os.path.isdir(path):
files.remove(item)
return files
Add template support to getCurrentTheme
|
import os
import os.path
from . import database
THEME_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "../themes"))
def getCurrentTheme():
databaseConnection = database.ConnectionManager.getConnection("main")
query = (databaseConnection.session
.query(database.tables.Setting)
.filter(database.tables.Setting.name == "theme"))
if query.count() > 0:
themeName = query.first().value
themes = os.listdir(THEME_PATH)
folderName = None
try:
folderName = next(theme for theme in themes if theme.lower() == themeName.lower())
except StopIteration:
return None
themeFile = open(
os.path.join(THEME_PATH, folderName, "theme.css"), "r")
theme = themeFile.read()
themeFile.close()
templateFile = open(
os.path.join(THEME_PATH, folderName, "template.html"), "r")
template = templatefile.read()
templateFile.close()
return {"template": template, "theme": theme}
def getAvailableThemes():
files = os.listdir(THEME_PATH)
for item in files:
path = os.path.join(THEME_PATH, item)
if not os.path.isdir(path):
files.remove(item)
return files
|
<commit_before>import os
import os.path
from . import database
THEME_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "../themes"))
def getCurrentTheme():
databaseConnection = database.ConnectionManager.getConnection("main")
query = (databaseConnection.session
.query(database.tables.Setting)
.filter(database.tables.Setting.name == "theme"))
if query.count() > 0:
themeName = query.first().value
themes = os.listdir(THEME_PATH)
folderName = None
try:
folderName = next(theme for theme in themes if theme.lower() == themeName.lower())
except StopIteration:
return None
themeFile = open(os.path.join(THEME_PATH, folderName, "theme.css"), "r")
theme = themeFile.read()
themeFile.close()
return theme
def getAvailableThemes():
files = os.listdir(THEME_PATH)
for item in files:
path = os.path.join(THEME_PATH, item)
if not os.path.isdir(path):
files.remove(item)
return files
<commit_msg>Add template support to getCurrentTheme<commit_after>
|
import os
import os.path
from . import database
THEME_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "../themes"))
def getCurrentTheme():
databaseConnection = database.ConnectionManager.getConnection("main")
query = (databaseConnection.session
.query(database.tables.Setting)
.filter(database.tables.Setting.name == "theme"))
if query.count() > 0:
themeName = query.first().value
themes = os.listdir(THEME_PATH)
folderName = None
try:
folderName = next(theme for theme in themes if theme.lower() == themeName.lower())
except StopIteration:
return None
themeFile = open(
os.path.join(THEME_PATH, folderName, "theme.css"), "r")
theme = themeFile.read()
themeFile.close()
templateFile = open(
os.path.join(THEME_PATH, folderName, "template.html"), "r")
template = templatefile.read()
templateFile.close()
return {"template": template, "theme": theme}
def getAvailableThemes():
files = os.listdir(THEME_PATH)
for item in files:
path = os.path.join(THEME_PATH, item)
if not os.path.isdir(path):
files.remove(item)
return files
|
import os
import os.path
from . import database
THEME_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "../themes"))
def getCurrentTheme():
databaseConnection = database.ConnectionManager.getConnection("main")
query = (databaseConnection.session
.query(database.tables.Setting)
.filter(database.tables.Setting.name == "theme"))
if query.count() > 0:
themeName = query.first().value
themes = os.listdir(THEME_PATH)
folderName = None
try:
folderName = next(theme for theme in themes if theme.lower() == themeName.lower())
except StopIteration:
return None
themeFile = open(os.path.join(THEME_PATH, folderName, "theme.css"), "r")
theme = themeFile.read()
themeFile.close()
return theme
def getAvailableThemes():
files = os.listdir(THEME_PATH)
for item in files:
path = os.path.join(THEME_PATH, item)
if not os.path.isdir(path):
files.remove(item)
return files
Add template support to getCurrentThemeimport os
import os.path
from . import database
THEME_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "../themes"))
def getCurrentTheme():
databaseConnection = database.ConnectionManager.getConnection("main")
query = (databaseConnection.session
.query(database.tables.Setting)
.filter(database.tables.Setting.name == "theme"))
if query.count() > 0:
themeName = query.first().value
themes = os.listdir(THEME_PATH)
folderName = None
try:
folderName = next(theme for theme in themes if theme.lower() == themeName.lower())
except StopIteration:
return None
themeFile = open(
os.path.join(THEME_PATH, folderName, "theme.css"), "r")
theme = themeFile.read()
themeFile.close()
templateFile = open(
os.path.join(THEME_PATH, folderName, "template.html"), "r")
template = templatefile.read()
templateFile.close()
return {"template": template, "theme": theme}
def getAvailableThemes():
files = os.listdir(THEME_PATH)
for item in files:
path = os.path.join(THEME_PATH, item)
if not os.path.isdir(path):
files.remove(item)
return files
|
<commit_before>import os
import os.path
from . import database
THEME_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "../themes"))
def getCurrentTheme():
databaseConnection = database.ConnectionManager.getConnection("main")
query = (databaseConnection.session
.query(database.tables.Setting)
.filter(database.tables.Setting.name == "theme"))
if query.count() > 0:
themeName = query.first().value
themes = os.listdir(THEME_PATH)
folderName = None
try:
folderName = next(theme for theme in themes if theme.lower() == themeName.lower())
except StopIteration:
return None
themeFile = open(os.path.join(THEME_PATH, folderName, "theme.css"), "r")
theme = themeFile.read()
themeFile.close()
return theme
def getAvailableThemes():
files = os.listdir(THEME_PATH)
for item in files:
path = os.path.join(THEME_PATH, item)
if not os.path.isdir(path):
files.remove(item)
return files
<commit_msg>Add template support to getCurrentTheme<commit_after>import os
import os.path
from . import database
THEME_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "../themes"))
def getCurrentTheme():
databaseConnection = database.ConnectionManager.getConnection("main")
query = (databaseConnection.session
.query(database.tables.Setting)
.filter(database.tables.Setting.name == "theme"))
if query.count() > 0:
themeName = query.first().value
themes = os.listdir(THEME_PATH)
folderName = None
try:
folderName = next(theme for theme in themes if theme.lower() == themeName.lower())
except StopIteration:
return None
themeFile = open(
os.path.join(THEME_PATH, folderName, "theme.css"), "r")
theme = themeFile.read()
themeFile.close()
templateFile = open(
os.path.join(THEME_PATH, folderName, "template.html"), "r")
template = templatefile.read()
templateFile.close()
return {"template": template, "theme": theme}
def getAvailableThemes():
files = os.listdir(THEME_PATH)
for item in files:
path = os.path.join(THEME_PATH, item)
if not os.path.isdir(path):
files.remove(item)
return files
|
fa6402472e30f59e67acf45d9faba632a3efc5e8
|
raiden/constants.py
|
raiden/constants.py
|
# -*- coding: utf-8 -*-
UINT64_MAX = 2 ** 64 - 1
UINT64_MIN = 0
INT64_MAX = 2 ** 63 - 1
INT64_MIN = -(2 ** 63)
UINT256_MAX = 2 ** 256 - 1
ROPSTEN_REGISTRY_ADDRESS = 'bbc60aa23059b039407ac008bd0b7e902890d382'
ROPSTEN_DISCOVERY_ADDRESS = '524b7dcacac3055bd42fc03b006e9fdcb607e2be'
MINUTE_SEC = 60
MINUTE_MS = 60 * 1000
NETTINGCHANNEL_SETTLE_TIMEOUT_MIN = 6
# TODO: add this as an attribute of the transport class
UDP_MAX_MESSAGE_SIZE = 1200
|
# -*- coding: utf-8 -*-
UINT64_MAX = 2 ** 64 - 1
UINT64_MIN = 0
INT64_MAX = 2 ** 63 - 1
INT64_MIN = -(2 ** 63)
UINT256_MAX = 2 ** 256 - 1
# Deployed to Ropsten revival on 2017-06-19 from commit 2677298a69c1b1f35b9ab26beafe457acfdcc0ee
ROPSTEN_REGISTRY_ADDRESS = 'aff1f958c69a6820b08a02549ff9041629ae8257'
ROPSTEN_DISCOVERY_ADDRESS = 'cf56165f4f6e8ec38bb463854c1fe28a5d320f4f'
MINUTE_SEC = 60
MINUTE_MS = 60 * 1000
NETTINGCHANNEL_SETTLE_TIMEOUT_MIN = 6
# TODO: add this as an attribute of the transport class
UDP_MAX_MESSAGE_SIZE = 1200
|
Update pre-deployed Ropsten contract addresses
|
Update pre-deployed Ropsten contract addresses
|
Python
|
mit
|
hackaugusto/raiden,tomashaber/raiden,tomashaber/raiden,tomashaber/raiden,tomashaber/raiden,tomashaber/raiden,hackaugusto/raiden
|
# -*- coding: utf-8 -*-
UINT64_MAX = 2 ** 64 - 1
UINT64_MIN = 0
INT64_MAX = 2 ** 63 - 1
INT64_MIN = -(2 ** 63)
UINT256_MAX = 2 ** 256 - 1
ROPSTEN_REGISTRY_ADDRESS = 'bbc60aa23059b039407ac008bd0b7e902890d382'
ROPSTEN_DISCOVERY_ADDRESS = '524b7dcacac3055bd42fc03b006e9fdcb607e2be'
MINUTE_SEC = 60
MINUTE_MS = 60 * 1000
NETTINGCHANNEL_SETTLE_TIMEOUT_MIN = 6
# TODO: add this as an attribute of the transport class
UDP_MAX_MESSAGE_SIZE = 1200
Update pre-deployed Ropsten contract addresses
|
# -*- coding: utf-8 -*-
UINT64_MAX = 2 ** 64 - 1
UINT64_MIN = 0
INT64_MAX = 2 ** 63 - 1
INT64_MIN = -(2 ** 63)
UINT256_MAX = 2 ** 256 - 1
# Deployed to Ropsten revival on 2017-06-19 from commit 2677298a69c1b1f35b9ab26beafe457acfdcc0ee
ROPSTEN_REGISTRY_ADDRESS = 'aff1f958c69a6820b08a02549ff9041629ae8257'
ROPSTEN_DISCOVERY_ADDRESS = 'cf56165f4f6e8ec38bb463854c1fe28a5d320f4f'
MINUTE_SEC = 60
MINUTE_MS = 60 * 1000
NETTINGCHANNEL_SETTLE_TIMEOUT_MIN = 6
# TODO: add this as an attribute of the transport class
UDP_MAX_MESSAGE_SIZE = 1200
|
<commit_before># -*- coding: utf-8 -*-
UINT64_MAX = 2 ** 64 - 1
UINT64_MIN = 0
INT64_MAX = 2 ** 63 - 1
INT64_MIN = -(2 ** 63)
UINT256_MAX = 2 ** 256 - 1
ROPSTEN_REGISTRY_ADDRESS = 'bbc60aa23059b039407ac008bd0b7e902890d382'
ROPSTEN_DISCOVERY_ADDRESS = '524b7dcacac3055bd42fc03b006e9fdcb607e2be'
MINUTE_SEC = 60
MINUTE_MS = 60 * 1000
NETTINGCHANNEL_SETTLE_TIMEOUT_MIN = 6
# TODO: add this as an attribute of the transport class
UDP_MAX_MESSAGE_SIZE = 1200
<commit_msg>Update pre-deployed Ropsten contract addresses<commit_after>
|
# -*- coding: utf-8 -*-
UINT64_MAX = 2 ** 64 - 1
UINT64_MIN = 0
INT64_MAX = 2 ** 63 - 1
INT64_MIN = -(2 ** 63)
UINT256_MAX = 2 ** 256 - 1
# Deployed to Ropsten revival on 2017-06-19 from commit 2677298a69c1b1f35b9ab26beafe457acfdcc0ee
ROPSTEN_REGISTRY_ADDRESS = 'aff1f958c69a6820b08a02549ff9041629ae8257'
ROPSTEN_DISCOVERY_ADDRESS = 'cf56165f4f6e8ec38bb463854c1fe28a5d320f4f'
MINUTE_SEC = 60
MINUTE_MS = 60 * 1000
NETTINGCHANNEL_SETTLE_TIMEOUT_MIN = 6
# TODO: add this as an attribute of the transport class
UDP_MAX_MESSAGE_SIZE = 1200
|
# -*- coding: utf-8 -*-
UINT64_MAX = 2 ** 64 - 1
UINT64_MIN = 0
INT64_MAX = 2 ** 63 - 1
INT64_MIN = -(2 ** 63)
UINT256_MAX = 2 ** 256 - 1
ROPSTEN_REGISTRY_ADDRESS = 'bbc60aa23059b039407ac008bd0b7e902890d382'
ROPSTEN_DISCOVERY_ADDRESS = '524b7dcacac3055bd42fc03b006e9fdcb607e2be'
MINUTE_SEC = 60
MINUTE_MS = 60 * 1000
NETTINGCHANNEL_SETTLE_TIMEOUT_MIN = 6
# TODO: add this as an attribute of the transport class
UDP_MAX_MESSAGE_SIZE = 1200
Update pre-deployed Ropsten contract addresses# -*- coding: utf-8 -*-
UINT64_MAX = 2 ** 64 - 1
UINT64_MIN = 0
INT64_MAX = 2 ** 63 - 1
INT64_MIN = -(2 ** 63)
UINT256_MAX = 2 ** 256 - 1
# Deployed to Ropsten revival on 2017-06-19 from commit 2677298a69c1b1f35b9ab26beafe457acfdcc0ee
ROPSTEN_REGISTRY_ADDRESS = 'aff1f958c69a6820b08a02549ff9041629ae8257'
ROPSTEN_DISCOVERY_ADDRESS = 'cf56165f4f6e8ec38bb463854c1fe28a5d320f4f'
MINUTE_SEC = 60
MINUTE_MS = 60 * 1000
NETTINGCHANNEL_SETTLE_TIMEOUT_MIN = 6
# TODO: add this as an attribute of the transport class
UDP_MAX_MESSAGE_SIZE = 1200
|
<commit_before># -*- coding: utf-8 -*-
UINT64_MAX = 2 ** 64 - 1
UINT64_MIN = 0
INT64_MAX = 2 ** 63 - 1
INT64_MIN = -(2 ** 63)
UINT256_MAX = 2 ** 256 - 1
ROPSTEN_REGISTRY_ADDRESS = 'bbc60aa23059b039407ac008bd0b7e902890d382'
ROPSTEN_DISCOVERY_ADDRESS = '524b7dcacac3055bd42fc03b006e9fdcb607e2be'
MINUTE_SEC = 60
MINUTE_MS = 60 * 1000
NETTINGCHANNEL_SETTLE_TIMEOUT_MIN = 6
# TODO: add this as an attribute of the transport class
UDP_MAX_MESSAGE_SIZE = 1200
<commit_msg>Update pre-deployed Ropsten contract addresses<commit_after># -*- coding: utf-8 -*-
UINT64_MAX = 2 ** 64 - 1
UINT64_MIN = 0
INT64_MAX = 2 ** 63 - 1
INT64_MIN = -(2 ** 63)
UINT256_MAX = 2 ** 256 - 1
# Deployed to Ropsten revival on 2017-06-19 from commit 2677298a69c1b1f35b9ab26beafe457acfdcc0ee
ROPSTEN_REGISTRY_ADDRESS = 'aff1f958c69a6820b08a02549ff9041629ae8257'
ROPSTEN_DISCOVERY_ADDRESS = 'cf56165f4f6e8ec38bb463854c1fe28a5d320f4f'
MINUTE_SEC = 60
MINUTE_MS = 60 * 1000
NETTINGCHANNEL_SETTLE_TIMEOUT_MIN = 6
# TODO: add this as an attribute of the transport class
UDP_MAX_MESSAGE_SIZE = 1200
|
335a33465e197c9a2e52ed9de90546e2ca6173ee
|
tests/test_websocket_subscriber.py
|
tests/test_websocket_subscriber.py
|
"""Tests for the WebSocketSubscriber handlers."""
import json
import pytest
from tornado.web import Application
from tornado.websocket import websocket_connect
from tornadose.handlers import WebSocketSubscriber
import utilities
@pytest.fixture
def store():
return utilities.TestStore()
@pytest.fixture
def app():
return Application([
(r'/', WebSocketSubscriber, dict(store=store))
])
@pytest.mark.gen_test
def test_get_message(http_server, io_loop, base_url, store):
conn = yield websocket_connect('ws' + base_url.split('http')[1])
store.submit('test')
io_loop.call_later(0.01, store.publish)
msg = yield conn.read_message()
msg = json.loads(msg)
assert msg['data'] == 'test'
conn.close()
|
"""Tests for the WebSocketSubscriber handlers."""
import json
from tornado.ioloop import IOLoop
from tornado.web import Application
from tornado.websocket import websocket_connect
from tornado.testing import AsyncHTTPTestCase, gen_test
from tornadose.handlers import WebSocketSubscriber
import utilities
class WebSocketSubscriberTestCase(AsyncHTTPTestCase):
def setUp(self):
self.store = utilities.TestStore()
super(WebSocketSubscriberTestCase, self).setUp()
def get_app(self):
return Application([
(r'/', WebSocketSubscriber, dict(store=self.store))
])
@gen_test
def test_get_message(self):
url = self.get_url('/').replace("http://", "ws://")
conn = yield websocket_connect(url)
self.store.submit('test')
IOLoop.current().call_later(0.01, self.store.publish)
msg = yield conn.read_message()
msg = json.loads(msg)
self.assertEqual(msg['data'], 'test')
conn.close()
|
Fix test case for WebSocketSubscriber
|
Fix test case for WebSocketSubscriber
Switched to unittest-style testing (pytest is a bit too magical
especially with the pytest-tornado extension). I may change all
tests later to use unittest.
|
Python
|
mit
|
mivade/tornadose
|
"""Tests for the WebSocketSubscriber handlers."""
import json
import pytest
from tornado.web import Application
from tornado.websocket import websocket_connect
from tornadose.handlers import WebSocketSubscriber
import utilities
@pytest.fixture
def store():
return utilities.TestStore()
@pytest.fixture
def app():
return Application([
(r'/', WebSocketSubscriber, dict(store=store))
])
@pytest.mark.gen_test
def test_get_message(http_server, io_loop, base_url, store):
conn = yield websocket_connect('ws' + base_url.split('http')[1])
store.submit('test')
io_loop.call_later(0.01, store.publish)
msg = yield conn.read_message()
msg = json.loads(msg)
assert msg['data'] == 'test'
conn.close()
Fix test case for WebSocketSubscriber
Switched to unittest-style testing (pytest is a bit too magical
especially with the pytest-tornado extension). I may change all
tests later to use unittest.
|
"""Tests for the WebSocketSubscriber handlers."""
import json
from tornado.ioloop import IOLoop
from tornado.web import Application
from tornado.websocket import websocket_connect
from tornado.testing import AsyncHTTPTestCase, gen_test
from tornadose.handlers import WebSocketSubscriber
import utilities
class WebSocketSubscriberTestCase(AsyncHTTPTestCase):
def setUp(self):
self.store = utilities.TestStore()
super(WebSocketSubscriberTestCase, self).setUp()
def get_app(self):
return Application([
(r'/', WebSocketSubscriber, dict(store=self.store))
])
@gen_test
def test_get_message(self):
url = self.get_url('/').replace("http://", "ws://")
conn = yield websocket_connect(url)
self.store.submit('test')
IOLoop.current().call_later(0.01, self.store.publish)
msg = yield conn.read_message()
msg = json.loads(msg)
self.assertEqual(msg['data'], 'test')
conn.close()
|
<commit_before>"""Tests for the WebSocketSubscriber handlers."""
import json
import pytest
from tornado.web import Application
from tornado.websocket import websocket_connect
from tornadose.handlers import WebSocketSubscriber
import utilities
@pytest.fixture
def store():
return utilities.TestStore()
@pytest.fixture
def app():
return Application([
(r'/', WebSocketSubscriber, dict(store=store))
])
@pytest.mark.gen_test
def test_get_message(http_server, io_loop, base_url, store):
conn = yield websocket_connect('ws' + base_url.split('http')[1])
store.submit('test')
io_loop.call_later(0.01, store.publish)
msg = yield conn.read_message()
msg = json.loads(msg)
assert msg['data'] == 'test'
conn.close()
<commit_msg>Fix test case for WebSocketSubscriber
Switched to unittest-style testing (pytest is a bit too magical
especially with the pytest-tornado extension). I may change all
tests later to use unittest.<commit_after>
|
"""Tests for the WebSocketSubscriber handlers."""
import json
from tornado.ioloop import IOLoop
from tornado.web import Application
from tornado.websocket import websocket_connect
from tornado.testing import AsyncHTTPTestCase, gen_test
from tornadose.handlers import WebSocketSubscriber
import utilities
class WebSocketSubscriberTestCase(AsyncHTTPTestCase):
def setUp(self):
self.store = utilities.TestStore()
super(WebSocketSubscriberTestCase, self).setUp()
def get_app(self):
return Application([
(r'/', WebSocketSubscriber, dict(store=self.store))
])
@gen_test
def test_get_message(self):
url = self.get_url('/').replace("http://", "ws://")
conn = yield websocket_connect(url)
self.store.submit('test')
IOLoop.current().call_later(0.01, self.store.publish)
msg = yield conn.read_message()
msg = json.loads(msg)
self.assertEqual(msg['data'], 'test')
conn.close()
|
"""Tests for the WebSocketSubscriber handlers."""
import json
import pytest
from tornado.web import Application
from tornado.websocket import websocket_connect
from tornadose.handlers import WebSocketSubscriber
import utilities
@pytest.fixture
def store():
return utilities.TestStore()
@pytest.fixture
def app():
return Application([
(r'/', WebSocketSubscriber, dict(store=store))
])
@pytest.mark.gen_test
def test_get_message(http_server, io_loop, base_url, store):
conn = yield websocket_connect('ws' + base_url.split('http')[1])
store.submit('test')
io_loop.call_later(0.01, store.publish)
msg = yield conn.read_message()
msg = json.loads(msg)
assert msg['data'] == 'test'
conn.close()
Fix test case for WebSocketSubscriber
Switched to unittest-style testing (pytest is a bit too magical
especially with the pytest-tornado extension). I may change all
tests later to use unittest."""Tests for the WebSocketSubscriber handlers."""
import json
from tornado.ioloop import IOLoop
from tornado.web import Application
from tornado.websocket import websocket_connect
from tornado.testing import AsyncHTTPTestCase, gen_test
from tornadose.handlers import WebSocketSubscriber
import utilities
class WebSocketSubscriberTestCase(AsyncHTTPTestCase):
def setUp(self):
self.store = utilities.TestStore()
super(WebSocketSubscriberTestCase, self).setUp()
def get_app(self):
return Application([
(r'/', WebSocketSubscriber, dict(store=self.store))
])
@gen_test
def test_get_message(self):
url = self.get_url('/').replace("http://", "ws://")
conn = yield websocket_connect(url)
self.store.submit('test')
IOLoop.current().call_later(0.01, self.store.publish)
msg = yield conn.read_message()
msg = json.loads(msg)
self.assertEqual(msg['data'], 'test')
conn.close()
|
<commit_before>"""Tests for the WebSocketSubscriber handlers."""
import json
import pytest
from tornado.web import Application
from tornado.websocket import websocket_connect
from tornadose.handlers import WebSocketSubscriber
import utilities
@pytest.fixture
def store():
return utilities.TestStore()
@pytest.fixture
def app():
return Application([
(r'/', WebSocketSubscriber, dict(store=store))
])
@pytest.mark.gen_test
def test_get_message(http_server, io_loop, base_url, store):
conn = yield websocket_connect('ws' + base_url.split('http')[1])
store.submit('test')
io_loop.call_later(0.01, store.publish)
msg = yield conn.read_message()
msg = json.loads(msg)
assert msg['data'] == 'test'
conn.close()
<commit_msg>Fix test case for WebSocketSubscriber
Switched to unittest-style testing (pytest is a bit too magical
especially with the pytest-tornado extension). I may change all
tests later to use unittest.<commit_after>"""Tests for the WebSocketSubscriber handlers."""
import json
from tornado.ioloop import IOLoop
from tornado.web import Application
from tornado.websocket import websocket_connect
from tornado.testing import AsyncHTTPTestCase, gen_test
from tornadose.handlers import WebSocketSubscriber
import utilities
class WebSocketSubscriberTestCase(AsyncHTTPTestCase):
def setUp(self):
self.store = utilities.TestStore()
super(WebSocketSubscriberTestCase, self).setUp()
def get_app(self):
return Application([
(r'/', WebSocketSubscriber, dict(store=self.store))
])
@gen_test
def test_get_message(self):
url = self.get_url('/').replace("http://", "ws://")
conn = yield websocket_connect(url)
self.store.submit('test')
IOLoop.current().call_later(0.01, self.store.publish)
msg = yield conn.read_message()
msg = json.loads(msg)
self.assertEqual(msg['data'], 'test')
conn.close()
|
3d2d07294f7b891b7e716911475333c5e34d5c98
|
tests/unit/test_raw_generichash.py
|
tests/unit/test_raw_generichash.py
|
# Import nacl libs
import libnacl
# Import python libs
import unittest
class TestGenericHash(unittest.TestCase):
'''
Test sign functions
'''
def test_keyless_generichash(self):
msg1 = b'Are you suggesting coconuts migrate?'
msg2 = b'Not at all, they could be carried.'
chash1 = libnacl.crypto_generichash(msg1)
chash2 = libnacl.crypto_generichash(msg2)
self.assertNotEqual(msg1, chash1)
self.assertNotEqual(msg2, chash2)
self.assertNotEqual(chash2, chash1)
|
# Import nacl libs
import libnacl
# Import python libs
import unittest
class TestGenericHash(unittest.TestCase):
'''
Test sign functions
'''
def test_keyless_generichash(self):
msg1 = b'Are you suggesting coconuts migrate?'
msg2 = b'Not at all, they could be carried.'
chash1 = libnacl.crypto_generichash(msg1)
chash2 = libnacl.crypto_generichash(msg2)
self.assertNotEqual(msg1, chash1)
self.assertNotEqual(msg2, chash2)
self.assertNotEqual(chash2, chash1)
def test_key_generichash(self):
msg1 = b'Are you suggesting coconuts migrate?'
msg2 = b'Not at all, they could be carried.'
key1 = libnacl.utils.rand_nonce()
key2 = libnacl.utils.rand_nonce()
khash1_1 = libnacl.crypto_generichash(msg1, key1)
khash1_1_2 = libnacl.crypto_generichash(msg1, key1)
khash1_2 = libnacl.crypto_generichash(msg1, key2)
khash2_1 = libnacl.crypto_generichash(msg2, key1)
khash2_2 = libnacl.crypto_generichash(msg2, key2)
self.assertNotEqual(msg1, khash1_1)
self.assertNotEqual(msg1, khash1_2)
self.assertNotEqual(msg2, khash2_1)
self.assertNotEqual(msg2, khash2_2)
self.assertNotEqual(khash1_1, khash1_2)
self.assertNotEqual(khash2_1, khash2_2)
self.assertNotEqual(khash1_1, khash2_1)
self.assertNotEqual(khash1_2, khash2_2)
self.assertEqual(khash1_1, khash1_1_2)
|
Add tests for keyed hashes
|
Add tests for keyed hashes
|
Python
|
apache-2.0
|
mindw/libnacl,RaetProtocol/libnacl,cachedout/libnacl,johnttan/libnacl,coinkite/libnacl,saltstack/libnacl
|
# Import nacl libs
import libnacl
# Import python libs
import unittest
class TestGenericHash(unittest.TestCase):
'''
Test sign functions
'''
def test_keyless_generichash(self):
msg1 = b'Are you suggesting coconuts migrate?'
msg2 = b'Not at all, they could be carried.'
chash1 = libnacl.crypto_generichash(msg1)
chash2 = libnacl.crypto_generichash(msg2)
self.assertNotEqual(msg1, chash1)
self.assertNotEqual(msg2, chash2)
self.assertNotEqual(chash2, chash1)
Add tests for keyed hashes
|
# Import nacl libs
import libnacl
# Import python libs
import unittest
class TestGenericHash(unittest.TestCase):
'''
Test sign functions
'''
def test_keyless_generichash(self):
msg1 = b'Are you suggesting coconuts migrate?'
msg2 = b'Not at all, they could be carried.'
chash1 = libnacl.crypto_generichash(msg1)
chash2 = libnacl.crypto_generichash(msg2)
self.assertNotEqual(msg1, chash1)
self.assertNotEqual(msg2, chash2)
self.assertNotEqual(chash2, chash1)
def test_key_generichash(self):
msg1 = b'Are you suggesting coconuts migrate?'
msg2 = b'Not at all, they could be carried.'
key1 = libnacl.utils.rand_nonce()
key2 = libnacl.utils.rand_nonce()
khash1_1 = libnacl.crypto_generichash(msg1, key1)
khash1_1_2 = libnacl.crypto_generichash(msg1, key1)
khash1_2 = libnacl.crypto_generichash(msg1, key2)
khash2_1 = libnacl.crypto_generichash(msg2, key1)
khash2_2 = libnacl.crypto_generichash(msg2, key2)
self.assertNotEqual(msg1, khash1_1)
self.assertNotEqual(msg1, khash1_2)
self.assertNotEqual(msg2, khash2_1)
self.assertNotEqual(msg2, khash2_2)
self.assertNotEqual(khash1_1, khash1_2)
self.assertNotEqual(khash2_1, khash2_2)
self.assertNotEqual(khash1_1, khash2_1)
self.assertNotEqual(khash1_2, khash2_2)
self.assertEqual(khash1_1, khash1_1_2)
|
<commit_before># Import nacl libs
import libnacl
# Import python libs
import unittest
class TestGenericHash(unittest.TestCase):
'''
Test sign functions
'''
def test_keyless_generichash(self):
msg1 = b'Are you suggesting coconuts migrate?'
msg2 = b'Not at all, they could be carried.'
chash1 = libnacl.crypto_generichash(msg1)
chash2 = libnacl.crypto_generichash(msg2)
self.assertNotEqual(msg1, chash1)
self.assertNotEqual(msg2, chash2)
self.assertNotEqual(chash2, chash1)
<commit_msg>Add tests for keyed hashes<commit_after>
|
# Import nacl libs
import libnacl
# Import python libs
import unittest
class TestGenericHash(unittest.TestCase):
'''
Test sign functions
'''
def test_keyless_generichash(self):
msg1 = b'Are you suggesting coconuts migrate?'
msg2 = b'Not at all, they could be carried.'
chash1 = libnacl.crypto_generichash(msg1)
chash2 = libnacl.crypto_generichash(msg2)
self.assertNotEqual(msg1, chash1)
self.assertNotEqual(msg2, chash2)
self.assertNotEqual(chash2, chash1)
def test_key_generichash(self):
msg1 = b'Are you suggesting coconuts migrate?'
msg2 = b'Not at all, they could be carried.'
key1 = libnacl.utils.rand_nonce()
key2 = libnacl.utils.rand_nonce()
khash1_1 = libnacl.crypto_generichash(msg1, key1)
khash1_1_2 = libnacl.crypto_generichash(msg1, key1)
khash1_2 = libnacl.crypto_generichash(msg1, key2)
khash2_1 = libnacl.crypto_generichash(msg2, key1)
khash2_2 = libnacl.crypto_generichash(msg2, key2)
self.assertNotEqual(msg1, khash1_1)
self.assertNotEqual(msg1, khash1_2)
self.assertNotEqual(msg2, khash2_1)
self.assertNotEqual(msg2, khash2_2)
self.assertNotEqual(khash1_1, khash1_2)
self.assertNotEqual(khash2_1, khash2_2)
self.assertNotEqual(khash1_1, khash2_1)
self.assertNotEqual(khash1_2, khash2_2)
self.assertEqual(khash1_1, khash1_1_2)
|
# Import nacl libs
import libnacl
# Import python libs
import unittest
class TestGenericHash(unittest.TestCase):
'''
Test sign functions
'''
def test_keyless_generichash(self):
msg1 = b'Are you suggesting coconuts migrate?'
msg2 = b'Not at all, they could be carried.'
chash1 = libnacl.crypto_generichash(msg1)
chash2 = libnacl.crypto_generichash(msg2)
self.assertNotEqual(msg1, chash1)
self.assertNotEqual(msg2, chash2)
self.assertNotEqual(chash2, chash1)
Add tests for keyed hashes# Import nacl libs
import libnacl
# Import python libs
import unittest
class TestGenericHash(unittest.TestCase):
'''
Test sign functions
'''
def test_keyless_generichash(self):
msg1 = b'Are you suggesting coconuts migrate?'
msg2 = b'Not at all, they could be carried.'
chash1 = libnacl.crypto_generichash(msg1)
chash2 = libnacl.crypto_generichash(msg2)
self.assertNotEqual(msg1, chash1)
self.assertNotEqual(msg2, chash2)
self.assertNotEqual(chash2, chash1)
def test_key_generichash(self):
msg1 = b'Are you suggesting coconuts migrate?'
msg2 = b'Not at all, they could be carried.'
key1 = libnacl.utils.rand_nonce()
key2 = libnacl.utils.rand_nonce()
khash1_1 = libnacl.crypto_generichash(msg1, key1)
khash1_1_2 = libnacl.crypto_generichash(msg1, key1)
khash1_2 = libnacl.crypto_generichash(msg1, key2)
khash2_1 = libnacl.crypto_generichash(msg2, key1)
khash2_2 = libnacl.crypto_generichash(msg2, key2)
self.assertNotEqual(msg1, khash1_1)
self.assertNotEqual(msg1, khash1_2)
self.assertNotEqual(msg2, khash2_1)
self.assertNotEqual(msg2, khash2_2)
self.assertNotEqual(khash1_1, khash1_2)
self.assertNotEqual(khash2_1, khash2_2)
self.assertNotEqual(khash1_1, khash2_1)
self.assertNotEqual(khash1_2, khash2_2)
self.assertEqual(khash1_1, khash1_1_2)
|
<commit_before># Import nacl libs
import libnacl
# Import python libs
import unittest
class TestGenericHash(unittest.TestCase):
'''
Test sign functions
'''
def test_keyless_generichash(self):
msg1 = b'Are you suggesting coconuts migrate?'
msg2 = b'Not at all, they could be carried.'
chash1 = libnacl.crypto_generichash(msg1)
chash2 = libnacl.crypto_generichash(msg2)
self.assertNotEqual(msg1, chash1)
self.assertNotEqual(msg2, chash2)
self.assertNotEqual(chash2, chash1)
<commit_msg>Add tests for keyed hashes<commit_after># Import nacl libs
import libnacl
# Import python libs
import unittest
class TestGenericHash(unittest.TestCase):
'''
Test sign functions
'''
def test_keyless_generichash(self):
msg1 = b'Are you suggesting coconuts migrate?'
msg2 = b'Not at all, they could be carried.'
chash1 = libnacl.crypto_generichash(msg1)
chash2 = libnacl.crypto_generichash(msg2)
self.assertNotEqual(msg1, chash1)
self.assertNotEqual(msg2, chash2)
self.assertNotEqual(chash2, chash1)
def test_key_generichash(self):
msg1 = b'Are you suggesting coconuts migrate?'
msg2 = b'Not at all, they could be carried.'
key1 = libnacl.utils.rand_nonce()
key2 = libnacl.utils.rand_nonce()
khash1_1 = libnacl.crypto_generichash(msg1, key1)
khash1_1_2 = libnacl.crypto_generichash(msg1, key1)
khash1_2 = libnacl.crypto_generichash(msg1, key2)
khash2_1 = libnacl.crypto_generichash(msg2, key1)
khash2_2 = libnacl.crypto_generichash(msg2, key2)
self.assertNotEqual(msg1, khash1_1)
self.assertNotEqual(msg1, khash1_2)
self.assertNotEqual(msg2, khash2_1)
self.assertNotEqual(msg2, khash2_2)
self.assertNotEqual(khash1_1, khash1_2)
self.assertNotEqual(khash2_1, khash2_2)
self.assertNotEqual(khash1_1, khash2_1)
self.assertNotEqual(khash1_2, khash2_2)
self.assertEqual(khash1_1, khash1_1_2)
|
44609e0432855506cd977cd39f1a780dfbd9e366
|
tests/consoles_tests.py
|
tests/consoles_tests.py
|
import io
import spur
from nose.tools import istest, assert_equal
from toodlepip.consoles import Console
@istest
def console_writes_output_to_console():
console, output = _create_local_console()
console.run("Action", ["echo", "Go go go!"])
assert b"Go go go!" in output.getvalue()
def _create_local_console():
output = io.BytesIO()
shell = spur.LocalShell()
return Console(shell, output), output
|
import io
import spur
from nose.tools import istest, assert_equal
from toodlepip.consoles import Console
@istest
def console_writes_stdout_output_to_console():
console, output = _create_local_console()
console.run("Action", ["echo", "Go go go!"])
assert b"Go go go!" in output.getvalue()
@istest
def console_writes_stderr_output_to_console():
console, output = _create_local_console()
console.run("Action", ["sh", "-c", "echo 'Go go go!' 1>&2"])
assert b"Go go go!" in output.getvalue()
def _create_local_console():
output = io.BytesIO()
shell = spur.LocalShell()
return Console(shell, output), output
|
Add test for stderr output from console
|
Add test for stderr output from console
|
Python
|
bsd-2-clause
|
mwilliamson/toodlepip
|
import io
import spur
from nose.tools import istest, assert_equal
from toodlepip.consoles import Console
@istest
def console_writes_output_to_console():
console, output = _create_local_console()
console.run("Action", ["echo", "Go go go!"])
assert b"Go go go!" in output.getvalue()
def _create_local_console():
output = io.BytesIO()
shell = spur.LocalShell()
return Console(shell, output), output
Add test for stderr output from console
|
import io
import spur
from nose.tools import istest, assert_equal
from toodlepip.consoles import Console
@istest
def console_writes_stdout_output_to_console():
console, output = _create_local_console()
console.run("Action", ["echo", "Go go go!"])
assert b"Go go go!" in output.getvalue()
@istest
def console_writes_stderr_output_to_console():
console, output = _create_local_console()
console.run("Action", ["sh", "-c", "echo 'Go go go!' 1>&2"])
assert b"Go go go!" in output.getvalue()
def _create_local_console():
output = io.BytesIO()
shell = spur.LocalShell()
return Console(shell, output), output
|
<commit_before>import io
import spur
from nose.tools import istest, assert_equal
from toodlepip.consoles import Console
@istest
def console_writes_output_to_console():
console, output = _create_local_console()
console.run("Action", ["echo", "Go go go!"])
assert b"Go go go!" in output.getvalue()
def _create_local_console():
output = io.BytesIO()
shell = spur.LocalShell()
return Console(shell, output), output
<commit_msg>Add test for stderr output from console<commit_after>
|
import io
import spur
from nose.tools import istest, assert_equal
from toodlepip.consoles import Console
@istest
def console_writes_stdout_output_to_console():
console, output = _create_local_console()
console.run("Action", ["echo", "Go go go!"])
assert b"Go go go!" in output.getvalue()
@istest
def console_writes_stderr_output_to_console():
console, output = _create_local_console()
console.run("Action", ["sh", "-c", "echo 'Go go go!' 1>&2"])
assert b"Go go go!" in output.getvalue()
def _create_local_console():
output = io.BytesIO()
shell = spur.LocalShell()
return Console(shell, output), output
|
import io
import spur
from nose.tools import istest, assert_equal
from toodlepip.consoles import Console
@istest
def console_writes_output_to_console():
console, output = _create_local_console()
console.run("Action", ["echo", "Go go go!"])
assert b"Go go go!" in output.getvalue()
def _create_local_console():
output = io.BytesIO()
shell = spur.LocalShell()
return Console(shell, output), output
Add test for stderr output from consoleimport io
import spur
from nose.tools import istest, assert_equal
from toodlepip.consoles import Console
@istest
def console_writes_stdout_output_to_console():
console, output = _create_local_console()
console.run("Action", ["echo", "Go go go!"])
assert b"Go go go!" in output.getvalue()
@istest
def console_writes_stderr_output_to_console():
console, output = _create_local_console()
console.run("Action", ["sh", "-c", "echo 'Go go go!' 1>&2"])
assert b"Go go go!" in output.getvalue()
def _create_local_console():
output = io.BytesIO()
shell = spur.LocalShell()
return Console(shell, output), output
|
<commit_before>import io
import spur
from nose.tools import istest, assert_equal
from toodlepip.consoles import Console
@istest
def console_writes_output_to_console():
console, output = _create_local_console()
console.run("Action", ["echo", "Go go go!"])
assert b"Go go go!" in output.getvalue()
def _create_local_console():
output = io.BytesIO()
shell = spur.LocalShell()
return Console(shell, output), output
<commit_msg>Add test for stderr output from console<commit_after>import io
import spur
from nose.tools import istest, assert_equal
from toodlepip.consoles import Console
@istest
def console_writes_stdout_output_to_console():
console, output = _create_local_console()
console.run("Action", ["echo", "Go go go!"])
assert b"Go go go!" in output.getvalue()
@istest
def console_writes_stderr_output_to_console():
console, output = _create_local_console()
console.run("Action", ["sh", "-c", "echo 'Go go go!' 1>&2"])
assert b"Go go go!" in output.getvalue()
def _create_local_console():
output = io.BytesIO()
shell = spur.LocalShell()
return Console(shell, output), output
|
2f9e058b4ef79f6eecb0292642c85a9e3e2376b0
|
examples/pipes-repl.py
|
examples/pipes-repl.py
|
'''
Sample REPL code to integrate with Diesel
Using InteractiveInterpreter broke block handling (if/def/etc.), but exceptions
were handled well and the return value of code was printed.
Using exec runs the input in the current context, but exception handling and other
features of InteractiveInterpreter are lost.
'''
import sys
import code
from diesel import Application, Pipe, until
DEFAULT_PROMPT = '>>> '
def readcb():
from diesel.app import current_app
print 'Diesel Console'
cmd = ''
prompt = DEFAULT_PROMPT
while 1:
sys.stdout.write(prompt)
sys.stdout.flush()
input = yield until("\n")
cmd += input
if input.lstrip() == input or input == "\n":
try:
ret = code.compile_command(input)
except SyntaxError, e:
# TODO Pretty print traceback
print e
# Reset repl
cmd = ''
prompt = DEFAULT_PROMPT
else:
if ret:
#interp.runcode(ret)
exec cmd
cmd = ''
prompt = DEFAULT_PROMPT
else:
# Start of a block
prompt = '... '
else:
# Continued block
prompt = '... '
a = Application()
a.add_loop(Pipe(sys.stdin, readcb))
a.run()
|
import sys
import code
import traceback
from diesel import Application, Pipe, until
QUIT_STR = "quit()\n"
DEFAULT_PROMPT = '>>> '
def diesel_repl():
'''Simple REPL for use inside a diesel app'''
# Import current_app into locals for use in REPL
from diesel.app import current_app
print 'Diesel Console'
print 'Type %r to exit REPL' % QUIT_STR
run = True
cmd = ''
prompt = DEFAULT_PROMPT
while 1:
# Infinite REPL
sys.stdout.write(prompt)
sys.stdout.flush()
input = yield until("\n")
if input == QUIT_STR:
break
cmd += input
if input.lstrip() == input or input == "\n":
try:
ret = code.compile_command(cmd)
except (OverflowError, SyntaxError, ValueError):
print traceback.format_exc().rstrip()
# Reset repl
cmd = ''
prompt = DEFAULT_PROMPT
else:
if ret:
try:
out = eval(ret)
except:
print traceback.format_exc().rstrip()
else:
if out is not None:
print "%r" % out
cmd = ''
prompt = DEFAULT_PROMPT
else:
# Start of a block
prompt = '... '
else:
# Continued block
prompt = '... '
a = Application()
a.add_loop(Pipe(sys.stdin, diesel_repl))
a.run()
|
Fix REPL and add quit() command
|
Fix REPL and add quit() command
|
Python
|
bsd-3-clause
|
dieseldev/diesel
|
'''
Sample REPL code to integrate with Diesel
Using InteractiveInterpreter broke block handling (if/def/etc.), but exceptions
were handled well and the return value of code was printed.
Using exec runs the input in the current context, but exception handling and other
features of InteractiveInterpreter are lost.
'''
import sys
import code
from diesel import Application, Pipe, until
DEFAULT_PROMPT = '>>> '
def readcb():
from diesel.app import current_app
print 'Diesel Console'
cmd = ''
prompt = DEFAULT_PROMPT
while 1:
sys.stdout.write(prompt)
sys.stdout.flush()
input = yield until("\n")
cmd += input
if input.lstrip() == input or input == "\n":
try:
ret = code.compile_command(input)
except SyntaxError, e:
# TODO Pretty print traceback
print e
# Reset repl
cmd = ''
prompt = DEFAULT_PROMPT
else:
if ret:
#interp.runcode(ret)
exec cmd
cmd = ''
prompt = DEFAULT_PROMPT
else:
# Start of a block
prompt = '... '
else:
# Continued block
prompt = '... '
a = Application()
a.add_loop(Pipe(sys.stdin, readcb))
a.run()
Fix REPL and add quit() command
|
import sys
import code
import traceback
from diesel import Application, Pipe, until
QUIT_STR = "quit()\n"
DEFAULT_PROMPT = '>>> '
def diesel_repl():
'''Simple REPL for use inside a diesel app'''
# Import current_app into locals for use in REPL
from diesel.app import current_app
print 'Diesel Console'
print 'Type %r to exit REPL' % QUIT_STR
run = True
cmd = ''
prompt = DEFAULT_PROMPT
while 1:
# Infinite REPL
sys.stdout.write(prompt)
sys.stdout.flush()
input = yield until("\n")
if input == QUIT_STR:
break
cmd += input
if input.lstrip() == input or input == "\n":
try:
ret = code.compile_command(cmd)
except (OverflowError, SyntaxError, ValueError):
print traceback.format_exc().rstrip()
# Reset repl
cmd = ''
prompt = DEFAULT_PROMPT
else:
if ret:
try:
out = eval(ret)
except:
print traceback.format_exc().rstrip()
else:
if out is not None:
print "%r" % out
cmd = ''
prompt = DEFAULT_PROMPT
else:
# Start of a block
prompt = '... '
else:
# Continued block
prompt = '... '
a = Application()
a.add_loop(Pipe(sys.stdin, diesel_repl))
a.run()
|
<commit_before>'''
Sample REPL code to integrate with Diesel
Using InteractiveInterpreter broke block handling (if/def/etc.), but exceptions
were handled well and the return value of code was printed.
Using exec runs the input in the current context, but exception handling and other
features of InteractiveInterpreter are lost.
'''
import sys
import code
from diesel import Application, Pipe, until
DEFAULT_PROMPT = '>>> '
def readcb():
from diesel.app import current_app
print 'Diesel Console'
cmd = ''
prompt = DEFAULT_PROMPT
while 1:
sys.stdout.write(prompt)
sys.stdout.flush()
input = yield until("\n")
cmd += input
if input.lstrip() == input or input == "\n":
try:
ret = code.compile_command(input)
except SyntaxError, e:
# TODO Pretty print traceback
print e
# Reset repl
cmd = ''
prompt = DEFAULT_PROMPT
else:
if ret:
#interp.runcode(ret)
exec cmd
cmd = ''
prompt = DEFAULT_PROMPT
else:
# Start of a block
prompt = '... '
else:
# Continued block
prompt = '... '
a = Application()
a.add_loop(Pipe(sys.stdin, readcb))
a.run()
<commit_msg>Fix REPL and add quit() command<commit_after>
|
import sys
import code
import traceback
from diesel import Application, Pipe, until
QUIT_STR = "quit()\n"
DEFAULT_PROMPT = '>>> '
def diesel_repl():
'''Simple REPL for use inside a diesel app'''
# Import current_app into locals for use in REPL
from diesel.app import current_app
print 'Diesel Console'
print 'Type %r to exit REPL' % QUIT_STR
run = True
cmd = ''
prompt = DEFAULT_PROMPT
while 1:
# Infinite REPL
sys.stdout.write(prompt)
sys.stdout.flush()
input = yield until("\n")
if input == QUIT_STR:
break
cmd += input
if input.lstrip() == input or input == "\n":
try:
ret = code.compile_command(cmd)
except (OverflowError, SyntaxError, ValueError):
print traceback.format_exc().rstrip()
# Reset repl
cmd = ''
prompt = DEFAULT_PROMPT
else:
if ret:
try:
out = eval(ret)
except:
print traceback.format_exc().rstrip()
else:
if out is not None:
print "%r" % out
cmd = ''
prompt = DEFAULT_PROMPT
else:
# Start of a block
prompt = '... '
else:
# Continued block
prompt = '... '
a = Application()
a.add_loop(Pipe(sys.stdin, diesel_repl))
a.run()
|
'''
Sample REPL code to integrate with Diesel
Using InteractiveInterpreter broke block handling (if/def/etc.), but exceptions
were handled well and the return value of code was printed.
Using exec runs the input in the current context, but exception handling and other
features of InteractiveInterpreter are lost.
'''
import sys
import code
from diesel import Application, Pipe, until
DEFAULT_PROMPT = '>>> '
def readcb():
from diesel.app import current_app
print 'Diesel Console'
cmd = ''
prompt = DEFAULT_PROMPT
while 1:
sys.stdout.write(prompt)
sys.stdout.flush()
input = yield until("\n")
cmd += input
if input.lstrip() == input or input == "\n":
try:
ret = code.compile_command(input)
except SyntaxError, e:
# TODO Pretty print traceback
print e
# Reset repl
cmd = ''
prompt = DEFAULT_PROMPT
else:
if ret:
#interp.runcode(ret)
exec cmd
cmd = ''
prompt = DEFAULT_PROMPT
else:
# Start of a block
prompt = '... '
else:
# Continued block
prompt = '... '
a = Application()
a.add_loop(Pipe(sys.stdin, readcb))
a.run()
Fix REPL and add quit() commandimport sys
import code
import traceback
from diesel import Application, Pipe, until
QUIT_STR = "quit()\n"
DEFAULT_PROMPT = '>>> '
def diesel_repl():
'''Simple REPL for use inside a diesel app'''
# Import current_app into locals for use in REPL
from diesel.app import current_app
print 'Diesel Console'
print 'Type %r to exit REPL' % QUIT_STR
run = True
cmd = ''
prompt = DEFAULT_PROMPT
while 1:
# Infinite REPL
sys.stdout.write(prompt)
sys.stdout.flush()
input = yield until("\n")
if input == QUIT_STR:
break
cmd += input
if input.lstrip() == input or input == "\n":
try:
ret = code.compile_command(cmd)
except (OverflowError, SyntaxError, ValueError):
print traceback.format_exc().rstrip()
# Reset repl
cmd = ''
prompt = DEFAULT_PROMPT
else:
if ret:
try:
out = eval(ret)
except:
print traceback.format_exc().rstrip()
else:
if out is not None:
print "%r" % out
cmd = ''
prompt = DEFAULT_PROMPT
else:
# Start of a block
prompt = '... '
else:
# Continued block
prompt = '... '
a = Application()
a.add_loop(Pipe(sys.stdin, diesel_repl))
a.run()
|
<commit_before>'''
Sample REPL code to integrate with Diesel
Using InteractiveInterpreter broke block handling (if/def/etc.), but exceptions
were handled well and the return value of code was printed.
Using exec runs the input in the current context, but exception handling and other
features of InteractiveInterpreter are lost.
'''
import sys
import code
from diesel import Application, Pipe, until
DEFAULT_PROMPT = '>>> '
def readcb():
from diesel.app import current_app
print 'Diesel Console'
cmd = ''
prompt = DEFAULT_PROMPT
while 1:
sys.stdout.write(prompt)
sys.stdout.flush()
input = yield until("\n")
cmd += input
if input.lstrip() == input or input == "\n":
try:
ret = code.compile_command(input)
except SyntaxError, e:
# TODO Pretty print traceback
print e
# Reset repl
cmd = ''
prompt = DEFAULT_PROMPT
else:
if ret:
#interp.runcode(ret)
exec cmd
cmd = ''
prompt = DEFAULT_PROMPT
else:
# Start of a block
prompt = '... '
else:
# Continued block
prompt = '... '
a = Application()
a.add_loop(Pipe(sys.stdin, readcb))
a.run()
<commit_msg>Fix REPL and add quit() command<commit_after>import sys
import code
import traceback
from diesel import Application, Pipe, until
QUIT_STR = "quit()\n"
DEFAULT_PROMPT = '>>> '
def diesel_repl():
'''Simple REPL for use inside a diesel app'''
# Import current_app into locals for use in REPL
from diesel.app import current_app
print 'Diesel Console'
print 'Type %r to exit REPL' % QUIT_STR
run = True
cmd = ''
prompt = DEFAULT_PROMPT
while 1:
# Infinite REPL
sys.stdout.write(prompt)
sys.stdout.flush()
input = yield until("\n")
if input == QUIT_STR:
break
cmd += input
if input.lstrip() == input or input == "\n":
try:
ret = code.compile_command(cmd)
except (OverflowError, SyntaxError, ValueError):
print traceback.format_exc().rstrip()
# Reset repl
cmd = ''
prompt = DEFAULT_PROMPT
else:
if ret:
try:
out = eval(ret)
except:
print traceback.format_exc().rstrip()
else:
if out is not None:
print "%r" % out
cmd = ''
prompt = DEFAULT_PROMPT
else:
# Start of a block
prompt = '... '
else:
# Continued block
prompt = '... '
a = Application()
a.add_loop(Pipe(sys.stdin, diesel_repl))
a.run()
|
a6e1d44039d95f9f3f6ab6c53ffa28c50f3f9af6
|
bp/bp.py
|
bp/bp.py
|
# Python 3.6.1
def get_input():
with open('input.txt', 'r') as f:
return f.read().split()
def main():
input = get_input()
# Code here
if __name__ == '__main__':
import time
start = time.perf_counter()
main()
print(time.perf_counter() - start)
|
# Python 3.8.3
def get_input():
with open('input.txt', 'r') as f:
return f.read().split()
def main():
input = get_input()
# Code here
if __name__ == '__main__':
import time
start = time.perf_counter()
main()
print(time.perf_counter() - start)
|
Update Python version in template
|
Update Python version in template
I completely forgot about those templates too. I don't even remember
what "bp" was supposed to stand for.
|
Python
|
mit
|
foxscotch/advent-of-code,foxscotch/advent-of-code
|
# Python 3.6.1
def get_input():
with open('input.txt', 'r') as f:
return f.read().split()
def main():
input = get_input()
# Code here
if __name__ == '__main__':
import time
start = time.perf_counter()
main()
print(time.perf_counter() - start)
Update Python version in template
I completely forgot about those templates too. I don't even remember
what "bp" was supposed to stand for.
|
# Python 3.8.3
def get_input():
with open('input.txt', 'r') as f:
return f.read().split()
def main():
input = get_input()
# Code here
if __name__ == '__main__':
import time
start = time.perf_counter()
main()
print(time.perf_counter() - start)
|
<commit_before># Python 3.6.1
def get_input():
with open('input.txt', 'r') as f:
return f.read().split()
def main():
input = get_input()
# Code here
if __name__ == '__main__':
import time
start = time.perf_counter()
main()
print(time.perf_counter() - start)
<commit_msg>Update Python version in template
I completely forgot about those templates too. I don't even remember
what "bp" was supposed to stand for.<commit_after>
|
# Python 3.8.3
def get_input():
with open('input.txt', 'r') as f:
return f.read().split()
def main():
input = get_input()
# Code here
if __name__ == '__main__':
import time
start = time.perf_counter()
main()
print(time.perf_counter() - start)
|
# Python 3.6.1
def get_input():
with open('input.txt', 'r') as f:
return f.read().split()
def main():
input = get_input()
# Code here
if __name__ == '__main__':
import time
start = time.perf_counter()
main()
print(time.perf_counter() - start)
Update Python version in template
I completely forgot about those templates too. I don't even remember
what "bp" was supposed to stand for.# Python 3.8.3
def get_input():
with open('input.txt', 'r') as f:
return f.read().split()
def main():
input = get_input()
# Code here
if __name__ == '__main__':
import time
start = time.perf_counter()
main()
print(time.perf_counter() - start)
|
<commit_before># Python 3.6.1
def get_input():
with open('input.txt', 'r') as f:
return f.read().split()
def main():
input = get_input()
# Code here
if __name__ == '__main__':
import time
start = time.perf_counter()
main()
print(time.perf_counter() - start)
<commit_msg>Update Python version in template
I completely forgot about those templates too. I don't even remember
what "bp" was supposed to stand for.<commit_after># Python 3.8.3
def get_input():
with open('input.txt', 'r') as f:
return f.read().split()
def main():
input = get_input()
# Code here
if __name__ == '__main__':
import time
start = time.perf_counter()
main()
print(time.perf_counter() - start)
|
85123f01f1e63b4fc7688e13104ee59c6efb263a
|
proscli/main.py
|
proscli/main.py
|
import click
import proscli
from proscli.utils import default_options
def main():
# the program name should always be pros. don't care if it's not...
try:
cli.main(prog_name='pros')
except KeyboardInterrupt:
click.echo('Aborted!')
pass
import prosconductor.providers.utils
@proscli.flasher_cli.command('help', short_help='Show this message and exit.')
@click.argument('ignore', nargs=-1, expose_value=False)
@default_options
@click.pass_context
def help_cmd(ctx):
click.echo(prosconductor.providers.utils.get_all_available_templates())
@click.command('pros',
cls=click.CommandCollection,
context_settings=dict(help_option_names=['-h', '--help']),
sources=[proscli.terminal_cli, proscli.build_cli, proscli.flasher_cli, proscli.conductor_cli])
@click.version_option(version='2.1.923', prog_name='pros')
@default_options
def cli():
pass
if __name__ == '__main__':
main()
|
import click
import proscli
from proscli.utils import default_options
def main():
# the program name should always be pros. don't care if it's not...
try:
cli.main(prog_name='pros')
except KeyboardInterrupt:
click.echo('Aborted!')
pass
@click.command('pros',
cls=click.CommandCollection,
context_settings=dict(help_option_names=['-h', '--help']),
sources=[proscli.terminal_cli, proscli.build_cli, proscli.flasher_cli, proscli.conductor_cli])
@click.version_option(version='2.1.925', prog_name='pros')
@default_options
def cli():
pass
if __name__ == '__main__':
main()
|
Remove deprecated and broken pros help option
|
Remove deprecated and broken pros help option
|
Python
|
mpl-2.0
|
purduesigbots/pros-cli,purduesigbots/purdueros-cli
|
import click
import proscli
from proscli.utils import default_options
def main():
# the program name should always be pros. don't care if it's not...
try:
cli.main(prog_name='pros')
except KeyboardInterrupt:
click.echo('Aborted!')
pass
import prosconductor.providers.utils
@proscli.flasher_cli.command('help', short_help='Show this message and exit.')
@click.argument('ignore', nargs=-1, expose_value=False)
@default_options
@click.pass_context
def help_cmd(ctx):
click.echo(prosconductor.providers.utils.get_all_available_templates())
@click.command('pros',
cls=click.CommandCollection,
context_settings=dict(help_option_names=['-h', '--help']),
sources=[proscli.terminal_cli, proscli.build_cli, proscli.flasher_cli, proscli.conductor_cli])
@click.version_option(version='2.1.923', prog_name='pros')
@default_options
def cli():
pass
if __name__ == '__main__':
main()
Remove deprecated and broken pros help option
|
import click
import proscli
from proscli.utils import default_options
def main():
# the program name should always be pros. don't care if it's not...
try:
cli.main(prog_name='pros')
except KeyboardInterrupt:
click.echo('Aborted!')
pass
@click.command('pros',
cls=click.CommandCollection,
context_settings=dict(help_option_names=['-h', '--help']),
sources=[proscli.terminal_cli, proscli.build_cli, proscli.flasher_cli, proscli.conductor_cli])
@click.version_option(version='2.1.925', prog_name='pros')
@default_options
def cli():
pass
if __name__ == '__main__':
main()
|
<commit_before>import click
import proscli
from proscli.utils import default_options
def main():
# the program name should always be pros. don't care if it's not...
try:
cli.main(prog_name='pros')
except KeyboardInterrupt:
click.echo('Aborted!')
pass
import prosconductor.providers.utils
@proscli.flasher_cli.command('help', short_help='Show this message and exit.')
@click.argument('ignore', nargs=-1, expose_value=False)
@default_options
@click.pass_context
def help_cmd(ctx):
click.echo(prosconductor.providers.utils.get_all_available_templates())
@click.command('pros',
cls=click.CommandCollection,
context_settings=dict(help_option_names=['-h', '--help']),
sources=[proscli.terminal_cli, proscli.build_cli, proscli.flasher_cli, proscli.conductor_cli])
@click.version_option(version='2.1.923', prog_name='pros')
@default_options
def cli():
pass
if __name__ == '__main__':
main()
<commit_msg>Remove deprecated and broken pros help option<commit_after>
|
import click
import proscli
from proscli.utils import default_options
def main():
# the program name should always be pros. don't care if it's not...
try:
cli.main(prog_name='pros')
except KeyboardInterrupt:
click.echo('Aborted!')
pass
@click.command('pros',
cls=click.CommandCollection,
context_settings=dict(help_option_names=['-h', '--help']),
sources=[proscli.terminal_cli, proscli.build_cli, proscli.flasher_cli, proscli.conductor_cli])
@click.version_option(version='2.1.925', prog_name='pros')
@default_options
def cli():
pass
if __name__ == '__main__':
main()
|
import click
import proscli
from proscli.utils import default_options
def main():
# the program name should always be pros. don't care if it's not...
try:
cli.main(prog_name='pros')
except KeyboardInterrupt:
click.echo('Aborted!')
pass
import prosconductor.providers.utils
@proscli.flasher_cli.command('help', short_help='Show this message and exit.')
@click.argument('ignore', nargs=-1, expose_value=False)
@default_options
@click.pass_context
def help_cmd(ctx):
click.echo(prosconductor.providers.utils.get_all_available_templates())
@click.command('pros',
cls=click.CommandCollection,
context_settings=dict(help_option_names=['-h', '--help']),
sources=[proscli.terminal_cli, proscli.build_cli, proscli.flasher_cli, proscli.conductor_cli])
@click.version_option(version='2.1.923', prog_name='pros')
@default_options
def cli():
pass
if __name__ == '__main__':
main()
Remove deprecated and broken pros help optionimport click
import proscli
from proscli.utils import default_options
def main():
# the program name should always be pros. don't care if it's not...
try:
cli.main(prog_name='pros')
except KeyboardInterrupt:
click.echo('Aborted!')
pass
@click.command('pros',
cls=click.CommandCollection,
context_settings=dict(help_option_names=['-h', '--help']),
sources=[proscli.terminal_cli, proscli.build_cli, proscli.flasher_cli, proscli.conductor_cli])
@click.version_option(version='2.1.925', prog_name='pros')
@default_options
def cli():
pass
if __name__ == '__main__':
main()
|
<commit_before>import click
import proscli
from proscli.utils import default_options
def main():
# the program name should always be pros. don't care if it's not...
try:
cli.main(prog_name='pros')
except KeyboardInterrupt:
click.echo('Aborted!')
pass
import prosconductor.providers.utils
@proscli.flasher_cli.command('help', short_help='Show this message and exit.')
@click.argument('ignore', nargs=-1, expose_value=False)
@default_options
@click.pass_context
def help_cmd(ctx):
click.echo(prosconductor.providers.utils.get_all_available_templates())
@click.command('pros',
cls=click.CommandCollection,
context_settings=dict(help_option_names=['-h', '--help']),
sources=[proscli.terminal_cli, proscli.build_cli, proscli.flasher_cli, proscli.conductor_cli])
@click.version_option(version='2.1.923', prog_name='pros')
@default_options
def cli():
pass
if __name__ == '__main__':
main()
<commit_msg>Remove deprecated and broken pros help option<commit_after>import click
import proscli
from proscli.utils import default_options
def main():
# the program name should always be pros. don't care if it's not...
try:
cli.main(prog_name='pros')
except KeyboardInterrupt:
click.echo('Aborted!')
pass
@click.command('pros',
cls=click.CommandCollection,
context_settings=dict(help_option_names=['-h', '--help']),
sources=[proscli.terminal_cli, proscli.build_cli, proscli.flasher_cli, proscli.conductor_cli])
@click.version_option(version='2.1.925', prog_name='pros')
@default_options
def cli():
pass
if __name__ == '__main__':
main()
|
ecd3f6df837f38bf78940308088d0760272a0c18
|
server/world.py
|
server/world.py
|
import logging
from tile import Tile
from mech import Mech, Enemy, Player
class World(object):
def __init__(self, game):
print(game.state)
self.generate_tiles(game.state)
self.generate_mechs(game.state)
def generate_tiles(self, state):
""" Generate a tileset from the game state. """
logging.debug('Generating tiles...')
map = state.map
rows = map.split()
height = len(rows)
width = len(rows[0])
self.tiles = [[None for _ in range(height)] for _ in range(width)]
for y, row in enumerate(rows):
for x, char in enumerate(row):
self.tiles[x][y] = Tile(char, x, y)
def generate_mechs(self, state):
""" Generate enemy mechs from the game state. """
self.mechs = []
logging.debug('Generating enemy mechs...')
for name, player in state.players.items():
print(name, player, state)
is_current_player = False # TODO: Determine current player from state?
if is_current_player:
self.player = Player(player.name, player.pos, player.health, player.score, player.ammo)
else:
self.mechs.append(Enemy(player.name, player.pos, player.health, player.score, player.ammo))
|
import logging
from tile import Tile
from mech import Mech, Enemy, Player
class World(object):
def __init__(self, game):
print(game.state)
self.generate_tiles(game.state)
self.generate_mechs(game)
def generate_tiles(self, state):
""" Generate a tileset from the game state. """
logging.debug('Generating tiles...')
map = state.map
rows = map.split()
height = len(rows)
width = len(rows[0])
self.tiles = [[None for _ in range(height)] for _ in range(width)]
for y, row in enumerate(rows):
for x, char in enumerate(row):
self.tiles[x][y] = Tile(char, x, y)
def generate_mechs(self, game):
""" Generate enemy mechs from the game state. """
self.mechs = []
logging.debug('Generating enemy mechs...')
for name, player in game.state.players.items():
print(name, player, game.state.json)
if game.queue.is_turn(name):
self.player = Player(player.name, player.pos, player.health, player.score, player.ammo)
else:
self.mechs.append(Enemy(player.name, player.pos, player.health, player.score, player.ammo))
|
Use game.queue.is_turn(name) to build player or enemies
|
Use game.queue.is_turn(name) to build player or enemies
|
Python
|
mit
|
supermitch/mech-ai,supermitch/mech-ai,supermitch/mech-ai
|
import logging
from tile import Tile
from mech import Mech, Enemy, Player
class World(object):
def __init__(self, game):
print(game.state)
self.generate_tiles(game.state)
self.generate_mechs(game.state)
def generate_tiles(self, state):
""" Generate a tileset from the game state. """
logging.debug('Generating tiles...')
map = state.map
rows = map.split()
height = len(rows)
width = len(rows[0])
self.tiles = [[None for _ in range(height)] for _ in range(width)]
for y, row in enumerate(rows):
for x, char in enumerate(row):
self.tiles[x][y] = Tile(char, x, y)
def generate_mechs(self, state):
""" Generate enemy mechs from the game state. """
self.mechs = []
logging.debug('Generating enemy mechs...')
for name, player in state.players.items():
print(name, player, state)
is_current_player = False # TODO: Determine current player from state?
if is_current_player:
self.player = Player(player.name, player.pos, player.health, player.score, player.ammo)
else:
self.mechs.append(Enemy(player.name, player.pos, player.health, player.score, player.ammo))
Use game.queue.is_turn(name) to build player or enemies
|
import logging
from tile import Tile
from mech import Mech, Enemy, Player
class World(object):
def __init__(self, game):
print(game.state)
self.generate_tiles(game.state)
self.generate_mechs(game)
def generate_tiles(self, state):
""" Generate a tileset from the game state. """
logging.debug('Generating tiles...')
map = state.map
rows = map.split()
height = len(rows)
width = len(rows[0])
self.tiles = [[None for _ in range(height)] for _ in range(width)]
for y, row in enumerate(rows):
for x, char in enumerate(row):
self.tiles[x][y] = Tile(char, x, y)
def generate_mechs(self, game):
""" Generate enemy mechs from the game state. """
self.mechs = []
logging.debug('Generating enemy mechs...')
for name, player in game.state.players.items():
print(name, player, game.state.json)
if game.queue.is_turn(name):
self.player = Player(player.name, player.pos, player.health, player.score, player.ammo)
else:
self.mechs.append(Enemy(player.name, player.pos, player.health, player.score, player.ammo))
|
<commit_before>import logging
from tile import Tile
from mech import Mech, Enemy, Player
class World(object):
def __init__(self, game):
print(game.state)
self.generate_tiles(game.state)
self.generate_mechs(game.state)
def generate_tiles(self, state):
""" Generate a tileset from the game state. """
logging.debug('Generating tiles...')
map = state.map
rows = map.split()
height = len(rows)
width = len(rows[0])
self.tiles = [[None for _ in range(height)] for _ in range(width)]
for y, row in enumerate(rows):
for x, char in enumerate(row):
self.tiles[x][y] = Tile(char, x, y)
def generate_mechs(self, state):
""" Generate enemy mechs from the game state. """
self.mechs = []
logging.debug('Generating enemy mechs...')
for name, player in state.players.items():
print(name, player, state)
is_current_player = False # TODO: Determine current player from state?
if is_current_player:
self.player = Player(player.name, player.pos, player.health, player.score, player.ammo)
else:
self.mechs.append(Enemy(player.name, player.pos, player.health, player.score, player.ammo))
<commit_msg>Use game.queue.is_turn(name) to build player or enemies<commit_after>
|
import logging
from tile import Tile
from mech import Mech, Enemy, Player
class World(object):
def __init__(self, game):
print(game.state)
self.generate_tiles(game.state)
self.generate_mechs(game)
def generate_tiles(self, state):
""" Generate a tileset from the game state. """
logging.debug('Generating tiles...')
map = state.map
rows = map.split()
height = len(rows)
width = len(rows[0])
self.tiles = [[None for _ in range(height)] for _ in range(width)]
for y, row in enumerate(rows):
for x, char in enumerate(row):
self.tiles[x][y] = Tile(char, x, y)
def generate_mechs(self, game):
""" Generate enemy mechs from the game state. """
self.mechs = []
logging.debug('Generating enemy mechs...')
for name, player in game.state.players.items():
print(name, player, game.state.json)
if game.queue.is_turn(name):
self.player = Player(player.name, player.pos, player.health, player.score, player.ammo)
else:
self.mechs.append(Enemy(player.name, player.pos, player.health, player.score, player.ammo))
|
import logging
from tile import Tile
from mech import Mech, Enemy, Player
class World(object):
def __init__(self, game):
print(game.state)
self.generate_tiles(game.state)
self.generate_mechs(game.state)
def generate_tiles(self, state):
""" Generate a tileset from the game state. """
logging.debug('Generating tiles...')
map = state.map
rows = map.split()
height = len(rows)
width = len(rows[0])
self.tiles = [[None for _ in range(height)] for _ in range(width)]
for y, row in enumerate(rows):
for x, char in enumerate(row):
self.tiles[x][y] = Tile(char, x, y)
def generate_mechs(self, state):
""" Generate enemy mechs from the game state. """
self.mechs = []
logging.debug('Generating enemy mechs...')
for name, player in state.players.items():
print(name, player, state)
is_current_player = False # TODO: Determine current player from state?
if is_current_player:
self.player = Player(player.name, player.pos, player.health, player.score, player.ammo)
else:
self.mechs.append(Enemy(player.name, player.pos, player.health, player.score, player.ammo))
Use game.queue.is_turn(name) to build player or enemiesimport logging
from tile import Tile
from mech import Mech, Enemy, Player
class World(object):
def __init__(self, game):
print(game.state)
self.generate_tiles(game.state)
self.generate_mechs(game)
def generate_tiles(self, state):
""" Generate a tileset from the game state. """
logging.debug('Generating tiles...')
map = state.map
rows = map.split()
height = len(rows)
width = len(rows[0])
self.tiles = [[None for _ in range(height)] for _ in range(width)]
for y, row in enumerate(rows):
for x, char in enumerate(row):
self.tiles[x][y] = Tile(char, x, y)
def generate_mechs(self, game):
""" Generate enemy mechs from the game state. """
self.mechs = []
logging.debug('Generating enemy mechs...')
for name, player in game.state.players.items():
print(name, player, game.state.json)
if game.queue.is_turn(name):
self.player = Player(player.name, player.pos, player.health, player.score, player.ammo)
else:
self.mechs.append(Enemy(player.name, player.pos, player.health, player.score, player.ammo))
|
<commit_before>import logging
from tile import Tile
from mech import Mech, Enemy, Player
class World(object):
def __init__(self, game):
print(game.state)
self.generate_tiles(game.state)
self.generate_mechs(game.state)
def generate_tiles(self, state):
""" Generate a tileset from the game state. """
logging.debug('Generating tiles...')
map = state.map
rows = map.split()
height = len(rows)
width = len(rows[0])
self.tiles = [[None for _ in range(height)] for _ in range(width)]
for y, row in enumerate(rows):
for x, char in enumerate(row):
self.tiles[x][y] = Tile(char, x, y)
def generate_mechs(self, state):
""" Generate enemy mechs from the game state. """
self.mechs = []
logging.debug('Generating enemy mechs...')
for name, player in state.players.items():
print(name, player, state)
is_current_player = False # TODO: Determine current player from state?
if is_current_player:
self.player = Player(player.name, player.pos, player.health, player.score, player.ammo)
else:
self.mechs.append(Enemy(player.name, player.pos, player.health, player.score, player.ammo))
<commit_msg>Use game.queue.is_turn(name) to build player or enemies<commit_after>import logging
from tile import Tile
from mech import Mech, Enemy, Player
class World(object):
def __init__(self, game):
print(game.state)
self.generate_tiles(game.state)
self.generate_mechs(game)
def generate_tiles(self, state):
""" Generate a tileset from the game state. """
logging.debug('Generating tiles...')
map = state.map
rows = map.split()
height = len(rows)
width = len(rows[0])
self.tiles = [[None for _ in range(height)] for _ in range(width)]
for y, row in enumerate(rows):
for x, char in enumerate(row):
self.tiles[x][y] = Tile(char, x, y)
def generate_mechs(self, game):
""" Generate enemy mechs from the game state. """
self.mechs = []
logging.debug('Generating enemy mechs...')
for name, player in game.state.players.items():
print(name, player, game.state.json)
if game.queue.is_turn(name):
self.player = Player(player.name, player.pos, player.health, player.score, player.ammo)
else:
self.mechs.append(Enemy(player.name, player.pos, player.health, player.score, player.ammo))
|
7bc4afdde415ec4176c589fb867ccdee2db5c041
|
fmn/filters/generic.py
|
fmn/filters/generic.py
|
# Generic filters for FMN
import fedmsg
def user_filter(config, message, fasnick=None, *args, **kw):
""" All messages of user
Use this filter to filter out messages that are associated with a
specified user.
"""
fasnick = kw.get('fasnick', fasnick)
if fasnick:
return fasnick in fedmsg.meta.msg2usernames(message)
|
# Generic filters for FMN
import fedmsg
import fmn.lib.pkgdb
def user_filter(config, message, fasnick=None, *args, **kw):
""" All messages of user
Use this filter to filter out messages that are associated with a
specified user.
"""
fasnick = kw.get('fasnick', fasnick)
if fasnick:
return fasnick in fedmsg.meta.msg2usernames(message)
def user_package_filter(config, message, fasnick=None, *args, **kw):
""" All messages concerning user's packages
This filter filters out messages that related to packages where the
specified user has **commit** ACLs.
"""
fasnick = kw.get('fasnick', fasnick)
if fasnick:
packages = fmn.lib.pkgdb.get_package_of_user(fasnick)
return packages.intersection(fedmsg.meta.msg2packages(message))
|
Add first filter relying on pkgdb integration
|
Add first filter relying on pkgdb integration
|
Python
|
lgpl-2.1
|
jeremycline/fmn,jeremycline/fmn,jeremycline/fmn
|
# Generic filters for FMN
import fedmsg
def user_filter(config, message, fasnick=None, *args, **kw):
""" All messages of user
Use this filter to filter out messages that are associated with a
specified user.
"""
fasnick = kw.get('fasnick', fasnick)
if fasnick:
return fasnick in fedmsg.meta.msg2usernames(message)
Add first filter relying on pkgdb integration
|
# Generic filters for FMN
import fedmsg
import fmn.lib.pkgdb
def user_filter(config, message, fasnick=None, *args, **kw):
""" All messages of user
Use this filter to filter out messages that are associated with a
specified user.
"""
fasnick = kw.get('fasnick', fasnick)
if fasnick:
return fasnick in fedmsg.meta.msg2usernames(message)
def user_package_filter(config, message, fasnick=None, *args, **kw):
""" All messages concerning user's packages
This filter filters out messages that related to packages where the
specified user has **commit** ACLs.
"""
fasnick = kw.get('fasnick', fasnick)
if fasnick:
packages = fmn.lib.pkgdb.get_package_of_user(fasnick)
return packages.intersection(fedmsg.meta.msg2packages(message))
|
<commit_before># Generic filters for FMN
import fedmsg
def user_filter(config, message, fasnick=None, *args, **kw):
""" All messages of user
Use this filter to filter out messages that are associated with a
specified user.
"""
fasnick = kw.get('fasnick', fasnick)
if fasnick:
return fasnick in fedmsg.meta.msg2usernames(message)
<commit_msg>Add first filter relying on pkgdb integration<commit_after>
|
# Generic filters for FMN
import fedmsg
import fmn.lib.pkgdb
def user_filter(config, message, fasnick=None, *args, **kw):
""" All messages of user
Use this filter to filter out messages that are associated with a
specified user.
"""
fasnick = kw.get('fasnick', fasnick)
if fasnick:
return fasnick in fedmsg.meta.msg2usernames(message)
def user_package_filter(config, message, fasnick=None, *args, **kw):
""" All messages concerning user's packages
This filter filters out messages that related to packages where the
specified user has **commit** ACLs.
"""
fasnick = kw.get('fasnick', fasnick)
if fasnick:
packages = fmn.lib.pkgdb.get_package_of_user(fasnick)
return packages.intersection(fedmsg.meta.msg2packages(message))
|
# Generic filters for FMN
import fedmsg
def user_filter(config, message, fasnick=None, *args, **kw):
""" All messages of user
Use this filter to filter out messages that are associated with a
specified user.
"""
fasnick = kw.get('fasnick', fasnick)
if fasnick:
return fasnick in fedmsg.meta.msg2usernames(message)
Add first filter relying on pkgdb integration# Generic filters for FMN
import fedmsg
import fmn.lib.pkgdb
def user_filter(config, message, fasnick=None, *args, **kw):
""" All messages of user
Use this filter to filter out messages that are associated with a
specified user.
"""
fasnick = kw.get('fasnick', fasnick)
if fasnick:
return fasnick in fedmsg.meta.msg2usernames(message)
def user_package_filter(config, message, fasnick=None, *args, **kw):
""" All messages concerning user's packages
This filter filters out messages that related to packages where the
specified user has **commit** ACLs.
"""
fasnick = kw.get('fasnick', fasnick)
if fasnick:
packages = fmn.lib.pkgdb.get_package_of_user(fasnick)
return packages.intersection(fedmsg.meta.msg2packages(message))
|
<commit_before># Generic filters for FMN
import fedmsg
def user_filter(config, message, fasnick=None, *args, **kw):
""" All messages of user
Use this filter to filter out messages that are associated with a
specified user.
"""
fasnick = kw.get('fasnick', fasnick)
if fasnick:
return fasnick in fedmsg.meta.msg2usernames(message)
<commit_msg>Add first filter relying on pkgdb integration<commit_after># Generic filters for FMN
import fedmsg
import fmn.lib.pkgdb
def user_filter(config, message, fasnick=None, *args, **kw):
""" All messages of user
Use this filter to filter out messages that are associated with a
specified user.
"""
fasnick = kw.get('fasnick', fasnick)
if fasnick:
return fasnick in fedmsg.meta.msg2usernames(message)
def user_package_filter(config, message, fasnick=None, *args, **kw):
""" All messages concerning user's packages
This filter filters out messages that related to packages where the
specified user has **commit** ACLs.
"""
fasnick = kw.get('fasnick', fasnick)
if fasnick:
packages = fmn.lib.pkgdb.get_package_of_user(fasnick)
return packages.intersection(fedmsg.meta.msg2packages(message))
|
8d235a76120aadcd555da3d641f509541f525eb8
|
csunplugged/utils/retrieve_query_parameter.py
|
csunplugged/utils/retrieve_query_parameter.py
|
"""Module for retrieving a GET request query parameter."""
from django.http import Http404
def retrieve_query_parameter(request, parameter, valid_options=None):
"""Retrieve the query parameter.
If the parameter cannot be found, or is not found in the list of
valid options, then a 404 error is raised.
Args:
request: Request object (Request).
parameter: Parameter to retrieve (str).
valid_options: If provided, a list of valid options (list of str).
Returns:
String value of parameter.
"""
value = request.get(parameter, None)
if value is None:
raise Http404("{} parameter not specified.".format(parameter))
if valid_options and value not in valid_options:
raise Http404("{} parameter not valid.".format(parameter))
return value
|
"""Module for retrieving a GET request query parameter."""
from django.http import Http404
def retrieve_query_parameter(request, parameter, valid_options=None):
"""Retrieve the query parameter.
If the parameter cannot be found, or is not found in the list of
valid options, then a 404 error is raised.
Args:
request: Request object (Request).
parameter: Parameter to retrieve (str).
valid_options: If provided, a list of valid options (list of str).
Returns:
String value of parameter.
"""
value = request.get(parameter, None)
if value is None:
raise Http404("{} parameter not specified.".format(parameter))
if valid_options and value not in valid_options:
raise Http404("{} parameter not valid.".format(parameter))
return value
def retrieve_query_parameter_list(request, parameter, valid_options=None):
"""Retrieve the query parameter list.
If the parameter cannot be found, or is not found in the list of
valid options, then a 404 error is raised.
Args:
request: Request object (Request).
parameter: Parameter to retrieve (str).
valid_options: If provided, a list of valid options (list of str).
Returns:
List of strings of values of parameter.
"""
values = request.getlist(parameter, None)
if values is None:
raise Http404("{} parameter not specified.".format(parameter))
if valid_options:
for value in values:
if value not in valid_options:
raise Http404("{} parameter not valid.".format(parameter))
return values
|
Add function to get list of parameters
|
Add function to get list of parameters
|
Python
|
mit
|
uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged
|
"""Module for retrieving a GET request query parameter."""
from django.http import Http404
def retrieve_query_parameter(request, parameter, valid_options=None):
"""Retrieve the query parameter.
If the parameter cannot be found, or is not found in the list of
valid options, then a 404 error is raised.
Args:
request: Request object (Request).
parameter: Parameter to retrieve (str).
valid_options: If provided, a list of valid options (list of str).
Returns:
String value of parameter.
"""
value = request.get(parameter, None)
if value is None:
raise Http404("{} parameter not specified.".format(parameter))
if valid_options and value not in valid_options:
raise Http404("{} parameter not valid.".format(parameter))
return value
Add function to get list of parameters
|
"""Module for retrieving a GET request query parameter."""
from django.http import Http404
def retrieve_query_parameter(request, parameter, valid_options=None):
"""Retrieve the query parameter.
If the parameter cannot be found, or is not found in the list of
valid options, then a 404 error is raised.
Args:
request: Request object (Request).
parameter: Parameter to retrieve (str).
valid_options: If provided, a list of valid options (list of str).
Returns:
String value of parameter.
"""
value = request.get(parameter, None)
if value is None:
raise Http404("{} parameter not specified.".format(parameter))
if valid_options and value not in valid_options:
raise Http404("{} parameter not valid.".format(parameter))
return value
def retrieve_query_parameter_list(request, parameter, valid_options=None):
"""Retrieve the query parameter list.
If the parameter cannot be found, or is not found in the list of
valid options, then a 404 error is raised.
Args:
request: Request object (Request).
parameter: Parameter to retrieve (str).
valid_options: If provided, a list of valid options (list of str).
Returns:
List of strings of values of parameter.
"""
values = request.getlist(parameter, None)
if values is None:
raise Http404("{} parameter not specified.".format(parameter))
if valid_options:
for value in values:
if value not in valid_options:
raise Http404("{} parameter not valid.".format(parameter))
return values
|
<commit_before>"""Module for retrieving a GET request query parameter."""
from django.http import Http404
def retrieve_query_parameter(request, parameter, valid_options=None):
"""Retrieve the query parameter.
If the parameter cannot be found, or is not found in the list of
valid options, then a 404 error is raised.
Args:
request: Request object (Request).
parameter: Parameter to retrieve (str).
valid_options: If provided, a list of valid options (list of str).
Returns:
String value of parameter.
"""
value = request.get(parameter, None)
if value is None:
raise Http404("{} parameter not specified.".format(parameter))
if valid_options and value not in valid_options:
raise Http404("{} parameter not valid.".format(parameter))
return value
<commit_msg>Add function to get list of parameters<commit_after>
|
"""Module for retrieving a GET request query parameter."""
from django.http import Http404
def retrieve_query_parameter(request, parameter, valid_options=None):
"""Retrieve the query parameter.
If the parameter cannot be found, or is not found in the list of
valid options, then a 404 error is raised.
Args:
request: Request object (Request).
parameter: Parameter to retrieve (str).
valid_options: If provided, a list of valid options (list of str).
Returns:
String value of parameter.
"""
value = request.get(parameter, None)
if value is None:
raise Http404("{} parameter not specified.".format(parameter))
if valid_options and value not in valid_options:
raise Http404("{} parameter not valid.".format(parameter))
return value
def retrieve_query_parameter_list(request, parameter, valid_options=None):
"""Retrieve the query parameter list.
If the parameter cannot be found, or is not found in the list of
valid options, then a 404 error is raised.
Args:
request: Request object (Request).
parameter: Parameter to retrieve (str).
valid_options: If provided, a list of valid options (list of str).
Returns:
List of strings of values of parameter.
"""
values = request.getlist(parameter, None)
if values is None:
raise Http404("{} parameter not specified.".format(parameter))
if valid_options:
for value in values:
if value not in valid_options:
raise Http404("{} parameter not valid.".format(parameter))
return values
|
"""Module for retrieving a GET request query parameter."""
from django.http import Http404
def retrieve_query_parameter(request, parameter, valid_options=None):
"""Retrieve the query parameter.
If the parameter cannot be found, or is not found in the list of
valid options, then a 404 error is raised.
Args:
request: Request object (Request).
parameter: Parameter to retrieve (str).
valid_options: If provided, a list of valid options (list of str).
Returns:
String value of parameter.
"""
value = request.get(parameter, None)
if value is None:
raise Http404("{} parameter not specified.".format(parameter))
if valid_options and value not in valid_options:
raise Http404("{} parameter not valid.".format(parameter))
return value
Add function to get list of parameters"""Module for retrieving a GET request query parameter."""
from django.http import Http404
def retrieve_query_parameter(request, parameter, valid_options=None):
"""Retrieve the query parameter.
If the parameter cannot be found, or is not found in the list of
valid options, then a 404 error is raised.
Args:
request: Request object (Request).
parameter: Parameter to retrieve (str).
valid_options: If provided, a list of valid options (list of str).
Returns:
String value of parameter.
"""
value = request.get(parameter, None)
if value is None:
raise Http404("{} parameter not specified.".format(parameter))
if valid_options and value not in valid_options:
raise Http404("{} parameter not valid.".format(parameter))
return value
def retrieve_query_parameter_list(request, parameter, valid_options=None):
"""Retrieve the query parameter list.
If the parameter cannot be found, or is not found in the list of
valid options, then a 404 error is raised.
Args:
request: Request object (Request).
parameter: Parameter to retrieve (str).
valid_options: If provided, a list of valid options (list of str).
Returns:
List of strings of values of parameter.
"""
values = request.getlist(parameter, None)
if values is None:
raise Http404("{} parameter not specified.".format(parameter))
if valid_options:
for value in values:
if value not in valid_options:
raise Http404("{} parameter not valid.".format(parameter))
return values
|
<commit_before>"""Module for retrieving a GET request query parameter."""
from django.http import Http404
def retrieve_query_parameter(request, parameter, valid_options=None):
"""Retrieve the query parameter.
If the parameter cannot be found, or is not found in the list of
valid options, then a 404 error is raised.
Args:
request: Request object (Request).
parameter: Parameter to retrieve (str).
valid_options: If provided, a list of valid options (list of str).
Returns:
String value of parameter.
"""
value = request.get(parameter, None)
if value is None:
raise Http404("{} parameter not specified.".format(parameter))
if valid_options and value not in valid_options:
raise Http404("{} parameter not valid.".format(parameter))
return value
<commit_msg>Add function to get list of parameters<commit_after>"""Module for retrieving a GET request query parameter."""
from django.http import Http404
def retrieve_query_parameter(request, parameter, valid_options=None):
"""Retrieve the query parameter.
If the parameter cannot be found, or is not found in the list of
valid options, then a 404 error is raised.
Args:
request: Request object (Request).
parameter: Parameter to retrieve (str).
valid_options: If provided, a list of valid options (list of str).
Returns:
String value of parameter.
"""
value = request.get(parameter, None)
if value is None:
raise Http404("{} parameter not specified.".format(parameter))
if valid_options and value not in valid_options:
raise Http404("{} parameter not valid.".format(parameter))
return value
def retrieve_query_parameter_list(request, parameter, valid_options=None):
"""Retrieve the query parameter list.
If the parameter cannot be found, or is not found in the list of
valid options, then a 404 error is raised.
Args:
request: Request object (Request).
parameter: Parameter to retrieve (str).
valid_options: If provided, a list of valid options (list of str).
Returns:
List of strings of values of parameter.
"""
values = request.getlist(parameter, None)
if values is None:
raise Http404("{} parameter not specified.".format(parameter))
if valid_options:
for value in values:
if value not in valid_options:
raise Http404("{} parameter not valid.".format(parameter))
return values
|
ce1f62dd809b3bec0abb345464edede6a5701b20
|
clock.py
|
clock.py
|
from __future__ import print_function
from apscheduler.schedulers.blocking import BlockingScheduler
import logging
import subprocess
logging.basicConfig()
job_defaults = {
'coalesce': False,
'max_instances': 2
}
scheduler = BlockingScheduler(job_defaults=job_defaults)
@scheduler.scheduled_job('interval', minutes=1)
def timed_job_min1():
print("Run notifier (interval=1)")
subprocess.check_call(
"notifier -concurrency=5 -fetcher-cache=true -notification-interval=1 && curl -sS https://nosnch.in/c411a3a685",
shell=True)
@scheduler.scheduled_job('interval', minutes=20)
def timed_job_min10():
print("Run notifier (interval=10)")
subprocess.check_call(
"notifier -concurrency=9 -fetcher-cache=true -notification-interval=10 && curl -sS https://nosnch.in/c411a3a685",
shell=True)
@scheduler.scheduled_job('interval', days=7)
def timed_job_days7():
print("Run teacher_error_resetter")
subprocess.check_call(
"teacher_error_resetter -concurrency=5",
shell=True)
scheduler.start()
|
from __future__ import print_function
from apscheduler.schedulers.blocking import BlockingScheduler
import logging
import subprocess
logging.basicConfig()
job_defaults = {
'coalesce': False,
'max_instances': 2
}
scheduler = BlockingScheduler(job_defaults=job_defaults)
@scheduler.scheduled_job('interval', minutes=1)
def timed_job_min1():
print("Run notifier (interval=1)")
subprocess.check_call(
"notifier -concurrency=5 -fetcher-cache=true -notification-interval=1 && curl -sS https://nosnch.in/c411a3a685",
shell=True)
@scheduler.scheduled_job('interval', minutes=10)
def timed_job_min10():
print("Run notifier (interval=10)")
subprocess.check_call(
"notifier -concurrency=9 -fetcher-cache=true -notification-interval=10 && curl -sS https://nosnch.in/c411a3a685",
shell=True)
@scheduler.scheduled_job('interval', days=7)
def timed_job_days7():
print("Run teacher_error_resetter")
subprocess.check_call(
"teacher_error_resetter -concurrency=5",
shell=True)
scheduler.start()
|
Change notifier interval: 20 -> 10
|
Change notifier interval: 20 -> 10
|
Python
|
mit
|
oinume/lekcije,oinume/lekcije,oinume/lekcije,oinume/lekcije,oinume/lekcije,oinume/lekcije
|
from __future__ import print_function
from apscheduler.schedulers.blocking import BlockingScheduler
import logging
import subprocess
logging.basicConfig()
job_defaults = {
'coalesce': False,
'max_instances': 2
}
scheduler = BlockingScheduler(job_defaults=job_defaults)
@scheduler.scheduled_job('interval', minutes=1)
def timed_job_min1():
print("Run notifier (interval=1)")
subprocess.check_call(
"notifier -concurrency=5 -fetcher-cache=true -notification-interval=1 && curl -sS https://nosnch.in/c411a3a685",
shell=True)
@scheduler.scheduled_job('interval', minutes=20)
def timed_job_min10():
print("Run notifier (interval=10)")
subprocess.check_call(
"notifier -concurrency=9 -fetcher-cache=true -notification-interval=10 && curl -sS https://nosnch.in/c411a3a685",
shell=True)
@scheduler.scheduled_job('interval', days=7)
def timed_job_days7():
print("Run teacher_error_resetter")
subprocess.check_call(
"teacher_error_resetter -concurrency=5",
shell=True)
scheduler.start()
Change notifier interval: 20 -> 10
|
from __future__ import print_function
from apscheduler.schedulers.blocking import BlockingScheduler
import logging
import subprocess
logging.basicConfig()
job_defaults = {
'coalesce': False,
'max_instances': 2
}
scheduler = BlockingScheduler(job_defaults=job_defaults)
@scheduler.scheduled_job('interval', minutes=1)
def timed_job_min1():
print("Run notifier (interval=1)")
subprocess.check_call(
"notifier -concurrency=5 -fetcher-cache=true -notification-interval=1 && curl -sS https://nosnch.in/c411a3a685",
shell=True)
@scheduler.scheduled_job('interval', minutes=10)
def timed_job_min10():
print("Run notifier (interval=10)")
subprocess.check_call(
"notifier -concurrency=9 -fetcher-cache=true -notification-interval=10 && curl -sS https://nosnch.in/c411a3a685",
shell=True)
@scheduler.scheduled_job('interval', days=7)
def timed_job_days7():
print("Run teacher_error_resetter")
subprocess.check_call(
"teacher_error_resetter -concurrency=5",
shell=True)
scheduler.start()
|
<commit_before>from __future__ import print_function
from apscheduler.schedulers.blocking import BlockingScheduler
import logging
import subprocess
logging.basicConfig()
job_defaults = {
'coalesce': False,
'max_instances': 2
}
scheduler = BlockingScheduler(job_defaults=job_defaults)
@scheduler.scheduled_job('interval', minutes=1)
def timed_job_min1():
print("Run notifier (interval=1)")
subprocess.check_call(
"notifier -concurrency=5 -fetcher-cache=true -notification-interval=1 && curl -sS https://nosnch.in/c411a3a685",
shell=True)
@scheduler.scheduled_job('interval', minutes=20)
def timed_job_min10():
print("Run notifier (interval=10)")
subprocess.check_call(
"notifier -concurrency=9 -fetcher-cache=true -notification-interval=10 && curl -sS https://nosnch.in/c411a3a685",
shell=True)
@scheduler.scheduled_job('interval', days=7)
def timed_job_days7():
print("Run teacher_error_resetter")
subprocess.check_call(
"teacher_error_resetter -concurrency=5",
shell=True)
scheduler.start()
<commit_msg>Change notifier interval: 20 -> 10<commit_after>
|
from __future__ import print_function
from apscheduler.schedulers.blocking import BlockingScheduler
import logging
import subprocess
logging.basicConfig()
job_defaults = {
'coalesce': False,
'max_instances': 2
}
scheduler = BlockingScheduler(job_defaults=job_defaults)
@scheduler.scheduled_job('interval', minutes=1)
def timed_job_min1():
print("Run notifier (interval=1)")
subprocess.check_call(
"notifier -concurrency=5 -fetcher-cache=true -notification-interval=1 && curl -sS https://nosnch.in/c411a3a685",
shell=True)
@scheduler.scheduled_job('interval', minutes=10)
def timed_job_min10():
print("Run notifier (interval=10)")
subprocess.check_call(
"notifier -concurrency=9 -fetcher-cache=true -notification-interval=10 && curl -sS https://nosnch.in/c411a3a685",
shell=True)
@scheduler.scheduled_job('interval', days=7)
def timed_job_days7():
print("Run teacher_error_resetter")
subprocess.check_call(
"teacher_error_resetter -concurrency=5",
shell=True)
scheduler.start()
|
from __future__ import print_function
from apscheduler.schedulers.blocking import BlockingScheduler
import logging
import subprocess
logging.basicConfig()
job_defaults = {
'coalesce': False,
'max_instances': 2
}
scheduler = BlockingScheduler(job_defaults=job_defaults)
@scheduler.scheduled_job('interval', minutes=1)
def timed_job_min1():
print("Run notifier (interval=1)")
subprocess.check_call(
"notifier -concurrency=5 -fetcher-cache=true -notification-interval=1 && curl -sS https://nosnch.in/c411a3a685",
shell=True)
@scheduler.scheduled_job('interval', minutes=20)
def timed_job_min10():
print("Run notifier (interval=10)")
subprocess.check_call(
"notifier -concurrency=9 -fetcher-cache=true -notification-interval=10 && curl -sS https://nosnch.in/c411a3a685",
shell=True)
@scheduler.scheduled_job('interval', days=7)
def timed_job_days7():
print("Run teacher_error_resetter")
subprocess.check_call(
"teacher_error_resetter -concurrency=5",
shell=True)
scheduler.start()
Change notifier interval: 20 -> 10from __future__ import print_function
from apscheduler.schedulers.blocking import BlockingScheduler
import logging
import subprocess
logging.basicConfig()
job_defaults = {
'coalesce': False,
'max_instances': 2
}
scheduler = BlockingScheduler(job_defaults=job_defaults)
@scheduler.scheduled_job('interval', minutes=1)
def timed_job_min1():
print("Run notifier (interval=1)")
subprocess.check_call(
"notifier -concurrency=5 -fetcher-cache=true -notification-interval=1 && curl -sS https://nosnch.in/c411a3a685",
shell=True)
@scheduler.scheduled_job('interval', minutes=10)
def timed_job_min10():
print("Run notifier (interval=10)")
subprocess.check_call(
"notifier -concurrency=9 -fetcher-cache=true -notification-interval=10 && curl -sS https://nosnch.in/c411a3a685",
shell=True)
@scheduler.scheduled_job('interval', days=7)
def timed_job_days7():
print("Run teacher_error_resetter")
subprocess.check_call(
"teacher_error_resetter -concurrency=5",
shell=True)
scheduler.start()
|
<commit_before>from __future__ import print_function
from apscheduler.schedulers.blocking import BlockingScheduler
import logging
import subprocess
logging.basicConfig()
job_defaults = {
'coalesce': False,
'max_instances': 2
}
scheduler = BlockingScheduler(job_defaults=job_defaults)
@scheduler.scheduled_job('interval', minutes=1)
def timed_job_min1():
print("Run notifier (interval=1)")
subprocess.check_call(
"notifier -concurrency=5 -fetcher-cache=true -notification-interval=1 && curl -sS https://nosnch.in/c411a3a685",
shell=True)
@scheduler.scheduled_job('interval', minutes=20)
def timed_job_min10():
print("Run notifier (interval=10)")
subprocess.check_call(
"notifier -concurrency=9 -fetcher-cache=true -notification-interval=10 && curl -sS https://nosnch.in/c411a3a685",
shell=True)
@scheduler.scheduled_job('interval', days=7)
def timed_job_days7():
print("Run teacher_error_resetter")
subprocess.check_call(
"teacher_error_resetter -concurrency=5",
shell=True)
scheduler.start()
<commit_msg>Change notifier interval: 20 -> 10<commit_after>from __future__ import print_function
from apscheduler.schedulers.blocking import BlockingScheduler
import logging
import subprocess
logging.basicConfig()
job_defaults = {
'coalesce': False,
'max_instances': 2
}
scheduler = BlockingScheduler(job_defaults=job_defaults)
@scheduler.scheduled_job('interval', minutes=1)
def timed_job_min1():
print("Run notifier (interval=1)")
subprocess.check_call(
"notifier -concurrency=5 -fetcher-cache=true -notification-interval=1 && curl -sS https://nosnch.in/c411a3a685",
shell=True)
@scheduler.scheduled_job('interval', minutes=10)
def timed_job_min10():
print("Run notifier (interval=10)")
subprocess.check_call(
"notifier -concurrency=9 -fetcher-cache=true -notification-interval=10 && curl -sS https://nosnch.in/c411a3a685",
shell=True)
@scheduler.scheduled_job('interval', days=7)
def timed_job_days7():
print("Run teacher_error_resetter")
subprocess.check_call(
"teacher_error_resetter -concurrency=5",
shell=True)
scheduler.start()
|
d4adacc41858e224a8508a6da7ea77a30d1f8d9a
|
utils/data_paths.py
|
utils/data_paths.py
|
import os
ROOT_DIR_PATH = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
DATA_DIR_PATH = os.path.join(ROOT_DIR_PATH, 'data')
DATA_MOVIE_USER_DIR_PATH = os.path.join(DATA_DIR_PATH, 'mu')
DATA_USER_MOVIE_DIR_PATH = os.path.join(DATA_DIR_PATH, 'um')
SUBMISSIONS_DIR_PATH = os.path.join(ROOT_DIR_PATH, 'submissions')
ALL_DATA_FILE_PATH = os.path.join(DATA_MOVIE_USER_DIR_PATH, 'all.dta')
ALL_INDEX_FILE_PATH = os.path.join(DATA_MOVIE_USER_DIR_PATH, 'all.idx')
BASE_DATA_FILE_PATH = os.path.join(DATA_MOVIE_USER_DIR_PATH, 'base.dta')
HIDDEN_DATA_FILE_PATH = os.path.join(DATA_MOVIE_USER_DIR_PATH, 'hidden.dta')
PROBE_DATA_FILE_PATH = os.path.join(DATA_MOVIE_USER_DIR_PATH, 'probe.dta')
|
import os
ROOT_DIR_PATH = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
DATA_DIR_PATH = os.path.join(ROOT_DIR_PATH, 'data')
DATA_MOVIE_USER_DIR_PATH = os.path.join(DATA_DIR_PATH, 'mu')
DATA_USER_MOVIE_DIR_PATH = os.path.join(DATA_DIR_PATH, 'um')
SUBMISSIONS_DIR_PATH = os.path.join(ROOT_DIR_PATH, 'submissions')
ALL_DATA_FILE_PATH = os.path.join(DATA_MOVIE_USER_DIR_PATH, 'all.dta')
ALL_INDEX_FILE_PATH = os.path.join(DATA_MOVIE_USER_DIR_PATH, 'all.idx')
|
Remove base/hidden/probe data file paths (data_io isn't writing split data to files)
|
Remove base/hidden/probe data file paths (data_io isn't writing split data to files)
|
Python
|
mit
|
jvanbrug/netflix,jvanbrug/netflix
|
import os
ROOT_DIR_PATH = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
DATA_DIR_PATH = os.path.join(ROOT_DIR_PATH, 'data')
DATA_MOVIE_USER_DIR_PATH = os.path.join(DATA_DIR_PATH, 'mu')
DATA_USER_MOVIE_DIR_PATH = os.path.join(DATA_DIR_PATH, 'um')
SUBMISSIONS_DIR_PATH = os.path.join(ROOT_DIR_PATH, 'submissions')
ALL_DATA_FILE_PATH = os.path.join(DATA_MOVIE_USER_DIR_PATH, 'all.dta')
ALL_INDEX_FILE_PATH = os.path.join(DATA_MOVIE_USER_DIR_PATH, 'all.idx')
BASE_DATA_FILE_PATH = os.path.join(DATA_MOVIE_USER_DIR_PATH, 'base.dta')
HIDDEN_DATA_FILE_PATH = os.path.join(DATA_MOVIE_USER_DIR_PATH, 'hidden.dta')
PROBE_DATA_FILE_PATH = os.path.join(DATA_MOVIE_USER_DIR_PATH, 'probe.dta')
Remove base/hidden/probe data file paths (data_io isn't writing split data to files)
|
import os
ROOT_DIR_PATH = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
DATA_DIR_PATH = os.path.join(ROOT_DIR_PATH, 'data')
DATA_MOVIE_USER_DIR_PATH = os.path.join(DATA_DIR_PATH, 'mu')
DATA_USER_MOVIE_DIR_PATH = os.path.join(DATA_DIR_PATH, 'um')
SUBMISSIONS_DIR_PATH = os.path.join(ROOT_DIR_PATH, 'submissions')
ALL_DATA_FILE_PATH = os.path.join(DATA_MOVIE_USER_DIR_PATH, 'all.dta')
ALL_INDEX_FILE_PATH = os.path.join(DATA_MOVIE_USER_DIR_PATH, 'all.idx')
|
<commit_before>import os
ROOT_DIR_PATH = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
DATA_DIR_PATH = os.path.join(ROOT_DIR_PATH, 'data')
DATA_MOVIE_USER_DIR_PATH = os.path.join(DATA_DIR_PATH, 'mu')
DATA_USER_MOVIE_DIR_PATH = os.path.join(DATA_DIR_PATH, 'um')
SUBMISSIONS_DIR_PATH = os.path.join(ROOT_DIR_PATH, 'submissions')
ALL_DATA_FILE_PATH = os.path.join(DATA_MOVIE_USER_DIR_PATH, 'all.dta')
ALL_INDEX_FILE_PATH = os.path.join(DATA_MOVIE_USER_DIR_PATH, 'all.idx')
BASE_DATA_FILE_PATH = os.path.join(DATA_MOVIE_USER_DIR_PATH, 'base.dta')
HIDDEN_DATA_FILE_PATH = os.path.join(DATA_MOVIE_USER_DIR_PATH, 'hidden.dta')
PROBE_DATA_FILE_PATH = os.path.join(DATA_MOVIE_USER_DIR_PATH, 'probe.dta')
<commit_msg>Remove base/hidden/probe data file paths (data_io isn't writing split data to files)<commit_after>
|
import os
ROOT_DIR_PATH = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
DATA_DIR_PATH = os.path.join(ROOT_DIR_PATH, 'data')
DATA_MOVIE_USER_DIR_PATH = os.path.join(DATA_DIR_PATH, 'mu')
DATA_USER_MOVIE_DIR_PATH = os.path.join(DATA_DIR_PATH, 'um')
SUBMISSIONS_DIR_PATH = os.path.join(ROOT_DIR_PATH, 'submissions')
ALL_DATA_FILE_PATH = os.path.join(DATA_MOVIE_USER_DIR_PATH, 'all.dta')
ALL_INDEX_FILE_PATH = os.path.join(DATA_MOVIE_USER_DIR_PATH, 'all.idx')
|
import os
ROOT_DIR_PATH = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
DATA_DIR_PATH = os.path.join(ROOT_DIR_PATH, 'data')
DATA_MOVIE_USER_DIR_PATH = os.path.join(DATA_DIR_PATH, 'mu')
DATA_USER_MOVIE_DIR_PATH = os.path.join(DATA_DIR_PATH, 'um')
SUBMISSIONS_DIR_PATH = os.path.join(ROOT_DIR_PATH, 'submissions')
ALL_DATA_FILE_PATH = os.path.join(DATA_MOVIE_USER_DIR_PATH, 'all.dta')
ALL_INDEX_FILE_PATH = os.path.join(DATA_MOVIE_USER_DIR_PATH, 'all.idx')
BASE_DATA_FILE_PATH = os.path.join(DATA_MOVIE_USER_DIR_PATH, 'base.dta')
HIDDEN_DATA_FILE_PATH = os.path.join(DATA_MOVIE_USER_DIR_PATH, 'hidden.dta')
PROBE_DATA_FILE_PATH = os.path.join(DATA_MOVIE_USER_DIR_PATH, 'probe.dta')
Remove base/hidden/probe data file paths (data_io isn't writing split data to files)import os
ROOT_DIR_PATH = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
DATA_DIR_PATH = os.path.join(ROOT_DIR_PATH, 'data')
DATA_MOVIE_USER_DIR_PATH = os.path.join(DATA_DIR_PATH, 'mu')
DATA_USER_MOVIE_DIR_PATH = os.path.join(DATA_DIR_PATH, 'um')
SUBMISSIONS_DIR_PATH = os.path.join(ROOT_DIR_PATH, 'submissions')
ALL_DATA_FILE_PATH = os.path.join(DATA_MOVIE_USER_DIR_PATH, 'all.dta')
ALL_INDEX_FILE_PATH = os.path.join(DATA_MOVIE_USER_DIR_PATH, 'all.idx')
|
<commit_before>import os
ROOT_DIR_PATH = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
DATA_DIR_PATH = os.path.join(ROOT_DIR_PATH, 'data')
DATA_MOVIE_USER_DIR_PATH = os.path.join(DATA_DIR_PATH, 'mu')
DATA_USER_MOVIE_DIR_PATH = os.path.join(DATA_DIR_PATH, 'um')
SUBMISSIONS_DIR_PATH = os.path.join(ROOT_DIR_PATH, 'submissions')
ALL_DATA_FILE_PATH = os.path.join(DATA_MOVIE_USER_DIR_PATH, 'all.dta')
ALL_INDEX_FILE_PATH = os.path.join(DATA_MOVIE_USER_DIR_PATH, 'all.idx')
BASE_DATA_FILE_PATH = os.path.join(DATA_MOVIE_USER_DIR_PATH, 'base.dta')
HIDDEN_DATA_FILE_PATH = os.path.join(DATA_MOVIE_USER_DIR_PATH, 'hidden.dta')
PROBE_DATA_FILE_PATH = os.path.join(DATA_MOVIE_USER_DIR_PATH, 'probe.dta')
<commit_msg>Remove base/hidden/probe data file paths (data_io isn't writing split data to files)<commit_after>import os
ROOT_DIR_PATH = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
DATA_DIR_PATH = os.path.join(ROOT_DIR_PATH, 'data')
DATA_MOVIE_USER_DIR_PATH = os.path.join(DATA_DIR_PATH, 'mu')
DATA_USER_MOVIE_DIR_PATH = os.path.join(DATA_DIR_PATH, 'um')
SUBMISSIONS_DIR_PATH = os.path.join(ROOT_DIR_PATH, 'submissions')
ALL_DATA_FILE_PATH = os.path.join(DATA_MOVIE_USER_DIR_PATH, 'all.dta')
ALL_INDEX_FILE_PATH = os.path.join(DATA_MOVIE_USER_DIR_PATH, 'all.idx')
|
091c125f42463b372f0c2c99124578eb8fe13150
|
2019/aoc2019/day08.py
|
2019/aoc2019/day08.py
|
from collections import Counter
from typing import Iterable, TextIO
import numpy # type: ignore
def parse_layers(width: int, height: int, data: TextIO) -> Iterable[numpy.array]:
chunk_size = width * height
content = next(data).strip()
for pos in range(0, len(content), chunk_size):
yield numpy.array([int(c) for c in content[pos:pos + chunk_size]])
def part1(data: TextIO) -> int:
best_layer: Counter[int] = min((Counter(layer) for layer in parse_layers(25, 6, data)), key=lambda c: c[0])
return best_layer[1] * best_layer[2]
def format_row(row: Iterable[int]) -> str:
return ''.join('#' if p == 1 else ' ' for p in row)
def part2(data: TextIO) -> str:
layers = list(parse_layers(25, 6, data))
background = numpy.zeros(25 * 6, numpy.int8)
for layer in reversed(layers):
background[layer != 2] = layer[layer != 2]
return '\n'.join(format_row(row) for row in background.reshape(6, 25))
|
from collections import Counter
from typing import Iterable, TextIO
import numpy # type: ignore
def parse_layers(width: int, height: int, data: TextIO) -> Iterable[numpy.array]:
chunk_size = width * height
content = next(data).strip()
for pos in range(0, len(content), chunk_size):
yield numpy.array([int(c) for c in content[pos:pos + chunk_size]])
def part1(data: TextIO) -> int:
best_layer: Counter[int] = min((Counter(layer) for layer in parse_layers(25, 6, data)), key=lambda c: c[0])
return best_layer[1] * best_layer[2]
def format_row(row: Iterable[int]) -> str:
return ''.join('#' if p == 1 else ' ' for p in row)
def part2(data: TextIO) -> str:
background = numpy.zeros(25 * 6, numpy.int8)
background.fill(2)
for layer in parse_layers(25, 6, data):
mask = background == 2
background[mask] = layer[mask]
return '\n'.join(format_row(row) for row in background.reshape(6, 25))
|
Fix day 8 to paint front-to-back
|
Fix day 8 to paint front-to-back
|
Python
|
mit
|
bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode
|
from collections import Counter
from typing import Iterable, TextIO
import numpy # type: ignore
def parse_layers(width: int, height: int, data: TextIO) -> Iterable[numpy.array]:
chunk_size = width * height
content = next(data).strip()
for pos in range(0, len(content), chunk_size):
yield numpy.array([int(c) for c in content[pos:pos + chunk_size]])
def part1(data: TextIO) -> int:
best_layer: Counter[int] = min((Counter(layer) for layer in parse_layers(25, 6, data)), key=lambda c: c[0])
return best_layer[1] * best_layer[2]
def format_row(row: Iterable[int]) -> str:
return ''.join('#' if p == 1 else ' ' for p in row)
def part2(data: TextIO) -> str:
layers = list(parse_layers(25, 6, data))
background = numpy.zeros(25 * 6, numpy.int8)
for layer in reversed(layers):
background[layer != 2] = layer[layer != 2]
return '\n'.join(format_row(row) for row in background.reshape(6, 25))
Fix day 8 to paint front-to-back
|
from collections import Counter
from typing import Iterable, TextIO
import numpy # type: ignore
def parse_layers(width: int, height: int, data: TextIO) -> Iterable[numpy.array]:
chunk_size = width * height
content = next(data).strip()
for pos in range(0, len(content), chunk_size):
yield numpy.array([int(c) for c in content[pos:pos + chunk_size]])
def part1(data: TextIO) -> int:
best_layer: Counter[int] = min((Counter(layer) for layer in parse_layers(25, 6, data)), key=lambda c: c[0])
return best_layer[1] * best_layer[2]
def format_row(row: Iterable[int]) -> str:
return ''.join('#' if p == 1 else ' ' for p in row)
def part2(data: TextIO) -> str:
background = numpy.zeros(25 * 6, numpy.int8)
background.fill(2)
for layer in parse_layers(25, 6, data):
mask = background == 2
background[mask] = layer[mask]
return '\n'.join(format_row(row) for row in background.reshape(6, 25))
|
<commit_before>from collections import Counter
from typing import Iterable, TextIO
import numpy # type: ignore
def parse_layers(width: int, height: int, data: TextIO) -> Iterable[numpy.array]:
chunk_size = width * height
content = next(data).strip()
for pos in range(0, len(content), chunk_size):
yield numpy.array([int(c) for c in content[pos:pos + chunk_size]])
def part1(data: TextIO) -> int:
best_layer: Counter[int] = min((Counter(layer) for layer in parse_layers(25, 6, data)), key=lambda c: c[0])
return best_layer[1] * best_layer[2]
def format_row(row: Iterable[int]) -> str:
return ''.join('#' if p == 1 else ' ' for p in row)
def part2(data: TextIO) -> str:
layers = list(parse_layers(25, 6, data))
background = numpy.zeros(25 * 6, numpy.int8)
for layer in reversed(layers):
background[layer != 2] = layer[layer != 2]
return '\n'.join(format_row(row) for row in background.reshape(6, 25))
<commit_msg>Fix day 8 to paint front-to-back<commit_after>
|
from collections import Counter
from typing import Iterable, TextIO
import numpy # type: ignore
def parse_layers(width: int, height: int, data: TextIO) -> Iterable[numpy.array]:
chunk_size = width * height
content = next(data).strip()
for pos in range(0, len(content), chunk_size):
yield numpy.array([int(c) for c in content[pos:pos + chunk_size]])
def part1(data: TextIO) -> int:
best_layer: Counter[int] = min((Counter(layer) for layer in parse_layers(25, 6, data)), key=lambda c: c[0])
return best_layer[1] * best_layer[2]
def format_row(row: Iterable[int]) -> str:
return ''.join('#' if p == 1 else ' ' for p in row)
def part2(data: TextIO) -> str:
background = numpy.zeros(25 * 6, numpy.int8)
background.fill(2)
for layer in parse_layers(25, 6, data):
mask = background == 2
background[mask] = layer[mask]
return '\n'.join(format_row(row) for row in background.reshape(6, 25))
|
from collections import Counter
from typing import Iterable, TextIO
import numpy # type: ignore
def parse_layers(width: int, height: int, data: TextIO) -> Iterable[numpy.array]:
chunk_size = width * height
content = next(data).strip()
for pos in range(0, len(content), chunk_size):
yield numpy.array([int(c) for c in content[pos:pos + chunk_size]])
def part1(data: TextIO) -> int:
best_layer: Counter[int] = min((Counter(layer) for layer in parse_layers(25, 6, data)), key=lambda c: c[0])
return best_layer[1] * best_layer[2]
def format_row(row: Iterable[int]) -> str:
return ''.join('#' if p == 1 else ' ' for p in row)
def part2(data: TextIO) -> str:
layers = list(parse_layers(25, 6, data))
background = numpy.zeros(25 * 6, numpy.int8)
for layer in reversed(layers):
background[layer != 2] = layer[layer != 2]
return '\n'.join(format_row(row) for row in background.reshape(6, 25))
Fix day 8 to paint front-to-backfrom collections import Counter
from typing import Iterable, TextIO
import numpy # type: ignore
def parse_layers(width: int, height: int, data: TextIO) -> Iterable[numpy.array]:
chunk_size = width * height
content = next(data).strip()
for pos in range(0, len(content), chunk_size):
yield numpy.array([int(c) for c in content[pos:pos + chunk_size]])
def part1(data: TextIO) -> int:
best_layer: Counter[int] = min((Counter(layer) for layer in parse_layers(25, 6, data)), key=lambda c: c[0])
return best_layer[1] * best_layer[2]
def format_row(row: Iterable[int]) -> str:
return ''.join('#' if p == 1 else ' ' for p in row)
def part2(data: TextIO) -> str:
background = numpy.zeros(25 * 6, numpy.int8)
background.fill(2)
for layer in parse_layers(25, 6, data):
mask = background == 2
background[mask] = layer[mask]
return '\n'.join(format_row(row) for row in background.reshape(6, 25))
|
<commit_before>from collections import Counter
from typing import Iterable, TextIO
import numpy # type: ignore
def parse_layers(width: int, height: int, data: TextIO) -> Iterable[numpy.array]:
chunk_size = width * height
content = next(data).strip()
for pos in range(0, len(content), chunk_size):
yield numpy.array([int(c) for c in content[pos:pos + chunk_size]])
def part1(data: TextIO) -> int:
best_layer: Counter[int] = min((Counter(layer) for layer in parse_layers(25, 6, data)), key=lambda c: c[0])
return best_layer[1] * best_layer[2]
def format_row(row: Iterable[int]) -> str:
return ''.join('#' if p == 1 else ' ' for p in row)
def part2(data: TextIO) -> str:
layers = list(parse_layers(25, 6, data))
background = numpy.zeros(25 * 6, numpy.int8)
for layer in reversed(layers):
background[layer != 2] = layer[layer != 2]
return '\n'.join(format_row(row) for row in background.reshape(6, 25))
<commit_msg>Fix day 8 to paint front-to-back<commit_after>from collections import Counter
from typing import Iterable, TextIO
import numpy # type: ignore
def parse_layers(width: int, height: int, data: TextIO) -> Iterable[numpy.array]:
chunk_size = width * height
content = next(data).strip()
for pos in range(0, len(content), chunk_size):
yield numpy.array([int(c) for c in content[pos:pos + chunk_size]])
def part1(data: TextIO) -> int:
best_layer: Counter[int] = min((Counter(layer) for layer in parse_layers(25, 6, data)), key=lambda c: c[0])
return best_layer[1] * best_layer[2]
def format_row(row: Iterable[int]) -> str:
return ''.join('#' if p == 1 else ' ' for p in row)
def part2(data: TextIO) -> str:
background = numpy.zeros(25 * 6, numpy.int8)
background.fill(2)
for layer in parse_layers(25, 6, data):
mask = background == 2
background[mask] = layer[mask]
return '\n'.join(format_row(row) for row in background.reshape(6, 25))
|
28ecf02c3d08eae725512e1563cf74f1831bd02d
|
gears/engines/base.py
|
gears/engines/base.py
|
import subprocess
from functools import wraps
class EngineProcessFailed(Exception):
pass
class BaseEngine(object):
result_mimetype = None
@classmethod
def as_engine(cls, **initkwargs):
@wraps(cls, updated=())
def engine(asset):
instance = engine.engine_class(**initkwargs)
return instance.process(asset)
engine.engine_class = cls
engine.result_mimetype = cls.result_mimetype
return engine
def process(self, asset):
raise NotImplementedError()
class ExecEngine(BaseEngine):
executable = None
params = []
def __init__(self, executable=None):
if executable is not None:
self.executable = executable
def process(self, asset):
self.asset = asset
p = subprocess.Popen(
args=self.get_args(),
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
output, errors = p.communicate(input=asset.processed_source)
if p.returncode != 0:
raise EngineProcessFailed(errors)
asset.processed_source = output
def get_args(self):
return [self.executable] + self.params
|
import subprocess
from functools import wraps
class EngineProcessFailed(Exception):
pass
class BaseEngine(object):
result_mimetype = None
@classmethod
def as_engine(cls, **initkwargs):
@wraps(cls, updated=())
def engine(asset):
instance = engine.engine_class(**initkwargs)
return instance.process(asset)
engine.engine_class = cls
engine.result_mimetype = cls.result_mimetype
return engine
def process(self, asset):
raise NotImplementedError()
class ExecEngine(BaseEngine):
executable = None
params = []
def __init__(self, executable=None):
if executable is not None:
self.executable = executable
def process(self, asset):
self.asset = asset
p = subprocess.Popen(
args=self.get_args(),
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
output, errors = p.communicate(input=asset.processed_source.encode('utf-8'))
if p.returncode != 0:
raise EngineProcessFailed(errors)
asset.processed_source = output.decode('utf-8')
def get_args(self):
return [self.executable] + self.params
|
Fix unicode support in ExecEngine
|
Fix unicode support in ExecEngine
|
Python
|
isc
|
gears/gears,gears/gears,gears/gears
|
import subprocess
from functools import wraps
class EngineProcessFailed(Exception):
pass
class BaseEngine(object):
result_mimetype = None
@classmethod
def as_engine(cls, **initkwargs):
@wraps(cls, updated=())
def engine(asset):
instance = engine.engine_class(**initkwargs)
return instance.process(asset)
engine.engine_class = cls
engine.result_mimetype = cls.result_mimetype
return engine
def process(self, asset):
raise NotImplementedError()
class ExecEngine(BaseEngine):
executable = None
params = []
def __init__(self, executable=None):
if executable is not None:
self.executable = executable
def process(self, asset):
self.asset = asset
p = subprocess.Popen(
args=self.get_args(),
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
output, errors = p.communicate(input=asset.processed_source)
if p.returncode != 0:
raise EngineProcessFailed(errors)
asset.processed_source = output
def get_args(self):
return [self.executable] + self.params
Fix unicode support in ExecEngine
|
import subprocess
from functools import wraps
class EngineProcessFailed(Exception):
pass
class BaseEngine(object):
result_mimetype = None
@classmethod
def as_engine(cls, **initkwargs):
@wraps(cls, updated=())
def engine(asset):
instance = engine.engine_class(**initkwargs)
return instance.process(asset)
engine.engine_class = cls
engine.result_mimetype = cls.result_mimetype
return engine
def process(self, asset):
raise NotImplementedError()
class ExecEngine(BaseEngine):
executable = None
params = []
def __init__(self, executable=None):
if executable is not None:
self.executable = executable
def process(self, asset):
self.asset = asset
p = subprocess.Popen(
args=self.get_args(),
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
output, errors = p.communicate(input=asset.processed_source.encode('utf-8'))
if p.returncode != 0:
raise EngineProcessFailed(errors)
asset.processed_source = output.decode('utf-8')
def get_args(self):
return [self.executable] + self.params
|
<commit_before>import subprocess
from functools import wraps
class EngineProcessFailed(Exception):
pass
class BaseEngine(object):
result_mimetype = None
@classmethod
def as_engine(cls, **initkwargs):
@wraps(cls, updated=())
def engine(asset):
instance = engine.engine_class(**initkwargs)
return instance.process(asset)
engine.engine_class = cls
engine.result_mimetype = cls.result_mimetype
return engine
def process(self, asset):
raise NotImplementedError()
class ExecEngine(BaseEngine):
executable = None
params = []
def __init__(self, executable=None):
if executable is not None:
self.executable = executable
def process(self, asset):
self.asset = asset
p = subprocess.Popen(
args=self.get_args(),
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
output, errors = p.communicate(input=asset.processed_source)
if p.returncode != 0:
raise EngineProcessFailed(errors)
asset.processed_source = output
def get_args(self):
return [self.executable] + self.params
<commit_msg>Fix unicode support in ExecEngine<commit_after>
|
import subprocess
from functools import wraps
class EngineProcessFailed(Exception):
pass
class BaseEngine(object):
result_mimetype = None
@classmethod
def as_engine(cls, **initkwargs):
@wraps(cls, updated=())
def engine(asset):
instance = engine.engine_class(**initkwargs)
return instance.process(asset)
engine.engine_class = cls
engine.result_mimetype = cls.result_mimetype
return engine
def process(self, asset):
raise NotImplementedError()
class ExecEngine(BaseEngine):
executable = None
params = []
def __init__(self, executable=None):
if executable is not None:
self.executable = executable
def process(self, asset):
self.asset = asset
p = subprocess.Popen(
args=self.get_args(),
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
output, errors = p.communicate(input=asset.processed_source.encode('utf-8'))
if p.returncode != 0:
raise EngineProcessFailed(errors)
asset.processed_source = output.decode('utf-8')
def get_args(self):
return [self.executable] + self.params
|
import subprocess
from functools import wraps
class EngineProcessFailed(Exception):
pass
class BaseEngine(object):
result_mimetype = None
@classmethod
def as_engine(cls, **initkwargs):
@wraps(cls, updated=())
def engine(asset):
instance = engine.engine_class(**initkwargs)
return instance.process(asset)
engine.engine_class = cls
engine.result_mimetype = cls.result_mimetype
return engine
def process(self, asset):
raise NotImplementedError()
class ExecEngine(BaseEngine):
executable = None
params = []
def __init__(self, executable=None):
if executable is not None:
self.executable = executable
def process(self, asset):
self.asset = asset
p = subprocess.Popen(
args=self.get_args(),
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
output, errors = p.communicate(input=asset.processed_source)
if p.returncode != 0:
raise EngineProcessFailed(errors)
asset.processed_source = output
def get_args(self):
return [self.executable] + self.params
Fix unicode support in ExecEngineimport subprocess
from functools import wraps
class EngineProcessFailed(Exception):
pass
class BaseEngine(object):
result_mimetype = None
@classmethod
def as_engine(cls, **initkwargs):
@wraps(cls, updated=())
def engine(asset):
instance = engine.engine_class(**initkwargs)
return instance.process(asset)
engine.engine_class = cls
engine.result_mimetype = cls.result_mimetype
return engine
def process(self, asset):
raise NotImplementedError()
class ExecEngine(BaseEngine):
executable = None
params = []
def __init__(self, executable=None):
if executable is not None:
self.executable = executable
def process(self, asset):
self.asset = asset
p = subprocess.Popen(
args=self.get_args(),
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
output, errors = p.communicate(input=asset.processed_source.encode('utf-8'))
if p.returncode != 0:
raise EngineProcessFailed(errors)
asset.processed_source = output.decode('utf-8')
def get_args(self):
return [self.executable] + self.params
|
<commit_before>import subprocess
from functools import wraps
class EngineProcessFailed(Exception):
pass
class BaseEngine(object):
result_mimetype = None
@classmethod
def as_engine(cls, **initkwargs):
@wraps(cls, updated=())
def engine(asset):
instance = engine.engine_class(**initkwargs)
return instance.process(asset)
engine.engine_class = cls
engine.result_mimetype = cls.result_mimetype
return engine
def process(self, asset):
raise NotImplementedError()
class ExecEngine(BaseEngine):
executable = None
params = []
def __init__(self, executable=None):
if executable is not None:
self.executable = executable
def process(self, asset):
self.asset = asset
p = subprocess.Popen(
args=self.get_args(),
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
output, errors = p.communicate(input=asset.processed_source)
if p.returncode != 0:
raise EngineProcessFailed(errors)
asset.processed_source = output
def get_args(self):
return [self.executable] + self.params
<commit_msg>Fix unicode support in ExecEngine<commit_after>import subprocess
from functools import wraps
class EngineProcessFailed(Exception):
pass
class BaseEngine(object):
result_mimetype = None
@classmethod
def as_engine(cls, **initkwargs):
@wraps(cls, updated=())
def engine(asset):
instance = engine.engine_class(**initkwargs)
return instance.process(asset)
engine.engine_class = cls
engine.result_mimetype = cls.result_mimetype
return engine
def process(self, asset):
raise NotImplementedError()
class ExecEngine(BaseEngine):
executable = None
params = []
def __init__(self, executable=None):
if executable is not None:
self.executable = executable
def process(self, asset):
self.asset = asset
p = subprocess.Popen(
args=self.get_args(),
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
output, errors = p.communicate(input=asset.processed_source.encode('utf-8'))
if p.returncode != 0:
raise EngineProcessFailed(errors)
asset.processed_source = output.decode('utf-8')
def get_args(self):
return [self.executable] + self.params
|
52610add5ae887dcbc06f1435fdff34f182d78c9
|
go/campaigns/forms.py
|
go/campaigns/forms.py
|
from django import forms
class CampaignGeneralForm(forms.Form):
TYPE_CHOICES = (
('', 'Select campaign type'),
('B', 'Bulk Message'),
('C', 'Conversation'),
)
name = forms.CharField(label="Campaign name", max_length=100)
type = forms.ChoiceField(label="Which kind of campaign would you like?",
widget=forms.Select(), choices=TYPE_CHOICES)
class CampaignConfigurationForm(forms.Form):
COUNTRY_CHOICES = (
('.za', 'South Africa'),
)
CHANNEL_CHOICES = (
('ussd', 'USSD'),
)
# more than likely a many to many field, or something similair in the riak
# world. Whom I kidding, this is probably just a modelform?
countries = forms.MultipleChoiceField(label="Destinations",
widget=forms.Select(),
choices=COUNTRY_CHOICES)
channels = forms.MultipleChoiceField(label="Channels",
widget=forms.Select(),
choices=CHANNEL_CHOICES)
keyword = forms.CharField(label="Keyword", max_length=100)
class CampaignBulkMessageForm(forms.Form):
message = forms.CharField(label="Bulk message text", widget=forms.Textarea)
|
from django import forms
class CampaignGeneralForm(forms.Form):
TYPE_CHOICES = (
('', 'Select campaign type'),
('B', 'Bulk Message'),
('D', 'Dialogue'),
)
name = forms.CharField(label="Campaign name", max_length=100)
type = forms.ChoiceField(label="Which kind of campaign would you like?",
widget=forms.Select(), choices=TYPE_CHOICES)
class CampaignConfigurationForm(forms.Form):
COUNTRY_CHOICES = (
('.za', 'South Africa'),
)
CHANNEL_CHOICES = (
('ussd', 'USSD'),
)
# more than likely a many to many field, or something similair in the riak
# world. Whom I kidding, this is probably just a modelform?
countries = forms.MultipleChoiceField(label="Destinations",
widget=forms.Select(),
choices=COUNTRY_CHOICES)
channels = forms.MultipleChoiceField(label="Channels",
widget=forms.Select(),
choices=CHANNEL_CHOICES)
keyword = forms.CharField(label="Keyword", max_length=100)
class CampaignBulkMessageForm(forms.Form):
message = forms.CharField(label="Bulk message text", widget=forms.Textarea)
|
Use dialogue terminology in menu
|
Use dialogue terminology in menu
|
Python
|
bsd-3-clause
|
praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go
|
from django import forms
class CampaignGeneralForm(forms.Form):
TYPE_CHOICES = (
('', 'Select campaign type'),
('B', 'Bulk Message'),
('C', 'Conversation'),
)
name = forms.CharField(label="Campaign name", max_length=100)
type = forms.ChoiceField(label="Which kind of campaign would you like?",
widget=forms.Select(), choices=TYPE_CHOICES)
class CampaignConfigurationForm(forms.Form):
COUNTRY_CHOICES = (
('.za', 'South Africa'),
)
CHANNEL_CHOICES = (
('ussd', 'USSD'),
)
# more than likely a many to many field, or something similair in the riak
# world. Whom I kidding, this is probably just a modelform?
countries = forms.MultipleChoiceField(label="Destinations",
widget=forms.Select(),
choices=COUNTRY_CHOICES)
channels = forms.MultipleChoiceField(label="Channels",
widget=forms.Select(),
choices=CHANNEL_CHOICES)
keyword = forms.CharField(label="Keyword", max_length=100)
class CampaignBulkMessageForm(forms.Form):
message = forms.CharField(label="Bulk message text", widget=forms.Textarea)
Use dialogue terminology in menu
|
from django import forms
class CampaignGeneralForm(forms.Form):
TYPE_CHOICES = (
('', 'Select campaign type'),
('B', 'Bulk Message'),
('D', 'Dialogue'),
)
name = forms.CharField(label="Campaign name", max_length=100)
type = forms.ChoiceField(label="Which kind of campaign would you like?",
widget=forms.Select(), choices=TYPE_CHOICES)
class CampaignConfigurationForm(forms.Form):
COUNTRY_CHOICES = (
('.za', 'South Africa'),
)
CHANNEL_CHOICES = (
('ussd', 'USSD'),
)
# more than likely a many to many field, or something similair in the riak
# world. Whom I kidding, this is probably just a modelform?
countries = forms.MultipleChoiceField(label="Destinations",
widget=forms.Select(),
choices=COUNTRY_CHOICES)
channels = forms.MultipleChoiceField(label="Channels",
widget=forms.Select(),
choices=CHANNEL_CHOICES)
keyword = forms.CharField(label="Keyword", max_length=100)
class CampaignBulkMessageForm(forms.Form):
message = forms.CharField(label="Bulk message text", widget=forms.Textarea)
|
<commit_before>from django import forms
class CampaignGeneralForm(forms.Form):
TYPE_CHOICES = (
('', 'Select campaign type'),
('B', 'Bulk Message'),
('C', 'Conversation'),
)
name = forms.CharField(label="Campaign name", max_length=100)
type = forms.ChoiceField(label="Which kind of campaign would you like?",
widget=forms.Select(), choices=TYPE_CHOICES)
class CampaignConfigurationForm(forms.Form):
COUNTRY_CHOICES = (
('.za', 'South Africa'),
)
CHANNEL_CHOICES = (
('ussd', 'USSD'),
)
# more than likely a many to many field, or something similair in the riak
# world. Whom I kidding, this is probably just a modelform?
countries = forms.MultipleChoiceField(label="Destinations",
widget=forms.Select(),
choices=COUNTRY_CHOICES)
channels = forms.MultipleChoiceField(label="Channels",
widget=forms.Select(),
choices=CHANNEL_CHOICES)
keyword = forms.CharField(label="Keyword", max_length=100)
class CampaignBulkMessageForm(forms.Form):
message = forms.CharField(label="Bulk message text", widget=forms.Textarea)
<commit_msg>Use dialogue terminology in menu<commit_after>
|
from django import forms
class CampaignGeneralForm(forms.Form):
TYPE_CHOICES = (
('', 'Select campaign type'),
('B', 'Bulk Message'),
('D', 'Dialogue'),
)
name = forms.CharField(label="Campaign name", max_length=100)
type = forms.ChoiceField(label="Which kind of campaign would you like?",
widget=forms.Select(), choices=TYPE_CHOICES)
class CampaignConfigurationForm(forms.Form):
COUNTRY_CHOICES = (
('.za', 'South Africa'),
)
CHANNEL_CHOICES = (
('ussd', 'USSD'),
)
# more than likely a many to many field, or something similair in the riak
# world. Whom I kidding, this is probably just a modelform?
countries = forms.MultipleChoiceField(label="Destinations",
widget=forms.Select(),
choices=COUNTRY_CHOICES)
channels = forms.MultipleChoiceField(label="Channels",
widget=forms.Select(),
choices=CHANNEL_CHOICES)
keyword = forms.CharField(label="Keyword", max_length=100)
class CampaignBulkMessageForm(forms.Form):
message = forms.CharField(label="Bulk message text", widget=forms.Textarea)
|
from django import forms
class CampaignGeneralForm(forms.Form):
TYPE_CHOICES = (
('', 'Select campaign type'),
('B', 'Bulk Message'),
('C', 'Conversation'),
)
name = forms.CharField(label="Campaign name", max_length=100)
type = forms.ChoiceField(label="Which kind of campaign would you like?",
widget=forms.Select(), choices=TYPE_CHOICES)
class CampaignConfigurationForm(forms.Form):
COUNTRY_CHOICES = (
('.za', 'South Africa'),
)
CHANNEL_CHOICES = (
('ussd', 'USSD'),
)
# more than likely a many to many field, or something similair in the riak
# world. Whom I kidding, this is probably just a modelform?
countries = forms.MultipleChoiceField(label="Destinations",
widget=forms.Select(),
choices=COUNTRY_CHOICES)
channels = forms.MultipleChoiceField(label="Channels",
widget=forms.Select(),
choices=CHANNEL_CHOICES)
keyword = forms.CharField(label="Keyword", max_length=100)
class CampaignBulkMessageForm(forms.Form):
message = forms.CharField(label="Bulk message text", widget=forms.Textarea)
Use dialogue terminology in menufrom django import forms
class CampaignGeneralForm(forms.Form):
TYPE_CHOICES = (
('', 'Select campaign type'),
('B', 'Bulk Message'),
('D', 'Dialogue'),
)
name = forms.CharField(label="Campaign name", max_length=100)
type = forms.ChoiceField(label="Which kind of campaign would you like?",
widget=forms.Select(), choices=TYPE_CHOICES)
class CampaignConfigurationForm(forms.Form):
COUNTRY_CHOICES = (
('.za', 'South Africa'),
)
CHANNEL_CHOICES = (
('ussd', 'USSD'),
)
# more than likely a many to many field, or something similair in the riak
# world. Whom I kidding, this is probably just a modelform?
countries = forms.MultipleChoiceField(label="Destinations",
widget=forms.Select(),
choices=COUNTRY_CHOICES)
channels = forms.MultipleChoiceField(label="Channels",
widget=forms.Select(),
choices=CHANNEL_CHOICES)
keyword = forms.CharField(label="Keyword", max_length=100)
class CampaignBulkMessageForm(forms.Form):
message = forms.CharField(label="Bulk message text", widget=forms.Textarea)
|
<commit_before>from django import forms
class CampaignGeneralForm(forms.Form):
TYPE_CHOICES = (
('', 'Select campaign type'),
('B', 'Bulk Message'),
('C', 'Conversation'),
)
name = forms.CharField(label="Campaign name", max_length=100)
type = forms.ChoiceField(label="Which kind of campaign would you like?",
widget=forms.Select(), choices=TYPE_CHOICES)
class CampaignConfigurationForm(forms.Form):
COUNTRY_CHOICES = (
('.za', 'South Africa'),
)
CHANNEL_CHOICES = (
('ussd', 'USSD'),
)
# more than likely a many to many field, or something similair in the riak
# world. Whom I kidding, this is probably just a modelform?
countries = forms.MultipleChoiceField(label="Destinations",
widget=forms.Select(),
choices=COUNTRY_CHOICES)
channels = forms.MultipleChoiceField(label="Channels",
widget=forms.Select(),
choices=CHANNEL_CHOICES)
keyword = forms.CharField(label="Keyword", max_length=100)
class CampaignBulkMessageForm(forms.Form):
message = forms.CharField(label="Bulk message text", widget=forms.Textarea)
<commit_msg>Use dialogue terminology in menu<commit_after>from django import forms
class CampaignGeneralForm(forms.Form):
TYPE_CHOICES = (
('', 'Select campaign type'),
('B', 'Bulk Message'),
('D', 'Dialogue'),
)
name = forms.CharField(label="Campaign name", max_length=100)
type = forms.ChoiceField(label="Which kind of campaign would you like?",
widget=forms.Select(), choices=TYPE_CHOICES)
class CampaignConfigurationForm(forms.Form):
COUNTRY_CHOICES = (
('.za', 'South Africa'),
)
CHANNEL_CHOICES = (
('ussd', 'USSD'),
)
# more than likely a many to many field, or something similair in the riak
# world. Whom I kidding, this is probably just a modelform?
countries = forms.MultipleChoiceField(label="Destinations",
widget=forms.Select(),
choices=COUNTRY_CHOICES)
channels = forms.MultipleChoiceField(label="Channels",
widget=forms.Select(),
choices=CHANNEL_CHOICES)
keyword = forms.CharField(label="Keyword", max_length=100)
class CampaignBulkMessageForm(forms.Form):
message = forms.CharField(label="Bulk message text", widget=forms.Textarea)
|
ee2e1727ece6b591b39752a1d3cd6a87d972226d
|
github3/search/code.py
|
github3/search/code.py
|
# -*- coding: utf-8 -*-
from github3.models import GitHubCore
from github3.repos import Repository
class CodeSearchResult(GitHubCore):
def __init__(self, data, session=None):
super(CodeSearchResult, self).__init__(data, session)
self._api = data.get('url')
#: Filename the match occurs in
self.name = data.get('name')
#: Path in the repository to the file
self.path = data.get('path')
#: SHA in which the code can be found
self.sha = data.get('sha')
#: URL to the Git blob endpoint
self.git_url = data.get('git_url')
#: URL to the HTML view of the blob
self.html_url = data.get('html_url')
#: Repository the code snippet belongs to
self.repository = Repository(data.get('repository', {}), self)
#: Score of the result
self.score = data.get('score')
#: Text matches
self.text_matches = data.get('text_matches', [])
|
# -*- coding: utf-8 -*-
from github3.models import GitHubCore
from github3.repos import Repository
class CodeSearchResult(GitHubCore):
def __init__(self, data, session=None):
super(CodeSearchResult, self).__init__(data, session)
self._api = data.get('url')
#: Filename the match occurs in
self.name = data.get('name')
#: Path in the repository to the file
self.path = data.get('path')
#: SHA in which the code can be found
self.sha = data.get('sha')
#: URL to the Git blob endpoint
self.git_url = data.get('git_url')
#: URL to the HTML view of the blob
self.html_url = data.get('html_url')
#: Repository the code snippet belongs to
self.repository = Repository(data.get('repository', {}), self)
#: Score of the result
self.score = data.get('score')
#: Text matches
self.text_matches = data.get('text_matches', [])
def __repr__(self):
return '<CodeSearchResult [{0}]>'.format(self.path)
|
Add a __repr__ for CodeSearchResult
|
Add a __repr__ for CodeSearchResult
|
Python
|
bsd-3-clause
|
h4ck3rm1k3/github3.py,ueg1990/github3.py,degustaf/github3.py,krxsky/github3.py,sigmavirus24/github3.py,itsmemattchung/github3.py,agamdua/github3.py,wbrefvem/github3.py,jim-minter/github3.py,icio/github3.py,christophelec/github3.py,balloob/github3.py
|
# -*- coding: utf-8 -*-
from github3.models import GitHubCore
from github3.repos import Repository
class CodeSearchResult(GitHubCore):
def __init__(self, data, session=None):
super(CodeSearchResult, self).__init__(data, session)
self._api = data.get('url')
#: Filename the match occurs in
self.name = data.get('name')
#: Path in the repository to the file
self.path = data.get('path')
#: SHA in which the code can be found
self.sha = data.get('sha')
#: URL to the Git blob endpoint
self.git_url = data.get('git_url')
#: URL to the HTML view of the blob
self.html_url = data.get('html_url')
#: Repository the code snippet belongs to
self.repository = Repository(data.get('repository', {}), self)
#: Score of the result
self.score = data.get('score')
#: Text matches
self.text_matches = data.get('text_matches', [])
Add a __repr__ for CodeSearchResult
|
# -*- coding: utf-8 -*-
from github3.models import GitHubCore
from github3.repos import Repository
class CodeSearchResult(GitHubCore):
def __init__(self, data, session=None):
super(CodeSearchResult, self).__init__(data, session)
self._api = data.get('url')
#: Filename the match occurs in
self.name = data.get('name')
#: Path in the repository to the file
self.path = data.get('path')
#: SHA in which the code can be found
self.sha = data.get('sha')
#: URL to the Git blob endpoint
self.git_url = data.get('git_url')
#: URL to the HTML view of the blob
self.html_url = data.get('html_url')
#: Repository the code snippet belongs to
self.repository = Repository(data.get('repository', {}), self)
#: Score of the result
self.score = data.get('score')
#: Text matches
self.text_matches = data.get('text_matches', [])
def __repr__(self):
return '<CodeSearchResult [{0}]>'.format(self.path)
|
<commit_before># -*- coding: utf-8 -*-
from github3.models import GitHubCore
from github3.repos import Repository
class CodeSearchResult(GitHubCore):
def __init__(self, data, session=None):
super(CodeSearchResult, self).__init__(data, session)
self._api = data.get('url')
#: Filename the match occurs in
self.name = data.get('name')
#: Path in the repository to the file
self.path = data.get('path')
#: SHA in which the code can be found
self.sha = data.get('sha')
#: URL to the Git blob endpoint
self.git_url = data.get('git_url')
#: URL to the HTML view of the blob
self.html_url = data.get('html_url')
#: Repository the code snippet belongs to
self.repository = Repository(data.get('repository', {}), self)
#: Score of the result
self.score = data.get('score')
#: Text matches
self.text_matches = data.get('text_matches', [])
<commit_msg>Add a __repr__ for CodeSearchResult<commit_after>
|
# -*- coding: utf-8 -*-
from github3.models import GitHubCore
from github3.repos import Repository
class CodeSearchResult(GitHubCore):
def __init__(self, data, session=None):
super(CodeSearchResult, self).__init__(data, session)
self._api = data.get('url')
#: Filename the match occurs in
self.name = data.get('name')
#: Path in the repository to the file
self.path = data.get('path')
#: SHA in which the code can be found
self.sha = data.get('sha')
#: URL to the Git blob endpoint
self.git_url = data.get('git_url')
#: URL to the HTML view of the blob
self.html_url = data.get('html_url')
#: Repository the code snippet belongs to
self.repository = Repository(data.get('repository', {}), self)
#: Score of the result
self.score = data.get('score')
#: Text matches
self.text_matches = data.get('text_matches', [])
def __repr__(self):
return '<CodeSearchResult [{0}]>'.format(self.path)
|
# -*- coding: utf-8 -*-
from github3.models import GitHubCore
from github3.repos import Repository
class CodeSearchResult(GitHubCore):
def __init__(self, data, session=None):
super(CodeSearchResult, self).__init__(data, session)
self._api = data.get('url')
#: Filename the match occurs in
self.name = data.get('name')
#: Path in the repository to the file
self.path = data.get('path')
#: SHA in which the code can be found
self.sha = data.get('sha')
#: URL to the Git blob endpoint
self.git_url = data.get('git_url')
#: URL to the HTML view of the blob
self.html_url = data.get('html_url')
#: Repository the code snippet belongs to
self.repository = Repository(data.get('repository', {}), self)
#: Score of the result
self.score = data.get('score')
#: Text matches
self.text_matches = data.get('text_matches', [])
Add a __repr__ for CodeSearchResult# -*- coding: utf-8 -*-
from github3.models import GitHubCore
from github3.repos import Repository
class CodeSearchResult(GitHubCore):
def __init__(self, data, session=None):
super(CodeSearchResult, self).__init__(data, session)
self._api = data.get('url')
#: Filename the match occurs in
self.name = data.get('name')
#: Path in the repository to the file
self.path = data.get('path')
#: SHA in which the code can be found
self.sha = data.get('sha')
#: URL to the Git blob endpoint
self.git_url = data.get('git_url')
#: URL to the HTML view of the blob
self.html_url = data.get('html_url')
#: Repository the code snippet belongs to
self.repository = Repository(data.get('repository', {}), self)
#: Score of the result
self.score = data.get('score')
#: Text matches
self.text_matches = data.get('text_matches', [])
def __repr__(self):
return '<CodeSearchResult [{0}]>'.format(self.path)
|
<commit_before># -*- coding: utf-8 -*-
from github3.models import GitHubCore
from github3.repos import Repository
class CodeSearchResult(GitHubCore):
def __init__(self, data, session=None):
super(CodeSearchResult, self).__init__(data, session)
self._api = data.get('url')
#: Filename the match occurs in
self.name = data.get('name')
#: Path in the repository to the file
self.path = data.get('path')
#: SHA in which the code can be found
self.sha = data.get('sha')
#: URL to the Git blob endpoint
self.git_url = data.get('git_url')
#: URL to the HTML view of the blob
self.html_url = data.get('html_url')
#: Repository the code snippet belongs to
self.repository = Repository(data.get('repository', {}), self)
#: Score of the result
self.score = data.get('score')
#: Text matches
self.text_matches = data.get('text_matches', [])
<commit_msg>Add a __repr__ for CodeSearchResult<commit_after># -*- coding: utf-8 -*-
from github3.models import GitHubCore
from github3.repos import Repository
class CodeSearchResult(GitHubCore):
def __init__(self, data, session=None):
super(CodeSearchResult, self).__init__(data, session)
self._api = data.get('url')
#: Filename the match occurs in
self.name = data.get('name')
#: Path in the repository to the file
self.path = data.get('path')
#: SHA in which the code can be found
self.sha = data.get('sha')
#: URL to the Git blob endpoint
self.git_url = data.get('git_url')
#: URL to the HTML view of the blob
self.html_url = data.get('html_url')
#: Repository the code snippet belongs to
self.repository = Repository(data.get('repository', {}), self)
#: Score of the result
self.score = data.get('score')
#: Text matches
self.text_matches = data.get('text_matches', [])
def __repr__(self):
return '<CodeSearchResult [{0}]>'.format(self.path)
|
48ab19d9f81fc9973249e600f938586182fe6c7b
|
shop/rest/auth.py
|
shop/rest/auth.py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.template.loader import select_template
from rest_framework.serializers import CharField
from rest_auth import serializers
from shop import settings as shop_settings
class PasswordResetSerializer(serializers.PasswordResetSerializer):
def save(self):
subject_template = select_template([
'{}/email/reset-password-subject.txt'.format(shop_settings.APP_LABEL),
'shop/email/reset-password-subject.txt',
])
body_template = select_template([
'{}/email/reset-password-body.txt'.format(shop_settings.APP_LABEL),
'shop/email/reset-password-body.txt',
])
opts = {
'use_https': self.context['request'].is_secure(),
'from_email': getattr(settings, 'DEFAULT_FROM_EMAIL'),
'request': self.context['request'],
'subject_template_name': subject_template.name,
'email_template_name': body_template.name,
}
self.reset_form.save(**opts)
class PasswordResetConfirmSerializer(serializers.PasswordResetConfirmSerializer):
new_password1 = CharField(min_length=6, max_length=128)
new_password2 = CharField(min_length=6, max_length=128)
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.template.loader import select_template
from rest_framework.serializers import CharField
from rest_auth import serializers
from shop import settings as shop_settings
class PasswordResetSerializer(serializers.PasswordResetSerializer):
def save(self):
subject_template = select_template([
'{}/email/reset-password-subject.txt'.format(shop_settings.APP_LABEL),
'shop/email/reset-password-subject.txt',
])
body_template = select_template([
'{}/email/reset-password-body.txt'.format(shop_settings.APP_LABEL),
'shop/email/reset-password-body.txt',
])
opts = {
'use_https': self.context['request'].is_secure(),
'from_email': getattr(settings, 'DEFAULT_FROM_EMAIL'),
'request': self.context['request'],
'subject_template_name': subject_template.template.name,
'email_template_name': body_template.template.name,
}
self.reset_form.save(**opts)
class PasswordResetConfirmSerializer(serializers.PasswordResetConfirmSerializer):
new_password1 = CharField(min_length=6, max_length=128)
new_password2 = CharField(min_length=6, max_length=128)
|
Fix a failing test for PasswordResetSerializer
|
Fix a failing test for PasswordResetSerializer
It seems that Django's template API changed. This should adjust to that.
|
Python
|
bsd-3-clause
|
awesto/django-shop,nimbis/django-shop,nimbis/django-shop,khchine5/django-shop,jrief/django-shop,rfleschenberg/django-shop,awesto/django-shop,khchine5/django-shop,divio/django-shop,divio/django-shop,nimbis/django-shop,jrief/django-shop,nimbis/django-shop,rfleschenberg/django-shop,jrief/django-shop,rfleschenberg/django-shop,jrief/django-shop,rfleschenberg/django-shop,khchine5/django-shop,khchine5/django-shop,awesto/django-shop,divio/django-shop
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.template.loader import select_template
from rest_framework.serializers import CharField
from rest_auth import serializers
from shop import settings as shop_settings
class PasswordResetSerializer(serializers.PasswordResetSerializer):
def save(self):
subject_template = select_template([
'{}/email/reset-password-subject.txt'.format(shop_settings.APP_LABEL),
'shop/email/reset-password-subject.txt',
])
body_template = select_template([
'{}/email/reset-password-body.txt'.format(shop_settings.APP_LABEL),
'shop/email/reset-password-body.txt',
])
opts = {
'use_https': self.context['request'].is_secure(),
'from_email': getattr(settings, 'DEFAULT_FROM_EMAIL'),
'request': self.context['request'],
'subject_template_name': subject_template.name,
'email_template_name': body_template.name,
}
self.reset_form.save(**opts)
class PasswordResetConfirmSerializer(serializers.PasswordResetConfirmSerializer):
new_password1 = CharField(min_length=6, max_length=128)
new_password2 = CharField(min_length=6, max_length=128)
Fix a failing test for PasswordResetSerializer
It seems that Django's template API changed. This should adjust to that.
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.template.loader import select_template
from rest_framework.serializers import CharField
from rest_auth import serializers
from shop import settings as shop_settings
class PasswordResetSerializer(serializers.PasswordResetSerializer):
def save(self):
subject_template = select_template([
'{}/email/reset-password-subject.txt'.format(shop_settings.APP_LABEL),
'shop/email/reset-password-subject.txt',
])
body_template = select_template([
'{}/email/reset-password-body.txt'.format(shop_settings.APP_LABEL),
'shop/email/reset-password-body.txt',
])
opts = {
'use_https': self.context['request'].is_secure(),
'from_email': getattr(settings, 'DEFAULT_FROM_EMAIL'),
'request': self.context['request'],
'subject_template_name': subject_template.template.name,
'email_template_name': body_template.template.name,
}
self.reset_form.save(**opts)
class PasswordResetConfirmSerializer(serializers.PasswordResetConfirmSerializer):
new_password1 = CharField(min_length=6, max_length=128)
new_password2 = CharField(min_length=6, max_length=128)
|
<commit_before># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.template.loader import select_template
from rest_framework.serializers import CharField
from rest_auth import serializers
from shop import settings as shop_settings
class PasswordResetSerializer(serializers.PasswordResetSerializer):
def save(self):
subject_template = select_template([
'{}/email/reset-password-subject.txt'.format(shop_settings.APP_LABEL),
'shop/email/reset-password-subject.txt',
])
body_template = select_template([
'{}/email/reset-password-body.txt'.format(shop_settings.APP_LABEL),
'shop/email/reset-password-body.txt',
])
opts = {
'use_https': self.context['request'].is_secure(),
'from_email': getattr(settings, 'DEFAULT_FROM_EMAIL'),
'request': self.context['request'],
'subject_template_name': subject_template.name,
'email_template_name': body_template.name,
}
self.reset_form.save(**opts)
class PasswordResetConfirmSerializer(serializers.PasswordResetConfirmSerializer):
new_password1 = CharField(min_length=6, max_length=128)
new_password2 = CharField(min_length=6, max_length=128)
<commit_msg>Fix a failing test for PasswordResetSerializer
It seems that Django's template API changed. This should adjust to that.<commit_after>
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.template.loader import select_template
from rest_framework.serializers import CharField
from rest_auth import serializers
from shop import settings as shop_settings
class PasswordResetSerializer(serializers.PasswordResetSerializer):
def save(self):
subject_template = select_template([
'{}/email/reset-password-subject.txt'.format(shop_settings.APP_LABEL),
'shop/email/reset-password-subject.txt',
])
body_template = select_template([
'{}/email/reset-password-body.txt'.format(shop_settings.APP_LABEL),
'shop/email/reset-password-body.txt',
])
opts = {
'use_https': self.context['request'].is_secure(),
'from_email': getattr(settings, 'DEFAULT_FROM_EMAIL'),
'request': self.context['request'],
'subject_template_name': subject_template.template.name,
'email_template_name': body_template.template.name,
}
self.reset_form.save(**opts)
class PasswordResetConfirmSerializer(serializers.PasswordResetConfirmSerializer):
new_password1 = CharField(min_length=6, max_length=128)
new_password2 = CharField(min_length=6, max_length=128)
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.template.loader import select_template
from rest_framework.serializers import CharField
from rest_auth import serializers
from shop import settings as shop_settings
class PasswordResetSerializer(serializers.PasswordResetSerializer):
def save(self):
subject_template = select_template([
'{}/email/reset-password-subject.txt'.format(shop_settings.APP_LABEL),
'shop/email/reset-password-subject.txt',
])
body_template = select_template([
'{}/email/reset-password-body.txt'.format(shop_settings.APP_LABEL),
'shop/email/reset-password-body.txt',
])
opts = {
'use_https': self.context['request'].is_secure(),
'from_email': getattr(settings, 'DEFAULT_FROM_EMAIL'),
'request': self.context['request'],
'subject_template_name': subject_template.name,
'email_template_name': body_template.name,
}
self.reset_form.save(**opts)
class PasswordResetConfirmSerializer(serializers.PasswordResetConfirmSerializer):
new_password1 = CharField(min_length=6, max_length=128)
new_password2 = CharField(min_length=6, max_length=128)
Fix a failing test for PasswordResetSerializer
It seems that Django's template API changed. This should adjust to that.# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.template.loader import select_template
from rest_framework.serializers import CharField
from rest_auth import serializers
from shop import settings as shop_settings
class PasswordResetSerializer(serializers.PasswordResetSerializer):
def save(self):
subject_template = select_template([
'{}/email/reset-password-subject.txt'.format(shop_settings.APP_LABEL),
'shop/email/reset-password-subject.txt',
])
body_template = select_template([
'{}/email/reset-password-body.txt'.format(shop_settings.APP_LABEL),
'shop/email/reset-password-body.txt',
])
opts = {
'use_https': self.context['request'].is_secure(),
'from_email': getattr(settings, 'DEFAULT_FROM_EMAIL'),
'request': self.context['request'],
'subject_template_name': subject_template.template.name,
'email_template_name': body_template.template.name,
}
self.reset_form.save(**opts)
class PasswordResetConfirmSerializer(serializers.PasswordResetConfirmSerializer):
new_password1 = CharField(min_length=6, max_length=128)
new_password2 = CharField(min_length=6, max_length=128)
|
<commit_before># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.template.loader import select_template
from rest_framework.serializers import CharField
from rest_auth import serializers
from shop import settings as shop_settings
class PasswordResetSerializer(serializers.PasswordResetSerializer):
def save(self):
subject_template = select_template([
'{}/email/reset-password-subject.txt'.format(shop_settings.APP_LABEL),
'shop/email/reset-password-subject.txt',
])
body_template = select_template([
'{}/email/reset-password-body.txt'.format(shop_settings.APP_LABEL),
'shop/email/reset-password-body.txt',
])
opts = {
'use_https': self.context['request'].is_secure(),
'from_email': getattr(settings, 'DEFAULT_FROM_EMAIL'),
'request': self.context['request'],
'subject_template_name': subject_template.name,
'email_template_name': body_template.name,
}
self.reset_form.save(**opts)
class PasswordResetConfirmSerializer(serializers.PasswordResetConfirmSerializer):
new_password1 = CharField(min_length=6, max_length=128)
new_password2 = CharField(min_length=6, max_length=128)
<commit_msg>Fix a failing test for PasswordResetSerializer
It seems that Django's template API changed. This should adjust to that.<commit_after># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.template.loader import select_template
from rest_framework.serializers import CharField
from rest_auth import serializers
from shop import settings as shop_settings
class PasswordResetSerializer(serializers.PasswordResetSerializer):
def save(self):
subject_template = select_template([
'{}/email/reset-password-subject.txt'.format(shop_settings.APP_LABEL),
'shop/email/reset-password-subject.txt',
])
body_template = select_template([
'{}/email/reset-password-body.txt'.format(shop_settings.APP_LABEL),
'shop/email/reset-password-body.txt',
])
opts = {
'use_https': self.context['request'].is_secure(),
'from_email': getattr(settings, 'DEFAULT_FROM_EMAIL'),
'request': self.context['request'],
'subject_template_name': subject_template.template.name,
'email_template_name': body_template.template.name,
}
self.reset_form.save(**opts)
class PasswordResetConfirmSerializer(serializers.PasswordResetConfirmSerializer):
new_password1 = CharField(min_length=6, max_length=128)
new_password2 = CharField(min_length=6, max_length=128)
|
54bf7dd89cd4288d869b94123ce45f3c639ea894
|
website/addons/dropbox/__init__.py
|
website/addons/dropbox/__init__.py
|
from . import model
from . import routes
from . import views
MODELS = [model.AddonDropboxUserSettings] # TODO Other models needed? , model.AddonDropboxNodeSettings, model.DropboxGuidFile]
USER_SETTINGS_MODEL = model.AddonDropboxNodeSettings
#NODE_SETTINGS_MODEL = model.AddonDropboxNodeSettings
ROUTES = [routes.settings_routes, routes.nonapi_routes, routes.api_routes]
SHORT_NAME = 'dropbox'
FULL_NAME = 'Dropbox'
OWNERS = ['user']
ADDED_DEFAULT = []
ADDED_MANDATORY = []
VIEWS = []
CONFIGS = ['user']
CATEGORIES = ['storage']
INCLUDE_JS = {
'widget': [],
'page': [],
'files': []
}
INCLUDE_CSS = {
'widget': [],
'page': [],
}
HAS_HGRID_FILES = True
# GET_HGRID_DATA = TODO
MAX_FILE_SIZE = 5 # MB
|
from . import model
from . import routes
from . import views
MODELS = [model.DropboxUserSettings]
USER_SETTINGS_MODEL = model.DropboxUserSettings
#NODE_SETTINGS_MODEL = model.AddonDropboxNodeSettings
ROUTES = [routes.settings_routes, routes.nonapi_routes, routes.api_routes]
SHORT_NAME = 'dropbox'
FULL_NAME = 'Dropbox'
OWNERS = ['user']
ADDED_DEFAULT = []
ADDED_MANDATORY = []
VIEWS = []
CONFIGS = ['user']
CATEGORIES = ['storage']
INCLUDE_JS = {
'widget': [],
'page': [],
'files': []
}
INCLUDE_CSS = {
'widget': [],
'page': [],
}
HAS_HGRID_FILES = True
# GET_HGRID_DATA = TODO
MAX_FILE_SIZE = 5 # MB
|
Fix settings; tests now passing
|
Fix settings; tests now passing
|
Python
|
apache-2.0
|
rdhyee/osf.io,abought/osf.io,aaxelb/osf.io,billyhunt/osf.io,laurenrevere/osf.io,jnayak1/osf.io,rdhyee/osf.io,monikagrabowska/osf.io,jnayak1/osf.io,felliott/osf.io,lyndsysimon/osf.io,caseyrygt/osf.io,caneruguz/osf.io,jinluyuan/osf.io,baylee-d/osf.io,cslzchen/osf.io,monikagrabowska/osf.io,mattclark/osf.io,brandonPurvis/osf.io,kushG/osf.io,Johnetordoff/osf.io,DanielSBrown/osf.io,samanehsan/osf.io,jeffreyliu3230/osf.io,leb2dg/osf.io,pattisdr/osf.io,adlius/osf.io,cosenal/osf.io,danielneis/osf.io,GaryKriebel/osf.io,aaxelb/osf.io,kwierman/osf.io,GageGaskins/osf.io,AndrewSallans/osf.io,Johnetordoff/osf.io,brandonPurvis/osf.io,TomHeatwole/osf.io,CenterForOpenScience/osf.io,amyshi188/osf.io,chrisseto/osf.io,rdhyee/osf.io,KAsante95/osf.io,leb2dg/osf.io,alexschiller/osf.io,kch8qx/osf.io,samanehsan/osf.io,mfraezz/osf.io,kwierman/osf.io,jinluyuan/osf.io,dplorimer/osf,chennan47/osf.io,amyshi188/osf.io,fabianvf/osf.io,barbour-em/osf.io,Nesiehr/osf.io,baylee-d/osf.io,asanfilippo7/osf.io,acshi/osf.io,wearpants/osf.io,lamdnhan/osf.io,wearpants/osf.io,mluo613/osf.io,DanielSBrown/osf.io,mluke93/osf.io,saradbowman/osf.io,TomHeatwole/osf.io,dplorimer/osf,TomHeatwole/osf.io,erinspace/osf.io,CenterForOpenScience/osf.io,felliott/osf.io,petermalcolm/osf.io,petermalcolm/osf.io,KAsante95/osf.io,binoculars/osf.io,icereval/osf.io,zamattiac/osf.io,Nesiehr/osf.io,icereval/osf.io,bdyetton/prettychart,acshi/osf.io,himanshuo/osf.io,KAsante95/osf.io,TomBaxter/osf.io,rdhyee/osf.io,SSJohns/osf.io,GaryKriebel/osf.io,billyhunt/osf.io,dplorimer/osf,kch8qx/osf.io,HalcyonChimera/osf.io,alexschiller/osf.io,monikagrabowska/osf.io,aaxelb/osf.io,njantrania/osf.io,zkraime/osf.io,jeffreyliu3230/osf.io,felliott/osf.io,crcresearch/osf.io,MerlinZhang/osf.io,leb2dg/osf.io,HalcyonChimera/osf.io,jeffreyliu3230/osf.io,sbt9uc/osf.io,sbt9uc/osf.io,njantrania/osf.io,Johnetordoff/osf.io,RomanZWang/osf.io,haoyuchen1992/osf.io,SSJohns/osf.io,kch8qx/osf.io,alexschiller/osf.io,doublebits/osf.io,lamdnhan/osf.io,zachjanicki/osf.io,bdyetton/prettychart,kch8qx/osf.io,lyndsysimon/osf.io,RomanZWang/osf.io,chrisseto/osf.io,brianjgeiger/osf.io,GageGaskins/osf.io,CenterForOpenScience/osf.io,abought/osf.io,Ghalko/osf.io,laurenrevere/osf.io,billyhunt/osf.io,samchrisinger/osf.io,brianjgeiger/osf.io,ticklemepierce/osf.io,bdyetton/prettychart,GageGaskins/osf.io,asanfilippo7/osf.io,haoyuchen1992/osf.io,erinspace/osf.io,jinluyuan/osf.io,acshi/osf.io,revanthkolli/osf.io,zamattiac/osf.io,arpitar/osf.io,himanshuo/osf.io,mluo613/osf.io,RomanZWang/osf.io,zkraime/osf.io,lamdnhan/osf.io,caseyrollins/osf.io,billyhunt/osf.io,DanielSBrown/osf.io,RomanZWang/osf.io,barbour-em/osf.io,GageGaskins/osf.io,doublebits/osf.io,caseyrygt/osf.io,GageGaskins/osf.io,emetsger/osf.io,jolene-esposito/osf.io,barbour-em/osf.io,cslzchen/osf.io,Nesiehr/osf.io,lyndsysimon/osf.io,samanehsan/osf.io,dplorimer/osf,acshi/osf.io,cwisecarver/osf.io,doublebits/osf.io,TomBaxter/osf.io,TomBaxter/osf.io,ckc6cz/osf.io,ZobairAlijan/osf.io,mluo613/osf.io,alexschiller/osf.io,brandonPurvis/osf.io,MerlinZhang/osf.io,jolene-esposito/osf.io,haoyuchen1992/osf.io,wearpants/osf.io,crcresearch/osf.io,emetsger/osf.io,ZobairAlijan/osf.io,zachjanicki/osf.io,danielneis/osf.io,mluke93/osf.io,reinaH/osf.io,hmoco/osf.io,icereval/osf.io,brianjgeiger/osf.io,cldershem/osf.io,jmcarp/osf.io,caseyrygt/osf.io,ckc6cz/osf.io,jeffreyliu3230/osf.io,cslzchen/osf.io,jolene-esposito/osf.io,brianjgeiger/osf.io,KAsante95/osf.io,binoculars/osf.io,sbt9uc/osf.io,brandonPurvis/osf.io,njantrania/osf.io,cldershem/osf.io,fabianvf/osf.io,RomanZWang/osf.io,petermalcolm/osf.io,arpitar/osf.io,laurenrevere/osf.io,chrisseto/osf.io,emetsger/osf.io,HalcyonChimera/osf.io,arpitar/osf.io,MerlinZhang/osf.io,ZobairAlijan/osf.io,haoyuchen1992/osf.io,adlius/osf.io,caseyrollins/osf.io,kwierman/osf.io,abought/osf.io,cslzchen/osf.io,mattclark/osf.io,revanthkolli/osf.io,crcresearch/osf.io,Nesiehr/osf.io,cwisecarver/osf.io,chrisseto/osf.io,lamdnhan/osf.io,hmoco/osf.io,reinaH/osf.io,doublebits/osf.io,sloria/osf.io,amyshi188/osf.io,cwisecarver/osf.io,zamattiac/osf.io,cosenal/osf.io,asanfilippo7/osf.io,mfraezz/osf.io,zkraime/osf.io,saradbowman/osf.io,SSJohns/osf.io,GaryKriebel/osf.io,aaxelb/osf.io,monikagrabowska/osf.io,acshi/osf.io,caneruguz/osf.io,Ghalko/osf.io,cldershem/osf.io,chennan47/osf.io,adlius/osf.io,cosenal/osf.io,billyhunt/osf.io,mfraezz/osf.io,himanshuo/osf.io,ticklemepierce/osf.io,abought/osf.io,MerlinZhang/osf.io,samchrisinger/osf.io,mfraezz/osf.io,GaryKriebel/osf.io,ckc6cz/osf.io,jmcarp/osf.io,chennan47/osf.io,adlius/osf.io,felliott/osf.io,jmcarp/osf.io,zamattiac/osf.io,jnayak1/osf.io,danielneis/osf.io,revanthkolli/osf.io,wearpants/osf.io,zkraime/osf.io,caseyrygt/osf.io,fabianvf/osf.io,HarryRybacki/osf.io,binoculars/osf.io,cosenal/osf.io,CenterForOpenScience/osf.io,kch8qx/osf.io,KAsante95/osf.io,amyshi188/osf.io,mluo613/osf.io,mluke93/osf.io,DanielSBrown/osf.io,mluo613/osf.io,caseyrollins/osf.io,ckc6cz/osf.io,reinaH/osf.io,jolene-esposito/osf.io,njantrania/osf.io,danielneis/osf.io,hmoco/osf.io,HalcyonChimera/osf.io,Ghalko/osf.io,baylee-d/osf.io,samchrisinger/osf.io,Johnetordoff/osf.io,AndrewSallans/osf.io,hmoco/osf.io,himanshuo/osf.io,cldershem/osf.io,lyndsysimon/osf.io,ZobairAlijan/osf.io,kushG/osf.io,sbt9uc/osf.io,ticklemepierce/osf.io,asanfilippo7/osf.io,bdyetton/prettychart,barbour-em/osf.io,caneruguz/osf.io,revanthkolli/osf.io,caneruguz/osf.io,sloria/osf.io,jnayak1/osf.io,kushG/osf.io,kushG/osf.io,arpitar/osf.io,jinluyuan/osf.io,reinaH/osf.io,Ghalko/osf.io,SSJohns/osf.io,mluke93/osf.io,HarryRybacki/osf.io,erinspace/osf.io,petermalcolm/osf.io,HarryRybacki/osf.io,pattisdr/osf.io,brandonPurvis/osf.io,mattclark/osf.io,samchrisinger/osf.io,jmcarp/osf.io,cwisecarver/osf.io,emetsger/osf.io,samanehsan/osf.io,sloria/osf.io,zachjanicki/osf.io,doublebits/osf.io,TomHeatwole/osf.io,leb2dg/osf.io,HarryRybacki/osf.io,alexschiller/osf.io,zachjanicki/osf.io,pattisdr/osf.io,fabianvf/osf.io,monikagrabowska/osf.io,kwierman/osf.io,ticklemepierce/osf.io
|
from . import model
from . import routes
from . import views
MODELS = [model.AddonDropboxUserSettings] # TODO Other models needed? , model.AddonDropboxNodeSettings, model.DropboxGuidFile]
USER_SETTINGS_MODEL = model.AddonDropboxNodeSettings
#NODE_SETTINGS_MODEL = model.AddonDropboxNodeSettings
ROUTES = [routes.settings_routes, routes.nonapi_routes, routes.api_routes]
SHORT_NAME = 'dropbox'
FULL_NAME = 'Dropbox'
OWNERS = ['user']
ADDED_DEFAULT = []
ADDED_MANDATORY = []
VIEWS = []
CONFIGS = ['user']
CATEGORIES = ['storage']
INCLUDE_JS = {
'widget': [],
'page': [],
'files': []
}
INCLUDE_CSS = {
'widget': [],
'page': [],
}
HAS_HGRID_FILES = True
# GET_HGRID_DATA = TODO
MAX_FILE_SIZE = 5 # MB
Fix settings; tests now passing
|
from . import model
from . import routes
from . import views
MODELS = [model.DropboxUserSettings]
USER_SETTINGS_MODEL = model.DropboxUserSettings
#NODE_SETTINGS_MODEL = model.AddonDropboxNodeSettings
ROUTES = [routes.settings_routes, routes.nonapi_routes, routes.api_routes]
SHORT_NAME = 'dropbox'
FULL_NAME = 'Dropbox'
OWNERS = ['user']
ADDED_DEFAULT = []
ADDED_MANDATORY = []
VIEWS = []
CONFIGS = ['user']
CATEGORIES = ['storage']
INCLUDE_JS = {
'widget': [],
'page': [],
'files': []
}
INCLUDE_CSS = {
'widget': [],
'page': [],
}
HAS_HGRID_FILES = True
# GET_HGRID_DATA = TODO
MAX_FILE_SIZE = 5 # MB
|
<commit_before>from . import model
from . import routes
from . import views
MODELS = [model.AddonDropboxUserSettings] # TODO Other models needed? , model.AddonDropboxNodeSettings, model.DropboxGuidFile]
USER_SETTINGS_MODEL = model.AddonDropboxNodeSettings
#NODE_SETTINGS_MODEL = model.AddonDropboxNodeSettings
ROUTES = [routes.settings_routes, routes.nonapi_routes, routes.api_routes]
SHORT_NAME = 'dropbox'
FULL_NAME = 'Dropbox'
OWNERS = ['user']
ADDED_DEFAULT = []
ADDED_MANDATORY = []
VIEWS = []
CONFIGS = ['user']
CATEGORIES = ['storage']
INCLUDE_JS = {
'widget': [],
'page': [],
'files': []
}
INCLUDE_CSS = {
'widget': [],
'page': [],
}
HAS_HGRID_FILES = True
# GET_HGRID_DATA = TODO
MAX_FILE_SIZE = 5 # MB
<commit_msg>Fix settings; tests now passing<commit_after>
|
from . import model
from . import routes
from . import views
MODELS = [model.DropboxUserSettings]
USER_SETTINGS_MODEL = model.DropboxUserSettings
#NODE_SETTINGS_MODEL = model.AddonDropboxNodeSettings
ROUTES = [routes.settings_routes, routes.nonapi_routes, routes.api_routes]
SHORT_NAME = 'dropbox'
FULL_NAME = 'Dropbox'
OWNERS = ['user']
ADDED_DEFAULT = []
ADDED_MANDATORY = []
VIEWS = []
CONFIGS = ['user']
CATEGORIES = ['storage']
INCLUDE_JS = {
'widget': [],
'page': [],
'files': []
}
INCLUDE_CSS = {
'widget': [],
'page': [],
}
HAS_HGRID_FILES = True
# GET_HGRID_DATA = TODO
MAX_FILE_SIZE = 5 # MB
|
from . import model
from . import routes
from . import views
MODELS = [model.AddonDropboxUserSettings] # TODO Other models needed? , model.AddonDropboxNodeSettings, model.DropboxGuidFile]
USER_SETTINGS_MODEL = model.AddonDropboxNodeSettings
#NODE_SETTINGS_MODEL = model.AddonDropboxNodeSettings
ROUTES = [routes.settings_routes, routes.nonapi_routes, routes.api_routes]
SHORT_NAME = 'dropbox'
FULL_NAME = 'Dropbox'
OWNERS = ['user']
ADDED_DEFAULT = []
ADDED_MANDATORY = []
VIEWS = []
CONFIGS = ['user']
CATEGORIES = ['storage']
INCLUDE_JS = {
'widget': [],
'page': [],
'files': []
}
INCLUDE_CSS = {
'widget': [],
'page': [],
}
HAS_HGRID_FILES = True
# GET_HGRID_DATA = TODO
MAX_FILE_SIZE = 5 # MB
Fix settings; tests now passingfrom . import model
from . import routes
from . import views
MODELS = [model.DropboxUserSettings]
USER_SETTINGS_MODEL = model.DropboxUserSettings
#NODE_SETTINGS_MODEL = model.AddonDropboxNodeSettings
ROUTES = [routes.settings_routes, routes.nonapi_routes, routes.api_routes]
SHORT_NAME = 'dropbox'
FULL_NAME = 'Dropbox'
OWNERS = ['user']
ADDED_DEFAULT = []
ADDED_MANDATORY = []
VIEWS = []
CONFIGS = ['user']
CATEGORIES = ['storage']
INCLUDE_JS = {
'widget': [],
'page': [],
'files': []
}
INCLUDE_CSS = {
'widget': [],
'page': [],
}
HAS_HGRID_FILES = True
# GET_HGRID_DATA = TODO
MAX_FILE_SIZE = 5 # MB
|
<commit_before>from . import model
from . import routes
from . import views
MODELS = [model.AddonDropboxUserSettings] # TODO Other models needed? , model.AddonDropboxNodeSettings, model.DropboxGuidFile]
USER_SETTINGS_MODEL = model.AddonDropboxNodeSettings
#NODE_SETTINGS_MODEL = model.AddonDropboxNodeSettings
ROUTES = [routes.settings_routes, routes.nonapi_routes, routes.api_routes]
SHORT_NAME = 'dropbox'
FULL_NAME = 'Dropbox'
OWNERS = ['user']
ADDED_DEFAULT = []
ADDED_MANDATORY = []
VIEWS = []
CONFIGS = ['user']
CATEGORIES = ['storage']
INCLUDE_JS = {
'widget': [],
'page': [],
'files': []
}
INCLUDE_CSS = {
'widget': [],
'page': [],
}
HAS_HGRID_FILES = True
# GET_HGRID_DATA = TODO
MAX_FILE_SIZE = 5 # MB
<commit_msg>Fix settings; tests now passing<commit_after>from . import model
from . import routes
from . import views
MODELS = [model.DropboxUserSettings]
USER_SETTINGS_MODEL = model.DropboxUserSettings
#NODE_SETTINGS_MODEL = model.AddonDropboxNodeSettings
ROUTES = [routes.settings_routes, routes.nonapi_routes, routes.api_routes]
SHORT_NAME = 'dropbox'
FULL_NAME = 'Dropbox'
OWNERS = ['user']
ADDED_DEFAULT = []
ADDED_MANDATORY = []
VIEWS = []
CONFIGS = ['user']
CATEGORIES = ['storage']
INCLUDE_JS = {
'widget': [],
'page': [],
'files': []
}
INCLUDE_CSS = {
'widget': [],
'page': [],
}
HAS_HGRID_FILES = True
# GET_HGRID_DATA = TODO
MAX_FILE_SIZE = 5 # MB
|
a854c1564f581bda5c355d97069d775485a65047
|
installer/steps/a_setup_virtualenv.py
|
installer/steps/a_setup_virtualenv.py
|
import os
import re
from helper import *
import unix_windows
section("Preparing virtualenv")
# check that virtualenv installed
if not executable_exists('virtualenv'):
fail("""\
Please install virtualenv!
https://github.com/pypa/virtualenv
{}""".format(unix_windows.VIRTUALENV_INSTALL_MSG))
# Make sure that not running in virtualenv
if hasattr(sys, 'real_prefix'):
fail("""Please exit virtualenv!""")
# Check if 'env' already exists + is virtualenv
virtualenv_exists = False
if os.path.isdir("env"):
if shell(unix_windows.VIRTUALENV_CMD).success():
virtualenv_exists = True
# Create virtualenv if necessary
if not virtualenv_exists:
shell("virtualenv env --python=python3").should_not_fail()
|
import os
import re
from helper import *
import unix_windows
section("Preparing virtualenv")
# check that virtualenv installed
if not executable_exists('virtualenv'):
fail("""\
Please install virtualenv!
https://github.com/pypa/virtualenv
{}""".format(unix_windows.VIRTUALENV_INSTALL_MSG))
# Make sure that not running in virtualenv
if hasattr(sys, 'real_prefix'):
fail("""Please exit virtualenv!""")
# Check if 'env' already exists + is virtualenv
virtualenv_exists = False
if os.path.isdir("env"):
if shell(unix_windows.VIRTUALENV_CMD).success():
virtualenv_exists = True
# Create virtualenv if necessary
if not virtualenv_exists:
if unix_windows.IS_WIN:
shell("virtualenv env").should_not_fail()
else:
shell("virtualenv env --python=python3").should_not_fail()
|
Fix python path for windows
|
Fix python path for windows
|
Python
|
mit
|
appi147/Jarvis,sukeesh/Jarvis,appi147/Jarvis,sukeesh/Jarvis,sukeesh/Jarvis,sukeesh/Jarvis
|
import os
import re
from helper import *
import unix_windows
section("Preparing virtualenv")
# check that virtualenv installed
if not executable_exists('virtualenv'):
fail("""\
Please install virtualenv!
https://github.com/pypa/virtualenv
{}""".format(unix_windows.VIRTUALENV_INSTALL_MSG))
# Make sure that not running in virtualenv
if hasattr(sys, 'real_prefix'):
fail("""Please exit virtualenv!""")
# Check if 'env' already exists + is virtualenv
virtualenv_exists = False
if os.path.isdir("env"):
if shell(unix_windows.VIRTUALENV_CMD).success():
virtualenv_exists = True
# Create virtualenv if necessary
if not virtualenv_exists:
shell("virtualenv env --python=python3").should_not_fail()
Fix python path for windows
|
import os
import re
from helper import *
import unix_windows
section("Preparing virtualenv")
# check that virtualenv installed
if not executable_exists('virtualenv'):
fail("""\
Please install virtualenv!
https://github.com/pypa/virtualenv
{}""".format(unix_windows.VIRTUALENV_INSTALL_MSG))
# Make sure that not running in virtualenv
if hasattr(sys, 'real_prefix'):
fail("""Please exit virtualenv!""")
# Check if 'env' already exists + is virtualenv
virtualenv_exists = False
if os.path.isdir("env"):
if shell(unix_windows.VIRTUALENV_CMD).success():
virtualenv_exists = True
# Create virtualenv if necessary
if not virtualenv_exists:
if unix_windows.IS_WIN:
shell("virtualenv env").should_not_fail()
else:
shell("virtualenv env --python=python3").should_not_fail()
|
<commit_before>import os
import re
from helper import *
import unix_windows
section("Preparing virtualenv")
# check that virtualenv installed
if not executable_exists('virtualenv'):
fail("""\
Please install virtualenv!
https://github.com/pypa/virtualenv
{}""".format(unix_windows.VIRTUALENV_INSTALL_MSG))
# Make sure that not running in virtualenv
if hasattr(sys, 'real_prefix'):
fail("""Please exit virtualenv!""")
# Check if 'env' already exists + is virtualenv
virtualenv_exists = False
if os.path.isdir("env"):
if shell(unix_windows.VIRTUALENV_CMD).success():
virtualenv_exists = True
# Create virtualenv if necessary
if not virtualenv_exists:
shell("virtualenv env --python=python3").should_not_fail()
<commit_msg>Fix python path for windows<commit_after>
|
import os
import re
from helper import *
import unix_windows
section("Preparing virtualenv")
# check that virtualenv installed
if not executable_exists('virtualenv'):
fail("""\
Please install virtualenv!
https://github.com/pypa/virtualenv
{}""".format(unix_windows.VIRTUALENV_INSTALL_MSG))
# Make sure that not running in virtualenv
if hasattr(sys, 'real_prefix'):
fail("""Please exit virtualenv!""")
# Check if 'env' already exists + is virtualenv
virtualenv_exists = False
if os.path.isdir("env"):
if shell(unix_windows.VIRTUALENV_CMD).success():
virtualenv_exists = True
# Create virtualenv if necessary
if not virtualenv_exists:
if unix_windows.IS_WIN:
shell("virtualenv env").should_not_fail()
else:
shell("virtualenv env --python=python3").should_not_fail()
|
import os
import re
from helper import *
import unix_windows
section("Preparing virtualenv")
# check that virtualenv installed
if not executable_exists('virtualenv'):
fail("""\
Please install virtualenv!
https://github.com/pypa/virtualenv
{}""".format(unix_windows.VIRTUALENV_INSTALL_MSG))
# Make sure that not running in virtualenv
if hasattr(sys, 'real_prefix'):
fail("""Please exit virtualenv!""")
# Check if 'env' already exists + is virtualenv
virtualenv_exists = False
if os.path.isdir("env"):
if shell(unix_windows.VIRTUALENV_CMD).success():
virtualenv_exists = True
# Create virtualenv if necessary
if not virtualenv_exists:
shell("virtualenv env --python=python3").should_not_fail()
Fix python path for windowsimport os
import re
from helper import *
import unix_windows
section("Preparing virtualenv")
# check that virtualenv installed
if not executable_exists('virtualenv'):
fail("""\
Please install virtualenv!
https://github.com/pypa/virtualenv
{}""".format(unix_windows.VIRTUALENV_INSTALL_MSG))
# Make sure that not running in virtualenv
if hasattr(sys, 'real_prefix'):
fail("""Please exit virtualenv!""")
# Check if 'env' already exists + is virtualenv
virtualenv_exists = False
if os.path.isdir("env"):
if shell(unix_windows.VIRTUALENV_CMD).success():
virtualenv_exists = True
# Create virtualenv if necessary
if not virtualenv_exists:
if unix_windows.IS_WIN:
shell("virtualenv env").should_not_fail()
else:
shell("virtualenv env --python=python3").should_not_fail()
|
<commit_before>import os
import re
from helper import *
import unix_windows
section("Preparing virtualenv")
# check that virtualenv installed
if not executable_exists('virtualenv'):
fail("""\
Please install virtualenv!
https://github.com/pypa/virtualenv
{}""".format(unix_windows.VIRTUALENV_INSTALL_MSG))
# Make sure that not running in virtualenv
if hasattr(sys, 'real_prefix'):
fail("""Please exit virtualenv!""")
# Check if 'env' already exists + is virtualenv
virtualenv_exists = False
if os.path.isdir("env"):
if shell(unix_windows.VIRTUALENV_CMD).success():
virtualenv_exists = True
# Create virtualenv if necessary
if not virtualenv_exists:
shell("virtualenv env --python=python3").should_not_fail()
<commit_msg>Fix python path for windows<commit_after>import os
import re
from helper import *
import unix_windows
section("Preparing virtualenv")
# check that virtualenv installed
if not executable_exists('virtualenv'):
fail("""\
Please install virtualenv!
https://github.com/pypa/virtualenv
{}""".format(unix_windows.VIRTUALENV_INSTALL_MSG))
# Make sure that not running in virtualenv
if hasattr(sys, 'real_prefix'):
fail("""Please exit virtualenv!""")
# Check if 'env' already exists + is virtualenv
virtualenv_exists = False
if os.path.isdir("env"):
if shell(unix_windows.VIRTUALENV_CMD).success():
virtualenv_exists = True
# Create virtualenv if necessary
if not virtualenv_exists:
if unix_windows.IS_WIN:
shell("virtualenv env").should_not_fail()
else:
shell("virtualenv env --python=python3").should_not_fail()
|
652bca441489dd49552cbd5945605d51921394f0
|
snowfloat/settings.py
|
snowfloat/settings.py
|
"""Client global settings."""
HOST = 'api.snowfloat.com:443'
HTTP_TIMEOUT = 10
HTTP_RETRIES = 3
HTTP_RETRY_INTERVAL = 5
API_KEY = ''
API_PRIVATE_KEY = ''
try:
# pylint: disable=F0401
from settings_prod import *
except ImportError:
try:
# pylint: disable=F0401
from settings_dev import *
except ImportError:
pass
|
"""Client global settings."""
import os
import ConfigParser
HOST = 'api.snowfloat.com:443'
HTTP_TIMEOUT = 10
HTTP_RETRIES = 3
HTTP_RETRY_INTERVAL = 5
API_KEY = ''
API_PRIVATE_KEY = ''
CONFIG = ConfigParser.RawConfigParser()
for loc in (os.curdir, os.path.expanduser("~"), "/etc/snowfloat"):
try:
with open(os.path.join(loc, "snowfloat.conf")) as source:
CONFIG.readfp(source)
API_KEY = CONFIG.get('snowfloat', 'api_key')
API_PRIVATE_KEY = CONFIG.get('snowfloat', 'api_private_key')
break
except IOError:
pass
|
Read config file in different locations and set global config variables based on that.
|
Read config file in different locations and set global config variables based on that.
|
Python
|
bsd-3-clause
|
snowfloat/snowfloat-python,snowfloat/snowfloat-python
|
"""Client global settings."""
HOST = 'api.snowfloat.com:443'
HTTP_TIMEOUT = 10
HTTP_RETRIES = 3
HTTP_RETRY_INTERVAL = 5
API_KEY = ''
API_PRIVATE_KEY = ''
try:
# pylint: disable=F0401
from settings_prod import *
except ImportError:
try:
# pylint: disable=F0401
from settings_dev import *
except ImportError:
pass
Read config file in different locations and set global config variables based on that.
|
"""Client global settings."""
import os
import ConfigParser
HOST = 'api.snowfloat.com:443'
HTTP_TIMEOUT = 10
HTTP_RETRIES = 3
HTTP_RETRY_INTERVAL = 5
API_KEY = ''
API_PRIVATE_KEY = ''
CONFIG = ConfigParser.RawConfigParser()
for loc in (os.curdir, os.path.expanduser("~"), "/etc/snowfloat"):
try:
with open(os.path.join(loc, "snowfloat.conf")) as source:
CONFIG.readfp(source)
API_KEY = CONFIG.get('snowfloat', 'api_key')
API_PRIVATE_KEY = CONFIG.get('snowfloat', 'api_private_key')
break
except IOError:
pass
|
<commit_before>"""Client global settings."""
HOST = 'api.snowfloat.com:443'
HTTP_TIMEOUT = 10
HTTP_RETRIES = 3
HTTP_RETRY_INTERVAL = 5
API_KEY = ''
API_PRIVATE_KEY = ''
try:
# pylint: disable=F0401
from settings_prod import *
except ImportError:
try:
# pylint: disable=F0401
from settings_dev import *
except ImportError:
pass
<commit_msg>Read config file in different locations and set global config variables based on that.<commit_after>
|
"""Client global settings."""
import os
import ConfigParser
HOST = 'api.snowfloat.com:443'
HTTP_TIMEOUT = 10
HTTP_RETRIES = 3
HTTP_RETRY_INTERVAL = 5
API_KEY = ''
API_PRIVATE_KEY = ''
CONFIG = ConfigParser.RawConfigParser()
for loc in (os.curdir, os.path.expanduser("~"), "/etc/snowfloat"):
try:
with open(os.path.join(loc, "snowfloat.conf")) as source:
CONFIG.readfp(source)
API_KEY = CONFIG.get('snowfloat', 'api_key')
API_PRIVATE_KEY = CONFIG.get('snowfloat', 'api_private_key')
break
except IOError:
pass
|
"""Client global settings."""
HOST = 'api.snowfloat.com:443'
HTTP_TIMEOUT = 10
HTTP_RETRIES = 3
HTTP_RETRY_INTERVAL = 5
API_KEY = ''
API_PRIVATE_KEY = ''
try:
# pylint: disable=F0401
from settings_prod import *
except ImportError:
try:
# pylint: disable=F0401
from settings_dev import *
except ImportError:
pass
Read config file in different locations and set global config variables based on that."""Client global settings."""
import os
import ConfigParser
HOST = 'api.snowfloat.com:443'
HTTP_TIMEOUT = 10
HTTP_RETRIES = 3
HTTP_RETRY_INTERVAL = 5
API_KEY = ''
API_PRIVATE_KEY = ''
CONFIG = ConfigParser.RawConfigParser()
for loc in (os.curdir, os.path.expanduser("~"), "/etc/snowfloat"):
try:
with open(os.path.join(loc, "snowfloat.conf")) as source:
CONFIG.readfp(source)
API_KEY = CONFIG.get('snowfloat', 'api_key')
API_PRIVATE_KEY = CONFIG.get('snowfloat', 'api_private_key')
break
except IOError:
pass
|
<commit_before>"""Client global settings."""
HOST = 'api.snowfloat.com:443'
HTTP_TIMEOUT = 10
HTTP_RETRIES = 3
HTTP_RETRY_INTERVAL = 5
API_KEY = ''
API_PRIVATE_KEY = ''
try:
# pylint: disable=F0401
from settings_prod import *
except ImportError:
try:
# pylint: disable=F0401
from settings_dev import *
except ImportError:
pass
<commit_msg>Read config file in different locations and set global config variables based on that.<commit_after>"""Client global settings."""
import os
import ConfigParser
HOST = 'api.snowfloat.com:443'
HTTP_TIMEOUT = 10
HTTP_RETRIES = 3
HTTP_RETRY_INTERVAL = 5
API_KEY = ''
API_PRIVATE_KEY = ''
CONFIG = ConfigParser.RawConfigParser()
for loc in (os.curdir, os.path.expanduser("~"), "/etc/snowfloat"):
try:
with open(os.path.join(loc, "snowfloat.conf")) as source:
CONFIG.readfp(source)
API_KEY = CONFIG.get('snowfloat', 'api_key')
API_PRIVATE_KEY = CONFIG.get('snowfloat', 'api_private_key')
break
except IOError:
pass
|
2fe37e7c46671a2ba9039f20c63930de2aaa0576
|
src/cutecoin/tools/decorators.py
|
src/cutecoin/tools/decorators.py
|
import asyncio
import functools
import logging
def cancel_once_task(object, fn):
if getattr(object, "__tasks", None):
tasks = getattr(object, "__tasks")
if fn.__name__ in tasks and not tasks[fn.__name__].done():
getattr(object, "__tasks")[fn.__name__].cancel()
def once_at_a_time(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
if getattr(args[0], "__tasks", None) is None:
setattr(args[0], "__tasks", {})
if fn.__name__ in args[0].__tasks:
if not args[0].__tasks[fn.__name__].done():
args[0].__tasks[fn.__name__].cancel()
try:
args[0].__tasks[fn.__name__] = fn(*args, **kwargs)
except asyncio.CancelledError:
logging.debug("Cancelled asyncified : {0}".format(fn.__name__))
return args[0].__tasks[fn.__name__]
return wrapper
def asyncify(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
return asyncio.async(asyncio.coroutine(fn)(*args, **kwargs))
return wrapper
|
import asyncio
import functools
import logging
def cancel_once_task(object, fn):
if getattr(object, "__tasks", None):
tasks = getattr(object, "__tasks")
if fn.__name__ in tasks and not tasks[fn.__name__].done():
getattr(object, "__tasks")[fn.__name__].cancel()
def once_at_a_time(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
def task_done(task):
try:
args[0].__tasks.pop(fn.__name__)
except KeyError:
logging.debug("Task already removed")
if getattr(args[0], "__tasks", None) is None:
setattr(args[0], "__tasks", {})
if fn.__name__ in args[0].__tasks:
if not args[0].__tasks[fn.__name__].done():
args[0].__tasks[fn.__name__].cancel()
try:
args[0].__tasks[fn.__name__] = fn(*args, **kwargs)
args[0].__tasks[fn.__name__].add_done_callback(task_done)
except asyncio.CancelledError:
logging.debug("Cancelled asyncified : {0}".format(fn.__name__))
return args[0].__tasks[fn.__name__]
return wrapper
def asyncify(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
return asyncio.async(asyncio.coroutine(fn)(*args, **kwargs))
return wrapper
|
Fix bug with exception never handled in once_at_a_time coroutines
|
Fix bug with exception never handled in once_at_a_time coroutines
|
Python
|
mit
|
ucoin-io/cutecoin,ucoin-io/cutecoin,ucoin-io/cutecoin
|
import asyncio
import functools
import logging
def cancel_once_task(object, fn):
if getattr(object, "__tasks", None):
tasks = getattr(object, "__tasks")
if fn.__name__ in tasks and not tasks[fn.__name__].done():
getattr(object, "__tasks")[fn.__name__].cancel()
def once_at_a_time(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
if getattr(args[0], "__tasks", None) is None:
setattr(args[0], "__tasks", {})
if fn.__name__ in args[0].__tasks:
if not args[0].__tasks[fn.__name__].done():
args[0].__tasks[fn.__name__].cancel()
try:
args[0].__tasks[fn.__name__] = fn(*args, **kwargs)
except asyncio.CancelledError:
logging.debug("Cancelled asyncified : {0}".format(fn.__name__))
return args[0].__tasks[fn.__name__]
return wrapper
def asyncify(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
return asyncio.async(asyncio.coroutine(fn)(*args, **kwargs))
return wrapper
Fix bug with exception never handled in once_at_a_time coroutines
|
import asyncio
import functools
import logging
def cancel_once_task(object, fn):
if getattr(object, "__tasks", None):
tasks = getattr(object, "__tasks")
if fn.__name__ in tasks and not tasks[fn.__name__].done():
getattr(object, "__tasks")[fn.__name__].cancel()
def once_at_a_time(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
def task_done(task):
try:
args[0].__tasks.pop(fn.__name__)
except KeyError:
logging.debug("Task already removed")
if getattr(args[0], "__tasks", None) is None:
setattr(args[0], "__tasks", {})
if fn.__name__ in args[0].__tasks:
if not args[0].__tasks[fn.__name__].done():
args[0].__tasks[fn.__name__].cancel()
try:
args[0].__tasks[fn.__name__] = fn(*args, **kwargs)
args[0].__tasks[fn.__name__].add_done_callback(task_done)
except asyncio.CancelledError:
logging.debug("Cancelled asyncified : {0}".format(fn.__name__))
return args[0].__tasks[fn.__name__]
return wrapper
def asyncify(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
return asyncio.async(asyncio.coroutine(fn)(*args, **kwargs))
return wrapper
|
<commit_before>import asyncio
import functools
import logging
def cancel_once_task(object, fn):
if getattr(object, "__tasks", None):
tasks = getattr(object, "__tasks")
if fn.__name__ in tasks and not tasks[fn.__name__].done():
getattr(object, "__tasks")[fn.__name__].cancel()
def once_at_a_time(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
if getattr(args[0], "__tasks", None) is None:
setattr(args[0], "__tasks", {})
if fn.__name__ in args[0].__tasks:
if not args[0].__tasks[fn.__name__].done():
args[0].__tasks[fn.__name__].cancel()
try:
args[0].__tasks[fn.__name__] = fn(*args, **kwargs)
except asyncio.CancelledError:
logging.debug("Cancelled asyncified : {0}".format(fn.__name__))
return args[0].__tasks[fn.__name__]
return wrapper
def asyncify(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
return asyncio.async(asyncio.coroutine(fn)(*args, **kwargs))
return wrapper
<commit_msg>Fix bug with exception never handled in once_at_a_time coroutines<commit_after>
|
import asyncio
import functools
import logging
def cancel_once_task(object, fn):
if getattr(object, "__tasks", None):
tasks = getattr(object, "__tasks")
if fn.__name__ in tasks and not tasks[fn.__name__].done():
getattr(object, "__tasks")[fn.__name__].cancel()
def once_at_a_time(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
def task_done(task):
try:
args[0].__tasks.pop(fn.__name__)
except KeyError:
logging.debug("Task already removed")
if getattr(args[0], "__tasks", None) is None:
setattr(args[0], "__tasks", {})
if fn.__name__ in args[0].__tasks:
if not args[0].__tasks[fn.__name__].done():
args[0].__tasks[fn.__name__].cancel()
try:
args[0].__tasks[fn.__name__] = fn(*args, **kwargs)
args[0].__tasks[fn.__name__].add_done_callback(task_done)
except asyncio.CancelledError:
logging.debug("Cancelled asyncified : {0}".format(fn.__name__))
return args[0].__tasks[fn.__name__]
return wrapper
def asyncify(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
return asyncio.async(asyncio.coroutine(fn)(*args, **kwargs))
return wrapper
|
import asyncio
import functools
import logging
def cancel_once_task(object, fn):
if getattr(object, "__tasks", None):
tasks = getattr(object, "__tasks")
if fn.__name__ in tasks and not tasks[fn.__name__].done():
getattr(object, "__tasks")[fn.__name__].cancel()
def once_at_a_time(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
if getattr(args[0], "__tasks", None) is None:
setattr(args[0], "__tasks", {})
if fn.__name__ in args[0].__tasks:
if not args[0].__tasks[fn.__name__].done():
args[0].__tasks[fn.__name__].cancel()
try:
args[0].__tasks[fn.__name__] = fn(*args, **kwargs)
except asyncio.CancelledError:
logging.debug("Cancelled asyncified : {0}".format(fn.__name__))
return args[0].__tasks[fn.__name__]
return wrapper
def asyncify(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
return asyncio.async(asyncio.coroutine(fn)(*args, **kwargs))
return wrapper
Fix bug with exception never handled in once_at_a_time coroutinesimport asyncio
import functools
import logging
def cancel_once_task(object, fn):
if getattr(object, "__tasks", None):
tasks = getattr(object, "__tasks")
if fn.__name__ in tasks and not tasks[fn.__name__].done():
getattr(object, "__tasks")[fn.__name__].cancel()
def once_at_a_time(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
def task_done(task):
try:
args[0].__tasks.pop(fn.__name__)
except KeyError:
logging.debug("Task already removed")
if getattr(args[0], "__tasks", None) is None:
setattr(args[0], "__tasks", {})
if fn.__name__ in args[0].__tasks:
if not args[0].__tasks[fn.__name__].done():
args[0].__tasks[fn.__name__].cancel()
try:
args[0].__tasks[fn.__name__] = fn(*args, **kwargs)
args[0].__tasks[fn.__name__].add_done_callback(task_done)
except asyncio.CancelledError:
logging.debug("Cancelled asyncified : {0}".format(fn.__name__))
return args[0].__tasks[fn.__name__]
return wrapper
def asyncify(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
return asyncio.async(asyncio.coroutine(fn)(*args, **kwargs))
return wrapper
|
<commit_before>import asyncio
import functools
import logging
def cancel_once_task(object, fn):
if getattr(object, "__tasks", None):
tasks = getattr(object, "__tasks")
if fn.__name__ in tasks and not tasks[fn.__name__].done():
getattr(object, "__tasks")[fn.__name__].cancel()
def once_at_a_time(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
if getattr(args[0], "__tasks", None) is None:
setattr(args[0], "__tasks", {})
if fn.__name__ in args[0].__tasks:
if not args[0].__tasks[fn.__name__].done():
args[0].__tasks[fn.__name__].cancel()
try:
args[0].__tasks[fn.__name__] = fn(*args, **kwargs)
except asyncio.CancelledError:
logging.debug("Cancelled asyncified : {0}".format(fn.__name__))
return args[0].__tasks[fn.__name__]
return wrapper
def asyncify(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
return asyncio.async(asyncio.coroutine(fn)(*args, **kwargs))
return wrapper
<commit_msg>Fix bug with exception never handled in once_at_a_time coroutines<commit_after>import asyncio
import functools
import logging
def cancel_once_task(object, fn):
if getattr(object, "__tasks", None):
tasks = getattr(object, "__tasks")
if fn.__name__ in tasks and not tasks[fn.__name__].done():
getattr(object, "__tasks")[fn.__name__].cancel()
def once_at_a_time(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
def task_done(task):
try:
args[0].__tasks.pop(fn.__name__)
except KeyError:
logging.debug("Task already removed")
if getattr(args[0], "__tasks", None) is None:
setattr(args[0], "__tasks", {})
if fn.__name__ in args[0].__tasks:
if not args[0].__tasks[fn.__name__].done():
args[0].__tasks[fn.__name__].cancel()
try:
args[0].__tasks[fn.__name__] = fn(*args, **kwargs)
args[0].__tasks[fn.__name__].add_done_callback(task_done)
except asyncio.CancelledError:
logging.debug("Cancelled asyncified : {0}".format(fn.__name__))
return args[0].__tasks[fn.__name__]
return wrapper
def asyncify(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
return asyncio.async(asyncio.coroutine(fn)(*args, **kwargs))
return wrapper
|
dbf147b4842edd96842fa384b594265daf0c555e
|
byceps/util/system.py
|
byceps/util/system.py
|
"""
byceps.util.system
~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
import os
import sys
CONFIG_VAR_NAME = 'BYCEPS_CONFIG'
def get_config_filename_from_env() -> str:
"""Return the configuration filename set via environment variable.
Raise an exception if it isn't set.
"""
env = os.environ.get(CONFIG_VAR_NAME)
if not env:
raise Exception(
"No configuration file was specified via the '{}' "
"environment variable.".format(CONFIG_VAR_NAME))
return env
def get_config_filename_from_env_or_exit() -> str:
"""Return the configuration filename set via environment variable.
Exit if it isn't set.
"""
try:
return get_config_filename_from_env()
except Exception as e:
sys.stderr.write("{}\n".format(e))
sys.exit(1)
|
"""
byceps.util.system
~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
import os
import sys
from ..config import ConfigurationError
CONFIG_VAR_NAME = 'BYCEPS_CONFIG'
def get_config_filename_from_env() -> str:
"""Return the configuration filename set via environment variable.
Raise an exception if it isn't set.
"""
env = os.environ.get(CONFIG_VAR_NAME)
if not env:
raise ConfigurationError(
"No configuration file was specified via the '{}' "
"environment variable.".format(CONFIG_VAR_NAME))
return env
def get_config_filename_from_env_or_exit() -> str:
"""Return the configuration filename set via environment variable.
Exit if it isn't set.
"""
try:
return get_config_filename_from_env()
except ConfigurationError as e:
sys.stderr.write("{}\n".format(e))
sys.exit(1)
|
Raise `ConfigurationError` instead of `Exception` if environment variable `BYCEPS_CONFIG` is not set
|
Raise `ConfigurationError` instead of `Exception` if environment variable `BYCEPS_CONFIG` is not set
|
Python
|
bsd-3-clause
|
homeworkprod/byceps,m-ober/byceps,m-ober/byceps,homeworkprod/byceps,m-ober/byceps,homeworkprod/byceps
|
"""
byceps.util.system
~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
import os
import sys
CONFIG_VAR_NAME = 'BYCEPS_CONFIG'
def get_config_filename_from_env() -> str:
"""Return the configuration filename set via environment variable.
Raise an exception if it isn't set.
"""
env = os.environ.get(CONFIG_VAR_NAME)
if not env:
raise Exception(
"No configuration file was specified via the '{}' "
"environment variable.".format(CONFIG_VAR_NAME))
return env
def get_config_filename_from_env_or_exit() -> str:
"""Return the configuration filename set via environment variable.
Exit if it isn't set.
"""
try:
return get_config_filename_from_env()
except Exception as e:
sys.stderr.write("{}\n".format(e))
sys.exit(1)
Raise `ConfigurationError` instead of `Exception` if environment variable `BYCEPS_CONFIG` is not set
|
"""
byceps.util.system
~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
import os
import sys
from ..config import ConfigurationError
CONFIG_VAR_NAME = 'BYCEPS_CONFIG'
def get_config_filename_from_env() -> str:
"""Return the configuration filename set via environment variable.
Raise an exception if it isn't set.
"""
env = os.environ.get(CONFIG_VAR_NAME)
if not env:
raise ConfigurationError(
"No configuration file was specified via the '{}' "
"environment variable.".format(CONFIG_VAR_NAME))
return env
def get_config_filename_from_env_or_exit() -> str:
"""Return the configuration filename set via environment variable.
Exit if it isn't set.
"""
try:
return get_config_filename_from_env()
except ConfigurationError as e:
sys.stderr.write("{}\n".format(e))
sys.exit(1)
|
<commit_before>"""
byceps.util.system
~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
import os
import sys
CONFIG_VAR_NAME = 'BYCEPS_CONFIG'
def get_config_filename_from_env() -> str:
"""Return the configuration filename set via environment variable.
Raise an exception if it isn't set.
"""
env = os.environ.get(CONFIG_VAR_NAME)
if not env:
raise Exception(
"No configuration file was specified via the '{}' "
"environment variable.".format(CONFIG_VAR_NAME))
return env
def get_config_filename_from_env_or_exit() -> str:
"""Return the configuration filename set via environment variable.
Exit if it isn't set.
"""
try:
return get_config_filename_from_env()
except Exception as e:
sys.stderr.write("{}\n".format(e))
sys.exit(1)
<commit_msg>Raise `ConfigurationError` instead of `Exception` if environment variable `BYCEPS_CONFIG` is not set<commit_after>
|
"""
byceps.util.system
~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
import os
import sys
from ..config import ConfigurationError
CONFIG_VAR_NAME = 'BYCEPS_CONFIG'
def get_config_filename_from_env() -> str:
"""Return the configuration filename set via environment variable.
Raise an exception if it isn't set.
"""
env = os.environ.get(CONFIG_VAR_NAME)
if not env:
raise ConfigurationError(
"No configuration file was specified via the '{}' "
"environment variable.".format(CONFIG_VAR_NAME))
return env
def get_config_filename_from_env_or_exit() -> str:
"""Return the configuration filename set via environment variable.
Exit if it isn't set.
"""
try:
return get_config_filename_from_env()
except ConfigurationError as e:
sys.stderr.write("{}\n".format(e))
sys.exit(1)
|
"""
byceps.util.system
~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
import os
import sys
CONFIG_VAR_NAME = 'BYCEPS_CONFIG'
def get_config_filename_from_env() -> str:
"""Return the configuration filename set via environment variable.
Raise an exception if it isn't set.
"""
env = os.environ.get(CONFIG_VAR_NAME)
if not env:
raise Exception(
"No configuration file was specified via the '{}' "
"environment variable.".format(CONFIG_VAR_NAME))
return env
def get_config_filename_from_env_or_exit() -> str:
"""Return the configuration filename set via environment variable.
Exit if it isn't set.
"""
try:
return get_config_filename_from_env()
except Exception as e:
sys.stderr.write("{}\n".format(e))
sys.exit(1)
Raise `ConfigurationError` instead of `Exception` if environment variable `BYCEPS_CONFIG` is not set"""
byceps.util.system
~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
import os
import sys
from ..config import ConfigurationError
CONFIG_VAR_NAME = 'BYCEPS_CONFIG'
def get_config_filename_from_env() -> str:
"""Return the configuration filename set via environment variable.
Raise an exception if it isn't set.
"""
env = os.environ.get(CONFIG_VAR_NAME)
if not env:
raise ConfigurationError(
"No configuration file was specified via the '{}' "
"environment variable.".format(CONFIG_VAR_NAME))
return env
def get_config_filename_from_env_or_exit() -> str:
"""Return the configuration filename set via environment variable.
Exit if it isn't set.
"""
try:
return get_config_filename_from_env()
except ConfigurationError as e:
sys.stderr.write("{}\n".format(e))
sys.exit(1)
|
<commit_before>"""
byceps.util.system
~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
import os
import sys
CONFIG_VAR_NAME = 'BYCEPS_CONFIG'
def get_config_filename_from_env() -> str:
"""Return the configuration filename set via environment variable.
Raise an exception if it isn't set.
"""
env = os.environ.get(CONFIG_VAR_NAME)
if not env:
raise Exception(
"No configuration file was specified via the '{}' "
"environment variable.".format(CONFIG_VAR_NAME))
return env
def get_config_filename_from_env_or_exit() -> str:
"""Return the configuration filename set via environment variable.
Exit if it isn't set.
"""
try:
return get_config_filename_from_env()
except Exception as e:
sys.stderr.write("{}\n".format(e))
sys.exit(1)
<commit_msg>Raise `ConfigurationError` instead of `Exception` if environment variable `BYCEPS_CONFIG` is not set<commit_after>"""
byceps.util.system
~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
import os
import sys
from ..config import ConfigurationError
CONFIG_VAR_NAME = 'BYCEPS_CONFIG'
def get_config_filename_from_env() -> str:
"""Return the configuration filename set via environment variable.
Raise an exception if it isn't set.
"""
env = os.environ.get(CONFIG_VAR_NAME)
if not env:
raise ConfigurationError(
"No configuration file was specified via the '{}' "
"environment variable.".format(CONFIG_VAR_NAME))
return env
def get_config_filename_from_env_or_exit() -> str:
"""Return the configuration filename set via environment variable.
Exit if it isn't set.
"""
try:
return get_config_filename_from_env()
except ConfigurationError as e:
sys.stderr.write("{}\n".format(e))
sys.exit(1)
|
0f8c4cd71bff68860d0a18f8680eda9a690f0959
|
sqlstr/exception.py
|
sqlstr/exception.py
|
'''
Exceptions from sqlstr
-------------------------
'''
class sqlstrException(Exception):
def __init__(self, message):
'''
Instanitates a custom sqlstrException
:message str:
'''
Exception.__init__(self, message)
|
'''
Exceptions from sqlstr
-------------------------
'''
class sqlstrException(Exception):
def __init__(self, message):
'''
Instanitates a custom sqlstrException
message -- string. Message describing the exception.
'''
Exception.__init__(self, message)
|
Update docstring with parameter listing
|
Update docstring with parameter listing
|
Python
|
mit
|
GochoMugo/sql-string-templating
|
'''
Exceptions from sqlstr
-------------------------
'''
class sqlstrException(Exception):
def __init__(self, message):
'''
Instanitates a custom sqlstrException
:message str:
'''
Exception.__init__(self, message)
Update docstring with parameter listing
|
'''
Exceptions from sqlstr
-------------------------
'''
class sqlstrException(Exception):
def __init__(self, message):
'''
Instanitates a custom sqlstrException
message -- string. Message describing the exception.
'''
Exception.__init__(self, message)
|
<commit_before>'''
Exceptions from sqlstr
-------------------------
'''
class sqlstrException(Exception):
def __init__(self, message):
'''
Instanitates a custom sqlstrException
:message str:
'''
Exception.__init__(self, message)
<commit_msg>Update docstring with parameter listing<commit_after>
|
'''
Exceptions from sqlstr
-------------------------
'''
class sqlstrException(Exception):
def __init__(self, message):
'''
Instanitates a custom sqlstrException
message -- string. Message describing the exception.
'''
Exception.__init__(self, message)
|
'''
Exceptions from sqlstr
-------------------------
'''
class sqlstrException(Exception):
def __init__(self, message):
'''
Instanitates a custom sqlstrException
:message str:
'''
Exception.__init__(self, message)
Update docstring with parameter listing'''
Exceptions from sqlstr
-------------------------
'''
class sqlstrException(Exception):
def __init__(self, message):
'''
Instanitates a custom sqlstrException
message -- string. Message describing the exception.
'''
Exception.__init__(self, message)
|
<commit_before>'''
Exceptions from sqlstr
-------------------------
'''
class sqlstrException(Exception):
def __init__(self, message):
'''
Instanitates a custom sqlstrException
:message str:
'''
Exception.__init__(self, message)
<commit_msg>Update docstring with parameter listing<commit_after>'''
Exceptions from sqlstr
-------------------------
'''
class sqlstrException(Exception):
def __init__(self, message):
'''
Instanitates a custom sqlstrException
message -- string. Message describing the exception.
'''
Exception.__init__(self, message)
|
8e5e732ad02f9aa6df7a8963c73c2b0aa753ad0a
|
src/utils.py
|
src/utils.py
|
if 'logger' not in globals():
import logging
logger = logging.getLogger('Main')
logger.setLevel(logging.DEBUG)
logger.propagate = False
if not logger.handlers:
hdlr = logging.StreamHandler()
hdlr.setLevel(logging.DEBUG)
formatter = logging.Formatter(
# '%(asctime)s - '
'%(name)s - '
'%(levelname)s '
'%(filename)s:%(lineno)d: '
'%(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
|
if 'logger' not in globals():
import logging
logger = logging.getLogger('Main')
logger.setLevel(logging.DEBUG)
logger.propagate = False
if not logger.handlers:
hdlr = logging.StreamHandler()
hdlr.setLevel(logging.DEBUG)
formatter = logging.Formatter(
# '%(asctime)s - '
'%(name)s - '
'%(levelname)s '
'%(filename)s:%(lineno)d: '
'%(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
def reduce(obj, can_return_single=False):
"""
Flattens nested lists, like so;
>>> reduce([[[[[[[None]]]]]]])
None
"""
if type(obj) == list and len(obj) == 1 and type(obj[0]) == list:
return reduce(obj[0])
elif type(obj) == list and len(obj) == 1 and can_return_single:
return obj[0]
else:
return obj
|
Reduce function, to stop nested lists
|
Reduce function, to stop nested lists
|
Python
|
mit
|
Mause/tyrian,Mause/tyrian,Mause/tyrian,Mause/tyrian
|
if 'logger' not in globals():
import logging
logger = logging.getLogger('Main')
logger.setLevel(logging.DEBUG)
logger.propagate = False
if not logger.handlers:
hdlr = logging.StreamHandler()
hdlr.setLevel(logging.DEBUG)
formatter = logging.Formatter(
# '%(asctime)s - '
'%(name)s - '
'%(levelname)s '
'%(filename)s:%(lineno)d: '
'%(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
Reduce function, to stop nested lists
|
if 'logger' not in globals():
import logging
logger = logging.getLogger('Main')
logger.setLevel(logging.DEBUG)
logger.propagate = False
if not logger.handlers:
hdlr = logging.StreamHandler()
hdlr.setLevel(logging.DEBUG)
formatter = logging.Formatter(
# '%(asctime)s - '
'%(name)s - '
'%(levelname)s '
'%(filename)s:%(lineno)d: '
'%(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
def reduce(obj, can_return_single=False):
"""
Flattens nested lists, like so;
>>> reduce([[[[[[[None]]]]]]])
None
"""
if type(obj) == list and len(obj) == 1 and type(obj[0]) == list:
return reduce(obj[0])
elif type(obj) == list and len(obj) == 1 and can_return_single:
return obj[0]
else:
return obj
|
<commit_before>if 'logger' not in globals():
import logging
logger = logging.getLogger('Main')
logger.setLevel(logging.DEBUG)
logger.propagate = False
if not logger.handlers:
hdlr = logging.StreamHandler()
hdlr.setLevel(logging.DEBUG)
formatter = logging.Formatter(
# '%(asctime)s - '
'%(name)s - '
'%(levelname)s '
'%(filename)s:%(lineno)d: '
'%(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
<commit_msg>Reduce function, to stop nested lists<commit_after>
|
if 'logger' not in globals():
import logging
logger = logging.getLogger('Main')
logger.setLevel(logging.DEBUG)
logger.propagate = False
if not logger.handlers:
hdlr = logging.StreamHandler()
hdlr.setLevel(logging.DEBUG)
formatter = logging.Formatter(
# '%(asctime)s - '
'%(name)s - '
'%(levelname)s '
'%(filename)s:%(lineno)d: '
'%(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
def reduce(obj, can_return_single=False):
"""
Flattens nested lists, like so;
>>> reduce([[[[[[[None]]]]]]])
None
"""
if type(obj) == list and len(obj) == 1 and type(obj[0]) == list:
return reduce(obj[0])
elif type(obj) == list and len(obj) == 1 and can_return_single:
return obj[0]
else:
return obj
|
if 'logger' not in globals():
import logging
logger = logging.getLogger('Main')
logger.setLevel(logging.DEBUG)
logger.propagate = False
if not logger.handlers:
hdlr = logging.StreamHandler()
hdlr.setLevel(logging.DEBUG)
formatter = logging.Formatter(
# '%(asctime)s - '
'%(name)s - '
'%(levelname)s '
'%(filename)s:%(lineno)d: '
'%(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
Reduce function, to stop nested listsif 'logger' not in globals():
import logging
logger = logging.getLogger('Main')
logger.setLevel(logging.DEBUG)
logger.propagate = False
if not logger.handlers:
hdlr = logging.StreamHandler()
hdlr.setLevel(logging.DEBUG)
formatter = logging.Formatter(
# '%(asctime)s - '
'%(name)s - '
'%(levelname)s '
'%(filename)s:%(lineno)d: '
'%(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
def reduce(obj, can_return_single=False):
"""
Flattens nested lists, like so;
>>> reduce([[[[[[[None]]]]]]])
None
"""
if type(obj) == list and len(obj) == 1 and type(obj[0]) == list:
return reduce(obj[0])
elif type(obj) == list and len(obj) == 1 and can_return_single:
return obj[0]
else:
return obj
|
<commit_before>if 'logger' not in globals():
import logging
logger = logging.getLogger('Main')
logger.setLevel(logging.DEBUG)
logger.propagate = False
if not logger.handlers:
hdlr = logging.StreamHandler()
hdlr.setLevel(logging.DEBUG)
formatter = logging.Formatter(
# '%(asctime)s - '
'%(name)s - '
'%(levelname)s '
'%(filename)s:%(lineno)d: '
'%(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
<commit_msg>Reduce function, to stop nested lists<commit_after>if 'logger' not in globals():
import logging
logger = logging.getLogger('Main')
logger.setLevel(logging.DEBUG)
logger.propagate = False
if not logger.handlers:
hdlr = logging.StreamHandler()
hdlr.setLevel(logging.DEBUG)
formatter = logging.Formatter(
# '%(asctime)s - '
'%(name)s - '
'%(levelname)s '
'%(filename)s:%(lineno)d: '
'%(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
def reduce(obj, can_return_single=False):
"""
Flattens nested lists, like so;
>>> reduce([[[[[[[None]]]]]]])
None
"""
if type(obj) == list and len(obj) == 1 and type(obj[0]) == list:
return reduce(obj[0])
elif type(obj) == list and len(obj) == 1 and can_return_single:
return obj[0]
else:
return obj
|
a0a0d120552eeb304ac4b49648a43be5cf83cdcb
|
piper/core.py
|
piper/core.py
|
class Piper(object):
"""
The main runner.
This class loads the configurations, sets up all other components, and
finally executes them in whatever order they are supposed to happen in.
"""
def __init__(self):
pass
|
import logbook
class Piper(object):
"""
The main pipeline runner.
This class loads the configurations, sets up all other components,
executes them in whatever order they are supposed to happen in, collects
data about the state of the pipeline and persists it, and finally tears
down the components that needs tearing down.
The functions are almost executed in the order found in this file. Woo!
"""
def __init__(self):
self.log = logbook.Logger(self.__class__.__name__)
def setup(self):
"""
Performs all setup steps
This is basically an umbrella function that runs setup for all the
things that the class needs to run a fully configured execute().
"""
pass
def load_config(self):
"""
Parses the configuration file and dies in flames if there are errors.
"""
pass
def setup_environment(self):
"""
Load the environment and it's configuration
"""
pass
def setup_steps(self):
"""
Loads the steps and their configuration.
Also determines which collection of steps is to be ran.
"""
pass
def execute(self):
"""
Runs the steps and determines whether to continue or not.
Of all the things to happen in this application, this is probably
the most important part!
"""
pass
def save_state(self):
"""
Collects all data about the pipeline being built and persists it.
"""
pass
def teardown_environment(self):
"""
Execute teardown step of the environment
"""
pass
|
Add more skeletonisms and documentation for Piper()
|
Add more skeletonisms and documentation for Piper()
|
Python
|
mit
|
thiderman/piper
|
class Piper(object):
"""
The main runner.
This class loads the configurations, sets up all other components, and
finally executes them in whatever order they are supposed to happen in.
"""
def __init__(self):
pass
Add more skeletonisms and documentation for Piper()
|
import logbook
class Piper(object):
"""
The main pipeline runner.
This class loads the configurations, sets up all other components,
executes them in whatever order they are supposed to happen in, collects
data about the state of the pipeline and persists it, and finally tears
down the components that needs tearing down.
The functions are almost executed in the order found in this file. Woo!
"""
def __init__(self):
self.log = logbook.Logger(self.__class__.__name__)
def setup(self):
"""
Performs all setup steps
This is basically an umbrella function that runs setup for all the
things that the class needs to run a fully configured execute().
"""
pass
def load_config(self):
"""
Parses the configuration file and dies in flames if there are errors.
"""
pass
def setup_environment(self):
"""
Load the environment and it's configuration
"""
pass
def setup_steps(self):
"""
Loads the steps and their configuration.
Also determines which collection of steps is to be ran.
"""
pass
def execute(self):
"""
Runs the steps and determines whether to continue or not.
Of all the things to happen in this application, this is probably
the most important part!
"""
pass
def save_state(self):
"""
Collects all data about the pipeline being built and persists it.
"""
pass
def teardown_environment(self):
"""
Execute teardown step of the environment
"""
pass
|
<commit_before>class Piper(object):
"""
The main runner.
This class loads the configurations, sets up all other components, and
finally executes them in whatever order they are supposed to happen in.
"""
def __init__(self):
pass
<commit_msg>Add more skeletonisms and documentation for Piper()<commit_after>
|
import logbook
class Piper(object):
"""
The main pipeline runner.
This class loads the configurations, sets up all other components,
executes them in whatever order they are supposed to happen in, collects
data about the state of the pipeline and persists it, and finally tears
down the components that needs tearing down.
The functions are almost executed in the order found in this file. Woo!
"""
def __init__(self):
self.log = logbook.Logger(self.__class__.__name__)
def setup(self):
"""
Performs all setup steps
This is basically an umbrella function that runs setup for all the
things that the class needs to run a fully configured execute().
"""
pass
def load_config(self):
"""
Parses the configuration file and dies in flames if there are errors.
"""
pass
def setup_environment(self):
"""
Load the environment and it's configuration
"""
pass
def setup_steps(self):
"""
Loads the steps and their configuration.
Also determines which collection of steps is to be ran.
"""
pass
def execute(self):
"""
Runs the steps and determines whether to continue or not.
Of all the things to happen in this application, this is probably
the most important part!
"""
pass
def save_state(self):
"""
Collects all data about the pipeline being built and persists it.
"""
pass
def teardown_environment(self):
"""
Execute teardown step of the environment
"""
pass
|
class Piper(object):
"""
The main runner.
This class loads the configurations, sets up all other components, and
finally executes them in whatever order they are supposed to happen in.
"""
def __init__(self):
pass
Add more skeletonisms and documentation for Piper()import logbook
class Piper(object):
"""
The main pipeline runner.
This class loads the configurations, sets up all other components,
executes them in whatever order they are supposed to happen in, collects
data about the state of the pipeline and persists it, and finally tears
down the components that needs tearing down.
The functions are almost executed in the order found in this file. Woo!
"""
def __init__(self):
self.log = logbook.Logger(self.__class__.__name__)
def setup(self):
"""
Performs all setup steps
This is basically an umbrella function that runs setup for all the
things that the class needs to run a fully configured execute().
"""
pass
def load_config(self):
"""
Parses the configuration file and dies in flames if there are errors.
"""
pass
def setup_environment(self):
"""
Load the environment and it's configuration
"""
pass
def setup_steps(self):
"""
Loads the steps and their configuration.
Also determines which collection of steps is to be ran.
"""
pass
def execute(self):
"""
Runs the steps and determines whether to continue or not.
Of all the things to happen in this application, this is probably
the most important part!
"""
pass
def save_state(self):
"""
Collects all data about the pipeline being built and persists it.
"""
pass
def teardown_environment(self):
"""
Execute teardown step of the environment
"""
pass
|
<commit_before>class Piper(object):
"""
The main runner.
This class loads the configurations, sets up all other components, and
finally executes them in whatever order they are supposed to happen in.
"""
def __init__(self):
pass
<commit_msg>Add more skeletonisms and documentation for Piper()<commit_after>import logbook
class Piper(object):
"""
The main pipeline runner.
This class loads the configurations, sets up all other components,
executes them in whatever order they are supposed to happen in, collects
data about the state of the pipeline and persists it, and finally tears
down the components that needs tearing down.
The functions are almost executed in the order found in this file. Woo!
"""
def __init__(self):
self.log = logbook.Logger(self.__class__.__name__)
def setup(self):
"""
Performs all setup steps
This is basically an umbrella function that runs setup for all the
things that the class needs to run a fully configured execute().
"""
pass
def load_config(self):
"""
Parses the configuration file and dies in flames if there are errors.
"""
pass
def setup_environment(self):
"""
Load the environment and it's configuration
"""
pass
def setup_steps(self):
"""
Loads the steps and their configuration.
Also determines which collection of steps is to be ran.
"""
pass
def execute(self):
"""
Runs the steps and determines whether to continue or not.
Of all the things to happen in this application, this is probably
the most important part!
"""
pass
def save_state(self):
"""
Collects all data about the pipeline being built and persists it.
"""
pass
def teardown_environment(self):
"""
Execute teardown step of the environment
"""
pass
|
0261a0f9a1dde9f9f6167e3630561219e3dca124
|
statsmodels/datasets/__init__.py
|
statsmodels/datasets/__init__.py
|
"""
Datasets module
"""
#__all__ = filter(lambda s:not s.startswith('_'),dir())
import anes96, cancer, committee, ccard, copper, cpunish, elnino, grunfeld, longley, \
macrodata, nile, randhie, scotland, spector, stackloss, star98, \
strikes, sunspots, fair, heart, statecrime
|
"""
Datasets module
"""
#__all__ = filter(lambda s:not s.startswith('_'),dir())
from . import (anes96, cancer, committee, ccard, copper, cpunish, elnino,
grunfeld, longley, macrodata, nile, randhie, scotland, spector,
stackloss, star98, strikes, sunspots, fair, heart, statecrime)
|
Switch to relative imports and fix pep-8
|
STY: Switch to relative imports and fix pep-8
|
Python
|
bsd-3-clause
|
bsipocz/statsmodels,bsipocz/statsmodels,bsipocz/statsmodels,hlin117/statsmodels,bashtage/statsmodels,nguyentu1602/statsmodels,hlin117/statsmodels,musically-ut/statsmodels,yl565/statsmodels,jstoxrocky/statsmodels,wwf5067/statsmodels,bert9bert/statsmodels,nvoron23/statsmodels,bert9bert/statsmodels,astocko/statsmodels,jseabold/statsmodels,YihaoLu/statsmodels,hainm/statsmodels,ChadFulton/statsmodels,bert9bert/statsmodels,kiyoto/statsmodels,astocko/statsmodels,DonBeo/statsmodels,DonBeo/statsmodels,alekz112/statsmodels,waynenilsen/statsmodels,phobson/statsmodels,rgommers/statsmodels,nguyentu1602/statsmodels,josef-pkt/statsmodels,gef756/statsmodels,Averroes/statsmodels,phobson/statsmodels,statsmodels/statsmodels,yl565/statsmodels,statsmodels/statsmodels,adammenges/statsmodels,wdurhamh/statsmodels,cbmoore/statsmodels,edhuckle/statsmodels,adammenges/statsmodels,jstoxrocky/statsmodels,alekz112/statsmodels,rgommers/statsmodels,wwf5067/statsmodels,waynenilsen/statsmodels,huongttlan/statsmodels,bavardage/statsmodels,yarikoptic/pystatsmodels,jstoxrocky/statsmodels,musically-ut/statsmodels,ChadFulton/statsmodels,statsmodels/statsmodels,wdurhamh/statsmodels,huongttlan/statsmodels,hainm/statsmodels,bashtage/statsmodels,bzero/statsmodels,wzbozon/statsmodels,Averroes/statsmodels,josef-pkt/statsmodels,alekz112/statsmodels,musically-ut/statsmodels,cbmoore/statsmodels,waynenilsen/statsmodels,gef756/statsmodels,wkfwkf/statsmodels,wzbozon/statsmodels,saketkc/statsmodels,josef-pkt/statsmodels,detrout/debian-statsmodels,astocko/statsmodels,wzbozon/statsmodels,yl565/statsmodels,adammenges/statsmodels,hlin117/statsmodels,detrout/debian-statsmodels,bzero/statsmodels,kiyoto/statsmodels,yl565/statsmodels,alekz112/statsmodels,bavardage/statsmodels,nvoron23/statsmodels,YihaoLu/statsmodels,bashtage/statsmodels,hainm/statsmodels,rgommers/statsmodels,YihaoLu/statsmodels,bsipocz/statsmodels,ChadFulton/statsmodels,wkfwkf/statsmodels,astocko/statsmodels,DonBeo/statsmodels,edhuckle/statsmodels,kiyoto/statsmodels,josef-pkt/statsmodels,wkfwkf/statsmodels,josef-pkt/statsmodels,yl565/statsmodels,saketkc/statsmodels,musically-ut/statsmodels,jseabold/statsmodels,bavardage/statsmodels,huongttlan/statsmodels,rgommers/statsmodels,statsmodels/statsmodels,bzero/statsmodels,nvoron23/statsmodels,statsmodels/statsmodels,DonBeo/statsmodels,ChadFulton/statsmodels,edhuckle/statsmodels,bashtage/statsmodels,wwf5067/statsmodels,wdurhamh/statsmodels,nvoron23/statsmodels,detrout/debian-statsmodels,edhuckle/statsmodels,jseabold/statsmodels,nguyentu1602/statsmodels,saketkc/statsmodels,kiyoto/statsmodels,adammenges/statsmodels,ChadFulton/statsmodels,jseabold/statsmodels,DonBeo/statsmodels,bert9bert/statsmodels,cbmoore/statsmodels,saketkc/statsmodels,hlin117/statsmodels,YihaoLu/statsmodels,bzero/statsmodels,phobson/statsmodels,nvoron23/statsmodels,Averroes/statsmodels,josef-pkt/statsmodels,bavardage/statsmodels,wkfwkf/statsmodels,wdurhamh/statsmodels,gef756/statsmodels,bzero/statsmodels,edhuckle/statsmodels,bashtage/statsmodels,detrout/debian-statsmodels,wzbozon/statsmodels,phobson/statsmodels,nguyentu1602/statsmodels,Averroes/statsmodels,gef756/statsmodels,wwf5067/statsmodels,wkfwkf/statsmodels,huongttlan/statsmodels,YihaoLu/statsmodels,phobson/statsmodels,statsmodels/statsmodels,jseabold/statsmodels,wzbozon/statsmodels,bavardage/statsmodels,waynenilsen/statsmodels,cbmoore/statsmodels,cbmoore/statsmodels,jstoxrocky/statsmodels,hainm/statsmodels,ChadFulton/statsmodels,bashtage/statsmodels,bert9bert/statsmodels,kiyoto/statsmodels,saketkc/statsmodels,yarikoptic/pystatsmodels,wdurhamh/statsmodels,gef756/statsmodels,rgommers/statsmodels,yarikoptic/pystatsmodels
|
"""
Datasets module
"""
#__all__ = filter(lambda s:not s.startswith('_'),dir())
import anes96, cancer, committee, ccard, copper, cpunish, elnino, grunfeld, longley, \
macrodata, nile, randhie, scotland, spector, stackloss, star98, \
strikes, sunspots, fair, heart, statecrime
STY: Switch to relative imports and fix pep-8
|
"""
Datasets module
"""
#__all__ = filter(lambda s:not s.startswith('_'),dir())
from . import (anes96, cancer, committee, ccard, copper, cpunish, elnino,
grunfeld, longley, macrodata, nile, randhie, scotland, spector,
stackloss, star98, strikes, sunspots, fair, heart, statecrime)
|
<commit_before>"""
Datasets module
"""
#__all__ = filter(lambda s:not s.startswith('_'),dir())
import anes96, cancer, committee, ccard, copper, cpunish, elnino, grunfeld, longley, \
macrodata, nile, randhie, scotland, spector, stackloss, star98, \
strikes, sunspots, fair, heart, statecrime
<commit_msg>STY: Switch to relative imports and fix pep-8<commit_after>
|
"""
Datasets module
"""
#__all__ = filter(lambda s:not s.startswith('_'),dir())
from . import (anes96, cancer, committee, ccard, copper, cpunish, elnino,
grunfeld, longley, macrodata, nile, randhie, scotland, spector,
stackloss, star98, strikes, sunspots, fair, heart, statecrime)
|
"""
Datasets module
"""
#__all__ = filter(lambda s:not s.startswith('_'),dir())
import anes96, cancer, committee, ccard, copper, cpunish, elnino, grunfeld, longley, \
macrodata, nile, randhie, scotland, spector, stackloss, star98, \
strikes, sunspots, fair, heart, statecrime
STY: Switch to relative imports and fix pep-8"""
Datasets module
"""
#__all__ = filter(lambda s:not s.startswith('_'),dir())
from . import (anes96, cancer, committee, ccard, copper, cpunish, elnino,
grunfeld, longley, macrodata, nile, randhie, scotland, spector,
stackloss, star98, strikes, sunspots, fair, heart, statecrime)
|
<commit_before>"""
Datasets module
"""
#__all__ = filter(lambda s:not s.startswith('_'),dir())
import anes96, cancer, committee, ccard, copper, cpunish, elnino, grunfeld, longley, \
macrodata, nile, randhie, scotland, spector, stackloss, star98, \
strikes, sunspots, fair, heart, statecrime
<commit_msg>STY: Switch to relative imports and fix pep-8<commit_after>"""
Datasets module
"""
#__all__ = filter(lambda s:not s.startswith('_'),dir())
from . import (anes96, cancer, committee, ccard, copper, cpunish, elnino,
grunfeld, longley, macrodata, nile, randhie, scotland, spector,
stackloss, star98, strikes, sunspots, fair, heart, statecrime)
|
d7945f0394038e9c194a2e41e6da151b679128a3
|
cs251tk/toolkit/process_student.py
|
cs251tk/toolkit/process_student.py
|
from cs251tk.student import remove
from cs251tk.student import clone_student
from cs251tk.student import stash
from cs251tk.student import pull
from cs251tk.student import checkout_date
from cs251tk.student import record
from cs251tk.student import reset
from cs251tk.student import analyze
def process_student(
student,
*,
assignments,
basedir,
clean,
date,
debug,
interact,
no_check,
no_update,
specs,
stogit_url
):
if clean:
remove(student)
clone_student(student, baseurl=stogit_url)
try:
stash(student, no_update=no_update)
pull(student, no_update=no_update)
checkout_date(student, date=date)
recordings = record(student, specs=specs, to_record=assignments, basedir=basedir, debug=debug, interact=interact)
analysis = analyze(student, specs, check_for_branches=not no_check)
if date:
reset(student)
return analysis, recordings
except Exception as err:
if debug:
raise err
return {'username': student, 'error': err}, []
|
from cs251tk.student import remove
from cs251tk.student import clone_student
from cs251tk.student import stash
from cs251tk.student import pull
from cs251tk.student import checkout_date
from cs251tk.student import record
from cs251tk.student import reset
from cs251tk.student import analyze
def process_student(
student,
*,
assignments,
basedir,
clean,
date,
debug,
interact,
no_check,
no_update,
specs,
stogit_url
):
if clean:
remove(student)
clone_student(student, baseurl=stogit_url)
try:
stash(student, no_update=no_update)
pull(student, no_update=no_update)
checkout_date(student, date=date)
recordings = record(student, specs=specs, to_record=assignments, basedir=basedir, debug=debug, interact=interact)
analysis = analyze(student, specs, check_for_branches=not no_check)
if date:
reset(student)
return analysis, recordings
except Exception as err:
if debug:
raise err
return {'username': student, 'error': err}, []
|
Remove extra newlines added during editing
|
Remove extra newlines added during editing
|
Python
|
mit
|
StoDevX/cs251-toolkit,StoDevX/cs251-toolkit,StoDevX/cs251-toolkit,StoDevX/cs251-toolkit
|
from cs251tk.student import remove
from cs251tk.student import clone_student
from cs251tk.student import stash
from cs251tk.student import pull
from cs251tk.student import checkout_date
from cs251tk.student import record
from cs251tk.student import reset
from cs251tk.student import analyze
def process_student(
student,
*,
assignments,
basedir,
clean,
date,
debug,
interact,
no_check,
no_update,
specs,
stogit_url
):
if clean:
remove(student)
clone_student(student, baseurl=stogit_url)
try:
stash(student, no_update=no_update)
pull(student, no_update=no_update)
checkout_date(student, date=date)
recordings = record(student, specs=specs, to_record=assignments, basedir=basedir, debug=debug, interact=interact)
analysis = analyze(student, specs, check_for_branches=not no_check)
if date:
reset(student)
return analysis, recordings
except Exception as err:
if debug:
raise err
return {'username': student, 'error': err}, []
Remove extra newlines added during editing
|
from cs251tk.student import remove
from cs251tk.student import clone_student
from cs251tk.student import stash
from cs251tk.student import pull
from cs251tk.student import checkout_date
from cs251tk.student import record
from cs251tk.student import reset
from cs251tk.student import analyze
def process_student(
student,
*,
assignments,
basedir,
clean,
date,
debug,
interact,
no_check,
no_update,
specs,
stogit_url
):
if clean:
remove(student)
clone_student(student, baseurl=stogit_url)
try:
stash(student, no_update=no_update)
pull(student, no_update=no_update)
checkout_date(student, date=date)
recordings = record(student, specs=specs, to_record=assignments, basedir=basedir, debug=debug, interact=interact)
analysis = analyze(student, specs, check_for_branches=not no_check)
if date:
reset(student)
return analysis, recordings
except Exception as err:
if debug:
raise err
return {'username': student, 'error': err}, []
|
<commit_before>from cs251tk.student import remove
from cs251tk.student import clone_student
from cs251tk.student import stash
from cs251tk.student import pull
from cs251tk.student import checkout_date
from cs251tk.student import record
from cs251tk.student import reset
from cs251tk.student import analyze
def process_student(
student,
*,
assignments,
basedir,
clean,
date,
debug,
interact,
no_check,
no_update,
specs,
stogit_url
):
if clean:
remove(student)
clone_student(student, baseurl=stogit_url)
try:
stash(student, no_update=no_update)
pull(student, no_update=no_update)
checkout_date(student, date=date)
recordings = record(student, specs=specs, to_record=assignments, basedir=basedir, debug=debug, interact=interact)
analysis = analyze(student, specs, check_for_branches=not no_check)
if date:
reset(student)
return analysis, recordings
except Exception as err:
if debug:
raise err
return {'username': student, 'error': err}, []
<commit_msg>Remove extra newlines added during editing<commit_after>
|
from cs251tk.student import remove
from cs251tk.student import clone_student
from cs251tk.student import stash
from cs251tk.student import pull
from cs251tk.student import checkout_date
from cs251tk.student import record
from cs251tk.student import reset
from cs251tk.student import analyze
def process_student(
student,
*,
assignments,
basedir,
clean,
date,
debug,
interact,
no_check,
no_update,
specs,
stogit_url
):
if clean:
remove(student)
clone_student(student, baseurl=stogit_url)
try:
stash(student, no_update=no_update)
pull(student, no_update=no_update)
checkout_date(student, date=date)
recordings = record(student, specs=specs, to_record=assignments, basedir=basedir, debug=debug, interact=interact)
analysis = analyze(student, specs, check_for_branches=not no_check)
if date:
reset(student)
return analysis, recordings
except Exception as err:
if debug:
raise err
return {'username': student, 'error': err}, []
|
from cs251tk.student import remove
from cs251tk.student import clone_student
from cs251tk.student import stash
from cs251tk.student import pull
from cs251tk.student import checkout_date
from cs251tk.student import record
from cs251tk.student import reset
from cs251tk.student import analyze
def process_student(
student,
*,
assignments,
basedir,
clean,
date,
debug,
interact,
no_check,
no_update,
specs,
stogit_url
):
if clean:
remove(student)
clone_student(student, baseurl=stogit_url)
try:
stash(student, no_update=no_update)
pull(student, no_update=no_update)
checkout_date(student, date=date)
recordings = record(student, specs=specs, to_record=assignments, basedir=basedir, debug=debug, interact=interact)
analysis = analyze(student, specs, check_for_branches=not no_check)
if date:
reset(student)
return analysis, recordings
except Exception as err:
if debug:
raise err
return {'username': student, 'error': err}, []
Remove extra newlines added during editingfrom cs251tk.student import remove
from cs251tk.student import clone_student
from cs251tk.student import stash
from cs251tk.student import pull
from cs251tk.student import checkout_date
from cs251tk.student import record
from cs251tk.student import reset
from cs251tk.student import analyze
def process_student(
student,
*,
assignments,
basedir,
clean,
date,
debug,
interact,
no_check,
no_update,
specs,
stogit_url
):
if clean:
remove(student)
clone_student(student, baseurl=stogit_url)
try:
stash(student, no_update=no_update)
pull(student, no_update=no_update)
checkout_date(student, date=date)
recordings = record(student, specs=specs, to_record=assignments, basedir=basedir, debug=debug, interact=interact)
analysis = analyze(student, specs, check_for_branches=not no_check)
if date:
reset(student)
return analysis, recordings
except Exception as err:
if debug:
raise err
return {'username': student, 'error': err}, []
|
<commit_before>from cs251tk.student import remove
from cs251tk.student import clone_student
from cs251tk.student import stash
from cs251tk.student import pull
from cs251tk.student import checkout_date
from cs251tk.student import record
from cs251tk.student import reset
from cs251tk.student import analyze
def process_student(
student,
*,
assignments,
basedir,
clean,
date,
debug,
interact,
no_check,
no_update,
specs,
stogit_url
):
if clean:
remove(student)
clone_student(student, baseurl=stogit_url)
try:
stash(student, no_update=no_update)
pull(student, no_update=no_update)
checkout_date(student, date=date)
recordings = record(student, specs=specs, to_record=assignments, basedir=basedir, debug=debug, interact=interact)
analysis = analyze(student, specs, check_for_branches=not no_check)
if date:
reset(student)
return analysis, recordings
except Exception as err:
if debug:
raise err
return {'username': student, 'error': err}, []
<commit_msg>Remove extra newlines added during editing<commit_after>from cs251tk.student import remove
from cs251tk.student import clone_student
from cs251tk.student import stash
from cs251tk.student import pull
from cs251tk.student import checkout_date
from cs251tk.student import record
from cs251tk.student import reset
from cs251tk.student import analyze
def process_student(
student,
*,
assignments,
basedir,
clean,
date,
debug,
interact,
no_check,
no_update,
specs,
stogit_url
):
if clean:
remove(student)
clone_student(student, baseurl=stogit_url)
try:
stash(student, no_update=no_update)
pull(student, no_update=no_update)
checkout_date(student, date=date)
recordings = record(student, specs=specs, to_record=assignments, basedir=basedir, debug=debug, interact=interact)
analysis = analyze(student, specs, check_for_branches=not no_check)
if date:
reset(student)
return analysis, recordings
except Exception as err:
if debug:
raise err
return {'username': student, 'error': err}, []
|
105b5c3d8db38be9a12974e7be807c429e8ad9ad
|
contentcuration/contentcuration/utils/asynccommand.py
|
contentcuration/contentcuration/utils/asynccommand.py
|
from abc import abstractmethod
from collections import namedtuple
from django.core.management.base import BaseCommand
from django.core.management.base import CommandError
Progress = namedtuple(
'Progress',
[
'progress',
'total',
'fraction',
]
)
class TaskCommand(BaseCommand):
def handle(self, *args, **options):
self.progresstracker = None
return self.handle_async(*args, **options)
def start_progress(self, total):
self.progresstracker = Progress(progress=0, total=total, fraction=0)
def update_progress(self, increment):
tracker = self.progresstracker
progress = tracker.progress + increment
if progress > tracker.total:
raise CommandError("Progress reaches over 100%.")
fraction = 1.0 * progress / tracker.total
updated_tracker = tracker._replace(progress=progress, fraction=fraction)
self.progresstracker = updated_tracker
@abstractmethod
def handle_async(self, *args, **options):
pass
|
import logging as logmodule
from abc import abstractmethod
from django.core.management.base import BaseCommand
logmodule.basicConfig()
logging = logmodule.getLogger(__name__)
class Progress():
"""
A Progress contains the progress of the tasks, the total number of expected
tasks/data, and the fraction which equals to progress divided by total.
"""
def __init__(self, total):
self.progress = 0
self.total = total
self.fraction = 0
def update(self, increment):
self.progress += increment
# Raise an error when the progress exceeds the total value after increment
if self.progress > self.total:
logging.error("Progress reaches over 100%.")
self.fraction = 1.0 * self.progress / self.total
logging.info("\rProgress: [{}{}] ({}%)".format(
"=" * (int(self.fraction * 100) / 2),
" " * (50 - int(self.fraction * 100) / 2),
int(self.fraction * 100),
))
class TaskCommand(BaseCommand):
"""
A management command that serves as a base command for asynchronous tasks,
with a progresstracker attribute to track the progress of the tasks.
"""
def handle(self, *args, **options):
"""
Define the progress tracker and call handle_async method to handle
different asynchronous task commands.
"""
self.progresstracker = None
return self.handle_async(*args, **options)
def start_progress(self, total):
"""
Initialize the progress tracker.
"""
self.progresstracker = Progress(total)
def update_progress(self, increment):
"""
Update the progress tracker with the given value
"""
self.progresstracker.update(increment)
@abstractmethod
def handle_async(self, *args, **options):
pass
|
Define Progress as a Class and add more comments
|
Define Progress as a Class and add more comments
|
Python
|
mit
|
fle-internal/content-curation,DXCanas/content-curation,fle-internal/content-curation,DXCanas/content-curation,DXCanas/content-curation,fle-internal/content-curation,fle-internal/content-curation,DXCanas/content-curation
|
from abc import abstractmethod
from collections import namedtuple
from django.core.management.base import BaseCommand
from django.core.management.base import CommandError
Progress = namedtuple(
'Progress',
[
'progress',
'total',
'fraction',
]
)
class TaskCommand(BaseCommand):
def handle(self, *args, **options):
self.progresstracker = None
return self.handle_async(*args, **options)
def start_progress(self, total):
self.progresstracker = Progress(progress=0, total=total, fraction=0)
def update_progress(self, increment):
tracker = self.progresstracker
progress = tracker.progress + increment
if progress > tracker.total:
raise CommandError("Progress reaches over 100%.")
fraction = 1.0 * progress / tracker.total
updated_tracker = tracker._replace(progress=progress, fraction=fraction)
self.progresstracker = updated_tracker
@abstractmethod
def handle_async(self, *args, **options):
pass
Define Progress as a Class and add more comments
|
import logging as logmodule
from abc import abstractmethod
from django.core.management.base import BaseCommand
logmodule.basicConfig()
logging = logmodule.getLogger(__name__)
class Progress():
"""
A Progress contains the progress of the tasks, the total number of expected
tasks/data, and the fraction which equals to progress divided by total.
"""
def __init__(self, total):
self.progress = 0
self.total = total
self.fraction = 0
def update(self, increment):
self.progress += increment
# Raise an error when the progress exceeds the total value after increment
if self.progress > self.total:
logging.error("Progress reaches over 100%.")
self.fraction = 1.0 * self.progress / self.total
logging.info("\rProgress: [{}{}] ({}%)".format(
"=" * (int(self.fraction * 100) / 2),
" " * (50 - int(self.fraction * 100) / 2),
int(self.fraction * 100),
))
class TaskCommand(BaseCommand):
"""
A management command that serves as a base command for asynchronous tasks,
with a progresstracker attribute to track the progress of the tasks.
"""
def handle(self, *args, **options):
"""
Define the progress tracker and call handle_async method to handle
different asynchronous task commands.
"""
self.progresstracker = None
return self.handle_async(*args, **options)
def start_progress(self, total):
"""
Initialize the progress tracker.
"""
self.progresstracker = Progress(total)
def update_progress(self, increment):
"""
Update the progress tracker with the given value
"""
self.progresstracker.update(increment)
@abstractmethod
def handle_async(self, *args, **options):
pass
|
<commit_before>from abc import abstractmethod
from collections import namedtuple
from django.core.management.base import BaseCommand
from django.core.management.base import CommandError
Progress = namedtuple(
'Progress',
[
'progress',
'total',
'fraction',
]
)
class TaskCommand(BaseCommand):
def handle(self, *args, **options):
self.progresstracker = None
return self.handle_async(*args, **options)
def start_progress(self, total):
self.progresstracker = Progress(progress=0, total=total, fraction=0)
def update_progress(self, increment):
tracker = self.progresstracker
progress = tracker.progress + increment
if progress > tracker.total:
raise CommandError("Progress reaches over 100%.")
fraction = 1.0 * progress / tracker.total
updated_tracker = tracker._replace(progress=progress, fraction=fraction)
self.progresstracker = updated_tracker
@abstractmethod
def handle_async(self, *args, **options):
pass
<commit_msg>Define Progress as a Class and add more comments<commit_after>
|
import logging as logmodule
from abc import abstractmethod
from django.core.management.base import BaseCommand
logmodule.basicConfig()
logging = logmodule.getLogger(__name__)
class Progress():
"""
A Progress contains the progress of the tasks, the total number of expected
tasks/data, and the fraction which equals to progress divided by total.
"""
def __init__(self, total):
self.progress = 0
self.total = total
self.fraction = 0
def update(self, increment):
self.progress += increment
# Raise an error when the progress exceeds the total value after increment
if self.progress > self.total:
logging.error("Progress reaches over 100%.")
self.fraction = 1.0 * self.progress / self.total
logging.info("\rProgress: [{}{}] ({}%)".format(
"=" * (int(self.fraction * 100) / 2),
" " * (50 - int(self.fraction * 100) / 2),
int(self.fraction * 100),
))
class TaskCommand(BaseCommand):
"""
A management command that serves as a base command for asynchronous tasks,
with a progresstracker attribute to track the progress of the tasks.
"""
def handle(self, *args, **options):
"""
Define the progress tracker and call handle_async method to handle
different asynchronous task commands.
"""
self.progresstracker = None
return self.handle_async(*args, **options)
def start_progress(self, total):
"""
Initialize the progress tracker.
"""
self.progresstracker = Progress(total)
def update_progress(self, increment):
"""
Update the progress tracker with the given value
"""
self.progresstracker.update(increment)
@abstractmethod
def handle_async(self, *args, **options):
pass
|
from abc import abstractmethod
from collections import namedtuple
from django.core.management.base import BaseCommand
from django.core.management.base import CommandError
Progress = namedtuple(
'Progress',
[
'progress',
'total',
'fraction',
]
)
class TaskCommand(BaseCommand):
def handle(self, *args, **options):
self.progresstracker = None
return self.handle_async(*args, **options)
def start_progress(self, total):
self.progresstracker = Progress(progress=0, total=total, fraction=0)
def update_progress(self, increment):
tracker = self.progresstracker
progress = tracker.progress + increment
if progress > tracker.total:
raise CommandError("Progress reaches over 100%.")
fraction = 1.0 * progress / tracker.total
updated_tracker = tracker._replace(progress=progress, fraction=fraction)
self.progresstracker = updated_tracker
@abstractmethod
def handle_async(self, *args, **options):
pass
Define Progress as a Class and add more commentsimport logging as logmodule
from abc import abstractmethod
from django.core.management.base import BaseCommand
logmodule.basicConfig()
logging = logmodule.getLogger(__name__)
class Progress():
"""
A Progress contains the progress of the tasks, the total number of expected
tasks/data, and the fraction which equals to progress divided by total.
"""
def __init__(self, total):
self.progress = 0
self.total = total
self.fraction = 0
def update(self, increment):
self.progress += increment
# Raise an error when the progress exceeds the total value after increment
if self.progress > self.total:
logging.error("Progress reaches over 100%.")
self.fraction = 1.0 * self.progress / self.total
logging.info("\rProgress: [{}{}] ({}%)".format(
"=" * (int(self.fraction * 100) / 2),
" " * (50 - int(self.fraction * 100) / 2),
int(self.fraction * 100),
))
class TaskCommand(BaseCommand):
"""
A management command that serves as a base command for asynchronous tasks,
with a progresstracker attribute to track the progress of the tasks.
"""
def handle(self, *args, **options):
"""
Define the progress tracker and call handle_async method to handle
different asynchronous task commands.
"""
self.progresstracker = None
return self.handle_async(*args, **options)
def start_progress(self, total):
"""
Initialize the progress tracker.
"""
self.progresstracker = Progress(total)
def update_progress(self, increment):
"""
Update the progress tracker with the given value
"""
self.progresstracker.update(increment)
@abstractmethod
def handle_async(self, *args, **options):
pass
|
<commit_before>from abc import abstractmethod
from collections import namedtuple
from django.core.management.base import BaseCommand
from django.core.management.base import CommandError
Progress = namedtuple(
'Progress',
[
'progress',
'total',
'fraction',
]
)
class TaskCommand(BaseCommand):
def handle(self, *args, **options):
self.progresstracker = None
return self.handle_async(*args, **options)
def start_progress(self, total):
self.progresstracker = Progress(progress=0, total=total, fraction=0)
def update_progress(self, increment):
tracker = self.progresstracker
progress = tracker.progress + increment
if progress > tracker.total:
raise CommandError("Progress reaches over 100%.")
fraction = 1.0 * progress / tracker.total
updated_tracker = tracker._replace(progress=progress, fraction=fraction)
self.progresstracker = updated_tracker
@abstractmethod
def handle_async(self, *args, **options):
pass
<commit_msg>Define Progress as a Class and add more comments<commit_after>import logging as logmodule
from abc import abstractmethod
from django.core.management.base import BaseCommand
logmodule.basicConfig()
logging = logmodule.getLogger(__name__)
class Progress():
"""
A Progress contains the progress of the tasks, the total number of expected
tasks/data, and the fraction which equals to progress divided by total.
"""
def __init__(self, total):
self.progress = 0
self.total = total
self.fraction = 0
def update(self, increment):
self.progress += increment
# Raise an error when the progress exceeds the total value after increment
if self.progress > self.total:
logging.error("Progress reaches over 100%.")
self.fraction = 1.0 * self.progress / self.total
logging.info("\rProgress: [{}{}] ({}%)".format(
"=" * (int(self.fraction * 100) / 2),
" " * (50 - int(self.fraction * 100) / 2),
int(self.fraction * 100),
))
class TaskCommand(BaseCommand):
"""
A management command that serves as a base command for asynchronous tasks,
with a progresstracker attribute to track the progress of the tasks.
"""
def handle(self, *args, **options):
"""
Define the progress tracker and call handle_async method to handle
different asynchronous task commands.
"""
self.progresstracker = None
return self.handle_async(*args, **options)
def start_progress(self, total):
"""
Initialize the progress tracker.
"""
self.progresstracker = Progress(total)
def update_progress(self, increment):
"""
Update the progress tracker with the given value
"""
self.progresstracker.update(increment)
@abstractmethod
def handle_async(self, *args, **options):
pass
|
117d7bd313c62ae8ccf5c0565ab1d0538db5423c
|
astrobin/settings/components/haystack.py
|
astrobin/settings/components/haystack.py
|
HAYSTACK_DEFAULT_OPERATOR = 'AND'
HAYSTACK_SEARCH_RESULTS_PER_PAGE = 70
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine',
'URL': 'http://elasticsearch:9200',
'INDEX_NAME': 'astrobin',
'EXCLUDED_INDEXES': [
'threaded_messages.search_indexes.Thread',
'threaded_messages.search_indexes.ThreadIndex',
],
},
}
#if not TESTING:
#HAYSTACK_SIGNAL_PROCESSOR = 'celery_haystack.signals.CelerySignalProcessor'
|
HAYSTACK_DEFAULT_OPERATOR = 'AND'
HAYSTACK_SEARCH_RESULTS_PER_PAGE = 70
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine',
'URL': 'http://elasticsearch:9200',
'INDEX_NAME': 'astrobin',
'EXCLUDED_INDEXES': [
'threaded_messages.search_indexes.Thread',
'threaded_messages.search_indexes.ThreadIndex',
],
},
}
if not TESTING:
HAYSTACK_SIGNAL_PROCESSOR = 'celery_haystack.signals.CelerySignalProcessor'
|
Enable real-time celery-based search index
|
Enable real-time celery-based search index
|
Python
|
agpl-3.0
|
astrobin/astrobin,astrobin/astrobin,astrobin/astrobin,astrobin/astrobin
|
HAYSTACK_DEFAULT_OPERATOR = 'AND'
HAYSTACK_SEARCH_RESULTS_PER_PAGE = 70
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine',
'URL': 'http://elasticsearch:9200',
'INDEX_NAME': 'astrobin',
'EXCLUDED_INDEXES': [
'threaded_messages.search_indexes.Thread',
'threaded_messages.search_indexes.ThreadIndex',
],
},
}
#if not TESTING:
#HAYSTACK_SIGNAL_PROCESSOR = 'celery_haystack.signals.CelerySignalProcessor'
Enable real-time celery-based search index
|
HAYSTACK_DEFAULT_OPERATOR = 'AND'
HAYSTACK_SEARCH_RESULTS_PER_PAGE = 70
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine',
'URL': 'http://elasticsearch:9200',
'INDEX_NAME': 'astrobin',
'EXCLUDED_INDEXES': [
'threaded_messages.search_indexes.Thread',
'threaded_messages.search_indexes.ThreadIndex',
],
},
}
if not TESTING:
HAYSTACK_SIGNAL_PROCESSOR = 'celery_haystack.signals.CelerySignalProcessor'
|
<commit_before>HAYSTACK_DEFAULT_OPERATOR = 'AND'
HAYSTACK_SEARCH_RESULTS_PER_PAGE = 70
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine',
'URL': 'http://elasticsearch:9200',
'INDEX_NAME': 'astrobin',
'EXCLUDED_INDEXES': [
'threaded_messages.search_indexes.Thread',
'threaded_messages.search_indexes.ThreadIndex',
],
},
}
#if not TESTING:
#HAYSTACK_SIGNAL_PROCESSOR = 'celery_haystack.signals.CelerySignalProcessor'
<commit_msg>Enable real-time celery-based search index<commit_after>
|
HAYSTACK_DEFAULT_OPERATOR = 'AND'
HAYSTACK_SEARCH_RESULTS_PER_PAGE = 70
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine',
'URL': 'http://elasticsearch:9200',
'INDEX_NAME': 'astrobin',
'EXCLUDED_INDEXES': [
'threaded_messages.search_indexes.Thread',
'threaded_messages.search_indexes.ThreadIndex',
],
},
}
if not TESTING:
HAYSTACK_SIGNAL_PROCESSOR = 'celery_haystack.signals.CelerySignalProcessor'
|
HAYSTACK_DEFAULT_OPERATOR = 'AND'
HAYSTACK_SEARCH_RESULTS_PER_PAGE = 70
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine',
'URL': 'http://elasticsearch:9200',
'INDEX_NAME': 'astrobin',
'EXCLUDED_INDEXES': [
'threaded_messages.search_indexes.Thread',
'threaded_messages.search_indexes.ThreadIndex',
],
},
}
#if not TESTING:
#HAYSTACK_SIGNAL_PROCESSOR = 'celery_haystack.signals.CelerySignalProcessor'
Enable real-time celery-based search indexHAYSTACK_DEFAULT_OPERATOR = 'AND'
HAYSTACK_SEARCH_RESULTS_PER_PAGE = 70
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine',
'URL': 'http://elasticsearch:9200',
'INDEX_NAME': 'astrobin',
'EXCLUDED_INDEXES': [
'threaded_messages.search_indexes.Thread',
'threaded_messages.search_indexes.ThreadIndex',
],
},
}
if not TESTING:
HAYSTACK_SIGNAL_PROCESSOR = 'celery_haystack.signals.CelerySignalProcessor'
|
<commit_before>HAYSTACK_DEFAULT_OPERATOR = 'AND'
HAYSTACK_SEARCH_RESULTS_PER_PAGE = 70
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine',
'URL': 'http://elasticsearch:9200',
'INDEX_NAME': 'astrobin',
'EXCLUDED_INDEXES': [
'threaded_messages.search_indexes.Thread',
'threaded_messages.search_indexes.ThreadIndex',
],
},
}
#if not TESTING:
#HAYSTACK_SIGNAL_PROCESSOR = 'celery_haystack.signals.CelerySignalProcessor'
<commit_msg>Enable real-time celery-based search index<commit_after>HAYSTACK_DEFAULT_OPERATOR = 'AND'
HAYSTACK_SEARCH_RESULTS_PER_PAGE = 70
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine',
'URL': 'http://elasticsearch:9200',
'INDEX_NAME': 'astrobin',
'EXCLUDED_INDEXES': [
'threaded_messages.search_indexes.Thread',
'threaded_messages.search_indexes.ThreadIndex',
],
},
}
if not TESTING:
HAYSTACK_SIGNAL_PROCESSOR = 'celery_haystack.signals.CelerySignalProcessor'
|
e26573b37f6cb12817b35d3ac0d19fa301fd1a99
|
pytest-{{cookiecutter.plugin_name}}/pytest_{{cookiecutter.plugin_name}}.py
|
pytest-{{cookiecutter.plugin_name}}/pytest_{{cookiecutter.plugin_name}}.py
|
# -*- coding: utf-8 -*-
import pytest
def pytest_addoption(parser):
group = parser.getgroup('{{cookiecutter.plugin_name}}')
group.addoption(
'--foo',
action='store_const',
dest='foo',
help='alias for --foo'
)
|
# -*- coding: utf-8 -*-
import pytest
def pytest_addoption(parser):
group = parser.getgroup('{{cookiecutter.plugin_name}}')
group.addoption(
'--foo',
action='store_const',
dest='foo',
help='alias for --foo'
)
@pytest.fixture
def bar(request):
return request.config.option.foo
|
Implement a custom fixture for the plugin
|
Implement a custom fixture for the plugin
|
Python
|
mit
|
pytest-dev/cookiecutter-pytest-plugin,s0undt3ch/cookiecutter-pytest-plugin,luzfcb/cookiecutter-pytest-plugin
|
# -*- coding: utf-8 -*-
import pytest
def pytest_addoption(parser):
group = parser.getgroup('{{cookiecutter.plugin_name}}')
group.addoption(
'--foo',
action='store_const',
dest='foo',
help='alias for --foo'
)
Implement a custom fixture for the plugin
|
# -*- coding: utf-8 -*-
import pytest
def pytest_addoption(parser):
group = parser.getgroup('{{cookiecutter.plugin_name}}')
group.addoption(
'--foo',
action='store_const',
dest='foo',
help='alias for --foo'
)
@pytest.fixture
def bar(request):
return request.config.option.foo
|
<commit_before># -*- coding: utf-8 -*-
import pytest
def pytest_addoption(parser):
group = parser.getgroup('{{cookiecutter.plugin_name}}')
group.addoption(
'--foo',
action='store_const',
dest='foo',
help='alias for --foo'
)
<commit_msg>Implement a custom fixture for the plugin<commit_after>
|
# -*- coding: utf-8 -*-
import pytest
def pytest_addoption(parser):
group = parser.getgroup('{{cookiecutter.plugin_name}}')
group.addoption(
'--foo',
action='store_const',
dest='foo',
help='alias for --foo'
)
@pytest.fixture
def bar(request):
return request.config.option.foo
|
# -*- coding: utf-8 -*-
import pytest
def pytest_addoption(parser):
group = parser.getgroup('{{cookiecutter.plugin_name}}')
group.addoption(
'--foo',
action='store_const',
dest='foo',
help='alias for --foo'
)
Implement a custom fixture for the plugin# -*- coding: utf-8 -*-
import pytest
def pytest_addoption(parser):
group = parser.getgroup('{{cookiecutter.plugin_name}}')
group.addoption(
'--foo',
action='store_const',
dest='foo',
help='alias for --foo'
)
@pytest.fixture
def bar(request):
return request.config.option.foo
|
<commit_before># -*- coding: utf-8 -*-
import pytest
def pytest_addoption(parser):
group = parser.getgroup('{{cookiecutter.plugin_name}}')
group.addoption(
'--foo',
action='store_const',
dest='foo',
help='alias for --foo'
)
<commit_msg>Implement a custom fixture for the plugin<commit_after># -*- coding: utf-8 -*-
import pytest
def pytest_addoption(parser):
group = parser.getgroup('{{cookiecutter.plugin_name}}')
group.addoption(
'--foo',
action='store_const',
dest='foo',
help='alias for --foo'
)
@pytest.fixture
def bar(request):
return request.config.option.foo
|
aeebd8a4f2255bff03fbb55f3d7d29d822fbb31b
|
logaugment/__init__.py
|
logaugment/__init__.py
|
import logging
class AugmentFilter(logging.Filter):
def __init__(self, name='', args=None):
super(AugmentFilter, self).__init__(name)
self._args = args
def filter(self, record):
if self._args is not None:
data = {}
try:
if callable(self._args):
data = self._args(record)
except NameError: # Python 3.1
if hasattr(self._args, '__call__'):
data = self._args(record)
if isinstance(self._args, dict):
data = self._args
for key, value in data.items():
if record.__dict__.get(key) is None:
setattr(record, key, value)
return True
def add(logger, args):
logger.addFilter(
AugmentFilter(name='logaugment.AugmentFilter', args=args)
)
|
import logging
__title__ = 'logaugment'
__version__ = '0.0.1'
__author__ = 'Simeon Visser'
__email__ = 'simeonvisser@gmail.com'
__license__ = 'MIT'
__copyright__ = 'Copyright 2014 Simeon Visser'
class AugmentFilter(logging.Filter):
def __init__(self, name='', args=None):
super(AugmentFilter, self).__init__(name)
self._args = args
def filter(self, record):
if self._args is not None:
data = {}
try:
if callable(self._args):
data = self._args(record)
except NameError: # Python 3.1
if hasattr(self._args, '__call__'):
data = self._args(record)
if isinstance(self._args, dict):
data = self._args
for key, value in data.items():
if record.__dict__.get(key) is None:
setattr(record, key, value)
return True
def add(logger, args):
logger.addFilter(
AugmentFilter(name='logaugment.AugmentFilter', args=args)
)
|
Add project details to codebase
|
Add project details to codebase
|
Python
|
mit
|
svisser/logaugment
|
import logging
class AugmentFilter(logging.Filter):
def __init__(self, name='', args=None):
super(AugmentFilter, self).__init__(name)
self._args = args
def filter(self, record):
if self._args is not None:
data = {}
try:
if callable(self._args):
data = self._args(record)
except NameError: # Python 3.1
if hasattr(self._args, '__call__'):
data = self._args(record)
if isinstance(self._args, dict):
data = self._args
for key, value in data.items():
if record.__dict__.get(key) is None:
setattr(record, key, value)
return True
def add(logger, args):
logger.addFilter(
AugmentFilter(name='logaugment.AugmentFilter', args=args)
)
Add project details to codebase
|
import logging
__title__ = 'logaugment'
__version__ = '0.0.1'
__author__ = 'Simeon Visser'
__email__ = 'simeonvisser@gmail.com'
__license__ = 'MIT'
__copyright__ = 'Copyright 2014 Simeon Visser'
class AugmentFilter(logging.Filter):
def __init__(self, name='', args=None):
super(AugmentFilter, self).__init__(name)
self._args = args
def filter(self, record):
if self._args is not None:
data = {}
try:
if callable(self._args):
data = self._args(record)
except NameError: # Python 3.1
if hasattr(self._args, '__call__'):
data = self._args(record)
if isinstance(self._args, dict):
data = self._args
for key, value in data.items():
if record.__dict__.get(key) is None:
setattr(record, key, value)
return True
def add(logger, args):
logger.addFilter(
AugmentFilter(name='logaugment.AugmentFilter', args=args)
)
|
<commit_before>import logging
class AugmentFilter(logging.Filter):
def __init__(self, name='', args=None):
super(AugmentFilter, self).__init__(name)
self._args = args
def filter(self, record):
if self._args is not None:
data = {}
try:
if callable(self._args):
data = self._args(record)
except NameError: # Python 3.1
if hasattr(self._args, '__call__'):
data = self._args(record)
if isinstance(self._args, dict):
data = self._args
for key, value in data.items():
if record.__dict__.get(key) is None:
setattr(record, key, value)
return True
def add(logger, args):
logger.addFilter(
AugmentFilter(name='logaugment.AugmentFilter', args=args)
)
<commit_msg>Add project details to codebase<commit_after>
|
import logging
__title__ = 'logaugment'
__version__ = '0.0.1'
__author__ = 'Simeon Visser'
__email__ = 'simeonvisser@gmail.com'
__license__ = 'MIT'
__copyright__ = 'Copyright 2014 Simeon Visser'
class AugmentFilter(logging.Filter):
def __init__(self, name='', args=None):
super(AugmentFilter, self).__init__(name)
self._args = args
def filter(self, record):
if self._args is not None:
data = {}
try:
if callable(self._args):
data = self._args(record)
except NameError: # Python 3.1
if hasattr(self._args, '__call__'):
data = self._args(record)
if isinstance(self._args, dict):
data = self._args
for key, value in data.items():
if record.__dict__.get(key) is None:
setattr(record, key, value)
return True
def add(logger, args):
logger.addFilter(
AugmentFilter(name='logaugment.AugmentFilter', args=args)
)
|
import logging
class AugmentFilter(logging.Filter):
def __init__(self, name='', args=None):
super(AugmentFilter, self).__init__(name)
self._args = args
def filter(self, record):
if self._args is not None:
data = {}
try:
if callable(self._args):
data = self._args(record)
except NameError: # Python 3.1
if hasattr(self._args, '__call__'):
data = self._args(record)
if isinstance(self._args, dict):
data = self._args
for key, value in data.items():
if record.__dict__.get(key) is None:
setattr(record, key, value)
return True
def add(logger, args):
logger.addFilter(
AugmentFilter(name='logaugment.AugmentFilter', args=args)
)
Add project details to codebaseimport logging
__title__ = 'logaugment'
__version__ = '0.0.1'
__author__ = 'Simeon Visser'
__email__ = 'simeonvisser@gmail.com'
__license__ = 'MIT'
__copyright__ = 'Copyright 2014 Simeon Visser'
class AugmentFilter(logging.Filter):
def __init__(self, name='', args=None):
super(AugmentFilter, self).__init__(name)
self._args = args
def filter(self, record):
if self._args is not None:
data = {}
try:
if callable(self._args):
data = self._args(record)
except NameError: # Python 3.1
if hasattr(self._args, '__call__'):
data = self._args(record)
if isinstance(self._args, dict):
data = self._args
for key, value in data.items():
if record.__dict__.get(key) is None:
setattr(record, key, value)
return True
def add(logger, args):
logger.addFilter(
AugmentFilter(name='logaugment.AugmentFilter', args=args)
)
|
<commit_before>import logging
class AugmentFilter(logging.Filter):
def __init__(self, name='', args=None):
super(AugmentFilter, self).__init__(name)
self._args = args
def filter(self, record):
if self._args is not None:
data = {}
try:
if callable(self._args):
data = self._args(record)
except NameError: # Python 3.1
if hasattr(self._args, '__call__'):
data = self._args(record)
if isinstance(self._args, dict):
data = self._args
for key, value in data.items():
if record.__dict__.get(key) is None:
setattr(record, key, value)
return True
def add(logger, args):
logger.addFilter(
AugmentFilter(name='logaugment.AugmentFilter', args=args)
)
<commit_msg>Add project details to codebase<commit_after>import logging
__title__ = 'logaugment'
__version__ = '0.0.1'
__author__ = 'Simeon Visser'
__email__ = 'simeonvisser@gmail.com'
__license__ = 'MIT'
__copyright__ = 'Copyright 2014 Simeon Visser'
class AugmentFilter(logging.Filter):
def __init__(self, name='', args=None):
super(AugmentFilter, self).__init__(name)
self._args = args
def filter(self, record):
if self._args is not None:
data = {}
try:
if callable(self._args):
data = self._args(record)
except NameError: # Python 3.1
if hasattr(self._args, '__call__'):
data = self._args(record)
if isinstance(self._args, dict):
data = self._args
for key, value in data.items():
if record.__dict__.get(key) is None:
setattr(record, key, value)
return True
def add(logger, args):
logger.addFilter(
AugmentFilter(name='logaugment.AugmentFilter', args=args)
)
|
a9accd5460157e323e8514178d3e7bc9d2fa8667
|
dn1/kolona_vozil_test.py
|
dn1/kolona_vozil_test.py
|
__author__ = 'Nino Bašić <nino.basic@fmf.uni-lj.si>'
import unittest
from jadrolinija import KolonaVozil
class KolonaVozilTest(unittest.TestCase):
def test_init(self):
kv = KolonaVozil(2000)
self.assertEqual(kv.max_dolzina, 2000)
self.assertEqual(kv.zasedenost, 0)
if __name__ == '__main__':
unittest.main()
|
__author__ = 'Nino Bašić <nino.basic@fmf.uni-lj.si>'
import unittest
from jadrolinija import KolonaVozil, Vozilo
class KolonaVozilTest(unittest.TestCase):
def test_init(self):
kv = KolonaVozil(2000)
self.assertEqual(kv.max_dolzina, 2000)
self.assertEqual(kv.zasedenost, 0)
def test_vkrcaj(self):
kv = KolonaVozil(1000)
vozilo1 = Vozilo('NM DK-34J', 425)
kv.vkrcaj(vozilo1)
self.assertEqual(kv.zasedenost, 425)
vozilo2 = Vozilo('LJ N6-03K', 445)
kv.vkrcaj(vozilo2)
self.assertEqual(kv.zasedenost, 425 + 10 + 445)
vozilo3 = Vozilo('KP JB-P20', 385)
with self.assertRaisesRegexp(ValueError, 'ni dovolj prostora'):
kv.vkrcaj(vozilo3)
def test_izkrcaj(self):
kv = KolonaVozil(1000)
vozilo1 = Vozilo('NM DK-34J', 425)
kv.vkrcaj(vozilo1)
vozilo2 = Vozilo('LJ N6-03K', 445)
kv.vkrcaj(vozilo2)
self.assertIs(kv.izkrcaj(), vozilo1)
self.assertEqual(kv.zasedenost, 425 + 10 + 445)
with self.assertRaisesRegexp(ValueError, 'ni dovolj prostora'):
kv.vkrcaj(vozilo1)
self.assertIs(kv.izkrcaj(), vozilo2)
self.assertEqual(kv.zasedenost, 0)
with self.assertRaisesRegexp(ValueError, 'kolona je prazna'):
kv.izkrcaj()
if __name__ == '__main__':
unittest.main()
|
Update unittests for Task 4
|
Update unittests for Task 4
|
Python
|
mit
|
nbasic/racunalnistvo-1
|
__author__ = 'Nino Bašić <nino.basic@fmf.uni-lj.si>'
import unittest
from jadrolinija import KolonaVozil
class KolonaVozilTest(unittest.TestCase):
def test_init(self):
kv = KolonaVozil(2000)
self.assertEqual(kv.max_dolzina, 2000)
self.assertEqual(kv.zasedenost, 0)
if __name__ == '__main__':
unittest.main()
Update unittests for Task 4
|
__author__ = 'Nino Bašić <nino.basic@fmf.uni-lj.si>'
import unittest
from jadrolinija import KolonaVozil, Vozilo
class KolonaVozilTest(unittest.TestCase):
def test_init(self):
kv = KolonaVozil(2000)
self.assertEqual(kv.max_dolzina, 2000)
self.assertEqual(kv.zasedenost, 0)
def test_vkrcaj(self):
kv = KolonaVozil(1000)
vozilo1 = Vozilo('NM DK-34J', 425)
kv.vkrcaj(vozilo1)
self.assertEqual(kv.zasedenost, 425)
vozilo2 = Vozilo('LJ N6-03K', 445)
kv.vkrcaj(vozilo2)
self.assertEqual(kv.zasedenost, 425 + 10 + 445)
vozilo3 = Vozilo('KP JB-P20', 385)
with self.assertRaisesRegexp(ValueError, 'ni dovolj prostora'):
kv.vkrcaj(vozilo3)
def test_izkrcaj(self):
kv = KolonaVozil(1000)
vozilo1 = Vozilo('NM DK-34J', 425)
kv.vkrcaj(vozilo1)
vozilo2 = Vozilo('LJ N6-03K', 445)
kv.vkrcaj(vozilo2)
self.assertIs(kv.izkrcaj(), vozilo1)
self.assertEqual(kv.zasedenost, 425 + 10 + 445)
with self.assertRaisesRegexp(ValueError, 'ni dovolj prostora'):
kv.vkrcaj(vozilo1)
self.assertIs(kv.izkrcaj(), vozilo2)
self.assertEqual(kv.zasedenost, 0)
with self.assertRaisesRegexp(ValueError, 'kolona je prazna'):
kv.izkrcaj()
if __name__ == '__main__':
unittest.main()
|
<commit_before>__author__ = 'Nino Bašić <nino.basic@fmf.uni-lj.si>'
import unittest
from jadrolinija import KolonaVozil
class KolonaVozilTest(unittest.TestCase):
def test_init(self):
kv = KolonaVozil(2000)
self.assertEqual(kv.max_dolzina, 2000)
self.assertEqual(kv.zasedenost, 0)
if __name__ == '__main__':
unittest.main()
<commit_msg>Update unittests for Task 4<commit_after>
|
__author__ = 'Nino Bašić <nino.basic@fmf.uni-lj.si>'
import unittest
from jadrolinija import KolonaVozil, Vozilo
class KolonaVozilTest(unittest.TestCase):
def test_init(self):
kv = KolonaVozil(2000)
self.assertEqual(kv.max_dolzina, 2000)
self.assertEqual(kv.zasedenost, 0)
def test_vkrcaj(self):
kv = KolonaVozil(1000)
vozilo1 = Vozilo('NM DK-34J', 425)
kv.vkrcaj(vozilo1)
self.assertEqual(kv.zasedenost, 425)
vozilo2 = Vozilo('LJ N6-03K', 445)
kv.vkrcaj(vozilo2)
self.assertEqual(kv.zasedenost, 425 + 10 + 445)
vozilo3 = Vozilo('KP JB-P20', 385)
with self.assertRaisesRegexp(ValueError, 'ni dovolj prostora'):
kv.vkrcaj(vozilo3)
def test_izkrcaj(self):
kv = KolonaVozil(1000)
vozilo1 = Vozilo('NM DK-34J', 425)
kv.vkrcaj(vozilo1)
vozilo2 = Vozilo('LJ N6-03K', 445)
kv.vkrcaj(vozilo2)
self.assertIs(kv.izkrcaj(), vozilo1)
self.assertEqual(kv.zasedenost, 425 + 10 + 445)
with self.assertRaisesRegexp(ValueError, 'ni dovolj prostora'):
kv.vkrcaj(vozilo1)
self.assertIs(kv.izkrcaj(), vozilo2)
self.assertEqual(kv.zasedenost, 0)
with self.assertRaisesRegexp(ValueError, 'kolona je prazna'):
kv.izkrcaj()
if __name__ == '__main__':
unittest.main()
|
__author__ = 'Nino Bašić <nino.basic@fmf.uni-lj.si>'
import unittest
from jadrolinija import KolonaVozil
class KolonaVozilTest(unittest.TestCase):
def test_init(self):
kv = KolonaVozil(2000)
self.assertEqual(kv.max_dolzina, 2000)
self.assertEqual(kv.zasedenost, 0)
if __name__ == '__main__':
unittest.main()
Update unittests for Task 4__author__ = 'Nino Bašić <nino.basic@fmf.uni-lj.si>'
import unittest
from jadrolinija import KolonaVozil, Vozilo
class KolonaVozilTest(unittest.TestCase):
def test_init(self):
kv = KolonaVozil(2000)
self.assertEqual(kv.max_dolzina, 2000)
self.assertEqual(kv.zasedenost, 0)
def test_vkrcaj(self):
kv = KolonaVozil(1000)
vozilo1 = Vozilo('NM DK-34J', 425)
kv.vkrcaj(vozilo1)
self.assertEqual(kv.zasedenost, 425)
vozilo2 = Vozilo('LJ N6-03K', 445)
kv.vkrcaj(vozilo2)
self.assertEqual(kv.zasedenost, 425 + 10 + 445)
vozilo3 = Vozilo('KP JB-P20', 385)
with self.assertRaisesRegexp(ValueError, 'ni dovolj prostora'):
kv.vkrcaj(vozilo3)
def test_izkrcaj(self):
kv = KolonaVozil(1000)
vozilo1 = Vozilo('NM DK-34J', 425)
kv.vkrcaj(vozilo1)
vozilo2 = Vozilo('LJ N6-03K', 445)
kv.vkrcaj(vozilo2)
self.assertIs(kv.izkrcaj(), vozilo1)
self.assertEqual(kv.zasedenost, 425 + 10 + 445)
with self.assertRaisesRegexp(ValueError, 'ni dovolj prostora'):
kv.vkrcaj(vozilo1)
self.assertIs(kv.izkrcaj(), vozilo2)
self.assertEqual(kv.zasedenost, 0)
with self.assertRaisesRegexp(ValueError, 'kolona je prazna'):
kv.izkrcaj()
if __name__ == '__main__':
unittest.main()
|
<commit_before>__author__ = 'Nino Bašić <nino.basic@fmf.uni-lj.si>'
import unittest
from jadrolinija import KolonaVozil
class KolonaVozilTest(unittest.TestCase):
def test_init(self):
kv = KolonaVozil(2000)
self.assertEqual(kv.max_dolzina, 2000)
self.assertEqual(kv.zasedenost, 0)
if __name__ == '__main__':
unittest.main()
<commit_msg>Update unittests for Task 4<commit_after>__author__ = 'Nino Bašić <nino.basic@fmf.uni-lj.si>'
import unittest
from jadrolinija import KolonaVozil, Vozilo
class KolonaVozilTest(unittest.TestCase):
def test_init(self):
kv = KolonaVozil(2000)
self.assertEqual(kv.max_dolzina, 2000)
self.assertEqual(kv.zasedenost, 0)
def test_vkrcaj(self):
kv = KolonaVozil(1000)
vozilo1 = Vozilo('NM DK-34J', 425)
kv.vkrcaj(vozilo1)
self.assertEqual(kv.zasedenost, 425)
vozilo2 = Vozilo('LJ N6-03K', 445)
kv.vkrcaj(vozilo2)
self.assertEqual(kv.zasedenost, 425 + 10 + 445)
vozilo3 = Vozilo('KP JB-P20', 385)
with self.assertRaisesRegexp(ValueError, 'ni dovolj prostora'):
kv.vkrcaj(vozilo3)
def test_izkrcaj(self):
kv = KolonaVozil(1000)
vozilo1 = Vozilo('NM DK-34J', 425)
kv.vkrcaj(vozilo1)
vozilo2 = Vozilo('LJ N6-03K', 445)
kv.vkrcaj(vozilo2)
self.assertIs(kv.izkrcaj(), vozilo1)
self.assertEqual(kv.zasedenost, 425 + 10 + 445)
with self.assertRaisesRegexp(ValueError, 'ni dovolj prostora'):
kv.vkrcaj(vozilo1)
self.assertIs(kv.izkrcaj(), vozilo2)
self.assertEqual(kv.zasedenost, 0)
with self.assertRaisesRegexp(ValueError, 'kolona je prazna'):
kv.izkrcaj()
if __name__ == '__main__':
unittest.main()
|
05e651b0e606f216a78c61ccfb441ce7ed41d852
|
reg/compat.py
|
reg/compat.py
|
import sys
from types import MethodType
# True if we are running on Python 3.
PY3 = sys.version_info[0] == 3
if PY3:
string_types = (str,)
else: # pragma: no cover
string_types = (basestring,) # noqa
if PY3:
def create_method_for_class(callable, type):
return MethodType(callable, type)
def create_method_for_instance(callable, obj):
return MethodType(callable, obj)
else:
def create_method_for_class(callable, type):
return MethodType(callable, None, type)
def create_method_for_instance(callable, obj):
return MethodType(callable, obj, obj.__class__)
|
import sys
from types import MethodType
# True if we are running on Python 3.
PY3 = sys.version_info[0] == 3
if PY3:
string_types = (str,)
else: # pragma: no cover
string_types = (basestring,) # noqa
if PY3:
def create_method_for_class(callable, type):
return MethodType(callable, type)
def create_method_for_instance(callable, obj):
return MethodType(callable, obj)
else: # pragma: no cover
def create_method_for_class(callable, type):
return MethodType(callable, None, type)
def create_method_for_instance(callable, obj):
return MethodType(callable, obj, obj.__class__)
|
Exclude from coverage the code pathways that are specific to Python 2.
|
Exclude from coverage the code pathways that are specific to Python 2.
|
Python
|
bsd-3-clause
|
morepath/reg,taschini/reg
|
import sys
from types import MethodType
# True if we are running on Python 3.
PY3 = sys.version_info[0] == 3
if PY3:
string_types = (str,)
else: # pragma: no cover
string_types = (basestring,) # noqa
if PY3:
def create_method_for_class(callable, type):
return MethodType(callable, type)
def create_method_for_instance(callable, obj):
return MethodType(callable, obj)
else:
def create_method_for_class(callable, type):
return MethodType(callable, None, type)
def create_method_for_instance(callable, obj):
return MethodType(callable, obj, obj.__class__)
Exclude from coverage the code pathways that are specific to Python 2.
|
import sys
from types import MethodType
# True if we are running on Python 3.
PY3 = sys.version_info[0] == 3
if PY3:
string_types = (str,)
else: # pragma: no cover
string_types = (basestring,) # noqa
if PY3:
def create_method_for_class(callable, type):
return MethodType(callable, type)
def create_method_for_instance(callable, obj):
return MethodType(callable, obj)
else: # pragma: no cover
def create_method_for_class(callable, type):
return MethodType(callable, None, type)
def create_method_for_instance(callable, obj):
return MethodType(callable, obj, obj.__class__)
|
<commit_before>import sys
from types import MethodType
# True if we are running on Python 3.
PY3 = sys.version_info[0] == 3
if PY3:
string_types = (str,)
else: # pragma: no cover
string_types = (basestring,) # noqa
if PY3:
def create_method_for_class(callable, type):
return MethodType(callable, type)
def create_method_for_instance(callable, obj):
return MethodType(callable, obj)
else:
def create_method_for_class(callable, type):
return MethodType(callable, None, type)
def create_method_for_instance(callable, obj):
return MethodType(callable, obj, obj.__class__)
<commit_msg>Exclude from coverage the code pathways that are specific to Python 2.<commit_after>
|
import sys
from types import MethodType
# True if we are running on Python 3.
PY3 = sys.version_info[0] == 3
if PY3:
string_types = (str,)
else: # pragma: no cover
string_types = (basestring,) # noqa
if PY3:
def create_method_for_class(callable, type):
return MethodType(callable, type)
def create_method_for_instance(callable, obj):
return MethodType(callable, obj)
else: # pragma: no cover
def create_method_for_class(callable, type):
return MethodType(callable, None, type)
def create_method_for_instance(callable, obj):
return MethodType(callable, obj, obj.__class__)
|
import sys
from types import MethodType
# True if we are running on Python 3.
PY3 = sys.version_info[0] == 3
if PY3:
string_types = (str,)
else: # pragma: no cover
string_types = (basestring,) # noqa
if PY3:
def create_method_for_class(callable, type):
return MethodType(callable, type)
def create_method_for_instance(callable, obj):
return MethodType(callable, obj)
else:
def create_method_for_class(callable, type):
return MethodType(callable, None, type)
def create_method_for_instance(callable, obj):
return MethodType(callable, obj, obj.__class__)
Exclude from coverage the code pathways that are specific to Python 2.import sys
from types import MethodType
# True if we are running on Python 3.
PY3 = sys.version_info[0] == 3
if PY3:
string_types = (str,)
else: # pragma: no cover
string_types = (basestring,) # noqa
if PY3:
def create_method_for_class(callable, type):
return MethodType(callable, type)
def create_method_for_instance(callable, obj):
return MethodType(callable, obj)
else: # pragma: no cover
def create_method_for_class(callable, type):
return MethodType(callable, None, type)
def create_method_for_instance(callable, obj):
return MethodType(callable, obj, obj.__class__)
|
<commit_before>import sys
from types import MethodType
# True if we are running on Python 3.
PY3 = sys.version_info[0] == 3
if PY3:
string_types = (str,)
else: # pragma: no cover
string_types = (basestring,) # noqa
if PY3:
def create_method_for_class(callable, type):
return MethodType(callable, type)
def create_method_for_instance(callable, obj):
return MethodType(callable, obj)
else:
def create_method_for_class(callable, type):
return MethodType(callable, None, type)
def create_method_for_instance(callable, obj):
return MethodType(callable, obj, obj.__class__)
<commit_msg>Exclude from coverage the code pathways that are specific to Python 2.<commit_after>import sys
from types import MethodType
# True if we are running on Python 3.
PY3 = sys.version_info[0] == 3
if PY3:
string_types = (str,)
else: # pragma: no cover
string_types = (basestring,) # noqa
if PY3:
def create_method_for_class(callable, type):
return MethodType(callable, type)
def create_method_for_instance(callable, obj):
return MethodType(callable, obj)
else: # pragma: no cover
def create_method_for_class(callable, type):
return MethodType(callable, None, type)
def create_method_for_instance(callable, obj):
return MethodType(callable, obj, obj.__class__)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.