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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6559de6724c5e53bed3599c6ec21c968e3a71b83
|
openspending/tests/controllers/test_rest.py
|
openspending/tests/controllers/test_rest.py
|
from openspending.model.dataset import Dataset
from openspending.tests.base import ControllerTestCase
from openspending.tests.helpers import load_fixture
from pylons import url
class TestRestController(ControllerTestCase):
def setup(self):
super(TestRestController, self).setup()
load_fixture('cra')
self.cra = Dataset.by_name('cra')
def test_index(self):
response = self.app.get(url(controller='rest', action='index'))
for word in ['/cra', 'entries']:
assert word in response, response
def test_dataset(self):
response = self.app.get(url(controller='dataset',
action='view',
format='json',
dataset=self.cra.name))
assert '"name": "cra"' in response, response
def test_entry(self):
q = self.cra['from'].alias.c.name == 'Dept047'
example = list(self.cra.entries(q, limit=1)).pop()
response = self.app.get(url(controller='entry',
action='view',
dataset=self.cra.name,
format='json',
id=str(example['id'])))
assert '"id":' in response, response
assert '"cofog1":' in response, response
assert '"from":' in response, response
assert '"Dept047"' in response, response
|
from openspending.model.dataset import Dataset
from openspending.tests.base import ControllerTestCase
from openspending.tests.helpers import load_fixture
from pylons import url
class TestRestController(ControllerTestCase):
def setup(self):
super(TestRestController, self).setup()
load_fixture('cra')
self.cra = Dataset.by_name('cra')
def test_dataset(self):
response = self.app.get(url(controller='dataset',
action='view',
format='json',
dataset=self.cra.name))
assert '"name": "cra"' in response, response
def test_entry(self):
q = self.cra['from'].alias.c.name == 'Dept047'
example = list(self.cra.entries(q, limit=1)).pop()
response = self.app.get(url(controller='entry',
action='view',
dataset=self.cra.name,
format='json',
id=str(example['id'])))
assert '"id":' in response, response
assert '"cofog1":' in response, response
assert '"from":' in response, response
assert '"Dept047"' in response, response
|
Remove test for rest controller.
|
Remove test for rest controller.
|
Python
|
agpl-3.0
|
nathanhilbert/FPA_Core,pudo/spendb,nathanhilbert/FPA_Core,openspending/spendb,spendb/spendb,openspending/spendb,CivicVision/datahub,openspending/spendb,CivicVision/datahub,nathanhilbert/FPA_Core,johnjohndoe/spendb,spendb/spendb,spendb/spendb,USStateDept/FPA_Core,pudo/spendb,johnjohndoe/spendb,CivicVision/datahub,USStateDept/FPA_Core,pudo/spendb,USStateDept/FPA_Core,johnjohndoe/spendb
|
from openspending.model.dataset import Dataset
from openspending.tests.base import ControllerTestCase
from openspending.tests.helpers import load_fixture
from pylons import url
class TestRestController(ControllerTestCase):
def setup(self):
super(TestRestController, self).setup()
load_fixture('cra')
self.cra = Dataset.by_name('cra')
def test_index(self):
response = self.app.get(url(controller='rest', action='index'))
for word in ['/cra', 'entries']:
assert word in response, response
def test_dataset(self):
response = self.app.get(url(controller='dataset',
action='view',
format='json',
dataset=self.cra.name))
assert '"name": "cra"' in response, response
def test_entry(self):
q = self.cra['from'].alias.c.name == 'Dept047'
example = list(self.cra.entries(q, limit=1)).pop()
response = self.app.get(url(controller='entry',
action='view',
dataset=self.cra.name,
format='json',
id=str(example['id'])))
assert '"id":' in response, response
assert '"cofog1":' in response, response
assert '"from":' in response, response
assert '"Dept047"' in response, response
Remove test for rest controller.
|
from openspending.model.dataset import Dataset
from openspending.tests.base import ControllerTestCase
from openspending.tests.helpers import load_fixture
from pylons import url
class TestRestController(ControllerTestCase):
def setup(self):
super(TestRestController, self).setup()
load_fixture('cra')
self.cra = Dataset.by_name('cra')
def test_dataset(self):
response = self.app.get(url(controller='dataset',
action='view',
format='json',
dataset=self.cra.name))
assert '"name": "cra"' in response, response
def test_entry(self):
q = self.cra['from'].alias.c.name == 'Dept047'
example = list(self.cra.entries(q, limit=1)).pop()
response = self.app.get(url(controller='entry',
action='view',
dataset=self.cra.name,
format='json',
id=str(example['id'])))
assert '"id":' in response, response
assert '"cofog1":' in response, response
assert '"from":' in response, response
assert '"Dept047"' in response, response
|
<commit_before>from openspending.model.dataset import Dataset
from openspending.tests.base import ControllerTestCase
from openspending.tests.helpers import load_fixture
from pylons import url
class TestRestController(ControllerTestCase):
def setup(self):
super(TestRestController, self).setup()
load_fixture('cra')
self.cra = Dataset.by_name('cra')
def test_index(self):
response = self.app.get(url(controller='rest', action='index'))
for word in ['/cra', 'entries']:
assert word in response, response
def test_dataset(self):
response = self.app.get(url(controller='dataset',
action='view',
format='json',
dataset=self.cra.name))
assert '"name": "cra"' in response, response
def test_entry(self):
q = self.cra['from'].alias.c.name == 'Dept047'
example = list(self.cra.entries(q, limit=1)).pop()
response = self.app.get(url(controller='entry',
action='view',
dataset=self.cra.name,
format='json',
id=str(example['id'])))
assert '"id":' in response, response
assert '"cofog1":' in response, response
assert '"from":' in response, response
assert '"Dept047"' in response, response
<commit_msg>Remove test for rest controller. <commit_after>
|
from openspending.model.dataset import Dataset
from openspending.tests.base import ControllerTestCase
from openspending.tests.helpers import load_fixture
from pylons import url
class TestRestController(ControllerTestCase):
def setup(self):
super(TestRestController, self).setup()
load_fixture('cra')
self.cra = Dataset.by_name('cra')
def test_dataset(self):
response = self.app.get(url(controller='dataset',
action='view',
format='json',
dataset=self.cra.name))
assert '"name": "cra"' in response, response
def test_entry(self):
q = self.cra['from'].alias.c.name == 'Dept047'
example = list(self.cra.entries(q, limit=1)).pop()
response = self.app.get(url(controller='entry',
action='view',
dataset=self.cra.name,
format='json',
id=str(example['id'])))
assert '"id":' in response, response
assert '"cofog1":' in response, response
assert '"from":' in response, response
assert '"Dept047"' in response, response
|
from openspending.model.dataset import Dataset
from openspending.tests.base import ControllerTestCase
from openspending.tests.helpers import load_fixture
from pylons import url
class TestRestController(ControllerTestCase):
def setup(self):
super(TestRestController, self).setup()
load_fixture('cra')
self.cra = Dataset.by_name('cra')
def test_index(self):
response = self.app.get(url(controller='rest', action='index'))
for word in ['/cra', 'entries']:
assert word in response, response
def test_dataset(self):
response = self.app.get(url(controller='dataset',
action='view',
format='json',
dataset=self.cra.name))
assert '"name": "cra"' in response, response
def test_entry(self):
q = self.cra['from'].alias.c.name == 'Dept047'
example = list(self.cra.entries(q, limit=1)).pop()
response = self.app.get(url(controller='entry',
action='view',
dataset=self.cra.name,
format='json',
id=str(example['id'])))
assert '"id":' in response, response
assert '"cofog1":' in response, response
assert '"from":' in response, response
assert '"Dept047"' in response, response
Remove test for rest controller. from openspending.model.dataset import Dataset
from openspending.tests.base import ControllerTestCase
from openspending.tests.helpers import load_fixture
from pylons import url
class TestRestController(ControllerTestCase):
def setup(self):
super(TestRestController, self).setup()
load_fixture('cra')
self.cra = Dataset.by_name('cra')
def test_dataset(self):
response = self.app.get(url(controller='dataset',
action='view',
format='json',
dataset=self.cra.name))
assert '"name": "cra"' in response, response
def test_entry(self):
q = self.cra['from'].alias.c.name == 'Dept047'
example = list(self.cra.entries(q, limit=1)).pop()
response = self.app.get(url(controller='entry',
action='view',
dataset=self.cra.name,
format='json',
id=str(example['id'])))
assert '"id":' in response, response
assert '"cofog1":' in response, response
assert '"from":' in response, response
assert '"Dept047"' in response, response
|
<commit_before>from openspending.model.dataset import Dataset
from openspending.tests.base import ControllerTestCase
from openspending.tests.helpers import load_fixture
from pylons import url
class TestRestController(ControllerTestCase):
def setup(self):
super(TestRestController, self).setup()
load_fixture('cra')
self.cra = Dataset.by_name('cra')
def test_index(self):
response = self.app.get(url(controller='rest', action='index'))
for word in ['/cra', 'entries']:
assert word in response, response
def test_dataset(self):
response = self.app.get(url(controller='dataset',
action='view',
format='json',
dataset=self.cra.name))
assert '"name": "cra"' in response, response
def test_entry(self):
q = self.cra['from'].alias.c.name == 'Dept047'
example = list(self.cra.entries(q, limit=1)).pop()
response = self.app.get(url(controller='entry',
action='view',
dataset=self.cra.name,
format='json',
id=str(example['id'])))
assert '"id":' in response, response
assert '"cofog1":' in response, response
assert '"from":' in response, response
assert '"Dept047"' in response, response
<commit_msg>Remove test for rest controller. <commit_after>from openspending.model.dataset import Dataset
from openspending.tests.base import ControllerTestCase
from openspending.tests.helpers import load_fixture
from pylons import url
class TestRestController(ControllerTestCase):
def setup(self):
super(TestRestController, self).setup()
load_fixture('cra')
self.cra = Dataset.by_name('cra')
def test_dataset(self):
response = self.app.get(url(controller='dataset',
action='view',
format='json',
dataset=self.cra.name))
assert '"name": "cra"' in response, response
def test_entry(self):
q = self.cra['from'].alias.c.name == 'Dept047'
example = list(self.cra.entries(q, limit=1)).pop()
response = self.app.get(url(controller='entry',
action='view',
dataset=self.cra.name,
format='json',
id=str(example['id'])))
assert '"id":' in response, response
assert '"cofog1":' in response, response
assert '"from":' in response, response
assert '"Dept047"' in response, response
|
42584d8504daab56ced4447ccc08723999c5ca5b
|
linter.py
|
linter.py
|
#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Ivan Sobolev
# Copyright (c) 2016 Ivan Sobolev
#
# License: MIT
#
"""This module exports the Bemlint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class Bemlint(NodeLinter):
"""Provides an interface to bemlint."""
name = 'bemlint'
cmd = 'bemlint @ ${args}'
config_file = ('--config', '.bemlint.json')
regex = (
r'^.+?: line (?P<line>\d+), col (?P<col>\d+), '
r'(?:(?P<error>Error)|(?P<warning>Warning)) - '
r'(?P<message>.+)'
)
multiline = False
line_col_base = (1, 1)
error_stream = util.STREAM_BOTH
tempfile_suffix = 'bem'
defaults = {
'selector': 'text.html',
'--format': 'compact',
}
# the following attributes are marked useless for SL4
version_args = '--version'
version_re = r'v(?P<version>\d+\.\d+\.\d+)'
version_requirement = '>= 1.4.5'
|
#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Ivan Sobolev
# Copyright (c) 2016 Ivan Sobolev
#
# License: MIT
#
"""This module exports the Bemlint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class Bemlint(NodeLinter):
"""Provides an interface to bemlint."""
name = 'bemlint'
cmd = 'bemlint ${temp_file} ${args}'
config_file = ('--config', '.bemlint.json')
regex = (
r'^.+?: line (?P<line>\d+), col (?P<col>\d+), '
r'(?:(?P<error>Error)|(?P<warning>Warning)) - '
r'(?P<message>.+)'
)
multiline = False
line_col_base = (1, 1)
error_stream = util.STREAM_BOTH
tempfile_suffix = 'bem'
defaults = {
'selector': 'text.html',
'--format': 'compact',
}
# the following attributes are marked useless for SL4
version_args = '--version'
version_re = r'v(?P<version>\d+\.\d+\.\d+)'
version_requirement = '>= 1.4.5'
|
Mark usage of temporary files in `cmd`
|
Mark usage of temporary files in `cmd`
The marker `@` was ambiguous in SublimeLinter. Its usage has been deprecated in favor of explicit markers like `$temp_file`.
|
Python
|
mit
|
DesTincT/SublimeLinter-contrib-bemlint
|
#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Ivan Sobolev
# Copyright (c) 2016 Ivan Sobolev
#
# License: MIT
#
"""This module exports the Bemlint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class Bemlint(NodeLinter):
"""Provides an interface to bemlint."""
name = 'bemlint'
cmd = 'bemlint @ ${args}'
config_file = ('--config', '.bemlint.json')
regex = (
r'^.+?: line (?P<line>\d+), col (?P<col>\d+), '
r'(?:(?P<error>Error)|(?P<warning>Warning)) - '
r'(?P<message>.+)'
)
multiline = False
line_col_base = (1, 1)
error_stream = util.STREAM_BOTH
tempfile_suffix = 'bem'
defaults = {
'selector': 'text.html',
'--format': 'compact',
}
# the following attributes are marked useless for SL4
version_args = '--version'
version_re = r'v(?P<version>\d+\.\d+\.\d+)'
version_requirement = '>= 1.4.5'
Mark usage of temporary files in `cmd`
The marker `@` was ambiguous in SublimeLinter. Its usage has been deprecated in favor of explicit markers like `$temp_file`.
|
#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Ivan Sobolev
# Copyright (c) 2016 Ivan Sobolev
#
# License: MIT
#
"""This module exports the Bemlint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class Bemlint(NodeLinter):
"""Provides an interface to bemlint."""
name = 'bemlint'
cmd = 'bemlint ${temp_file} ${args}'
config_file = ('--config', '.bemlint.json')
regex = (
r'^.+?: line (?P<line>\d+), col (?P<col>\d+), '
r'(?:(?P<error>Error)|(?P<warning>Warning)) - '
r'(?P<message>.+)'
)
multiline = False
line_col_base = (1, 1)
error_stream = util.STREAM_BOTH
tempfile_suffix = 'bem'
defaults = {
'selector': 'text.html',
'--format': 'compact',
}
# the following attributes are marked useless for SL4
version_args = '--version'
version_re = r'v(?P<version>\d+\.\d+\.\d+)'
version_requirement = '>= 1.4.5'
|
<commit_before>
#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Ivan Sobolev
# Copyright (c) 2016 Ivan Sobolev
#
# License: MIT
#
"""This module exports the Bemlint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class Bemlint(NodeLinter):
"""Provides an interface to bemlint."""
name = 'bemlint'
cmd = 'bemlint @ ${args}'
config_file = ('--config', '.bemlint.json')
regex = (
r'^.+?: line (?P<line>\d+), col (?P<col>\d+), '
r'(?:(?P<error>Error)|(?P<warning>Warning)) - '
r'(?P<message>.+)'
)
multiline = False
line_col_base = (1, 1)
error_stream = util.STREAM_BOTH
tempfile_suffix = 'bem'
defaults = {
'selector': 'text.html',
'--format': 'compact',
}
# the following attributes are marked useless for SL4
version_args = '--version'
version_re = r'v(?P<version>\d+\.\d+\.\d+)'
version_requirement = '>= 1.4.5'
<commit_msg>Mark usage of temporary files in `cmd`
The marker `@` was ambiguous in SublimeLinter. Its usage has been deprecated in favor of explicit markers like `$temp_file`.<commit_after>
|
#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Ivan Sobolev
# Copyright (c) 2016 Ivan Sobolev
#
# License: MIT
#
"""This module exports the Bemlint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class Bemlint(NodeLinter):
"""Provides an interface to bemlint."""
name = 'bemlint'
cmd = 'bemlint ${temp_file} ${args}'
config_file = ('--config', '.bemlint.json')
regex = (
r'^.+?: line (?P<line>\d+), col (?P<col>\d+), '
r'(?:(?P<error>Error)|(?P<warning>Warning)) - '
r'(?P<message>.+)'
)
multiline = False
line_col_base = (1, 1)
error_stream = util.STREAM_BOTH
tempfile_suffix = 'bem'
defaults = {
'selector': 'text.html',
'--format': 'compact',
}
# the following attributes are marked useless for SL4
version_args = '--version'
version_re = r'v(?P<version>\d+\.\d+\.\d+)'
version_requirement = '>= 1.4.5'
|
#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Ivan Sobolev
# Copyright (c) 2016 Ivan Sobolev
#
# License: MIT
#
"""This module exports the Bemlint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class Bemlint(NodeLinter):
"""Provides an interface to bemlint."""
name = 'bemlint'
cmd = 'bemlint @ ${args}'
config_file = ('--config', '.bemlint.json')
regex = (
r'^.+?: line (?P<line>\d+), col (?P<col>\d+), '
r'(?:(?P<error>Error)|(?P<warning>Warning)) - '
r'(?P<message>.+)'
)
multiline = False
line_col_base = (1, 1)
error_stream = util.STREAM_BOTH
tempfile_suffix = 'bem'
defaults = {
'selector': 'text.html',
'--format': 'compact',
}
# the following attributes are marked useless for SL4
version_args = '--version'
version_re = r'v(?P<version>\d+\.\d+\.\d+)'
version_requirement = '>= 1.4.5'
Mark usage of temporary files in `cmd`
The marker `@` was ambiguous in SublimeLinter. Its usage has been deprecated in favor of explicit markers like `$temp_file`.
#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Ivan Sobolev
# Copyright (c) 2016 Ivan Sobolev
#
# License: MIT
#
"""This module exports the Bemlint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class Bemlint(NodeLinter):
"""Provides an interface to bemlint."""
name = 'bemlint'
cmd = 'bemlint ${temp_file} ${args}'
config_file = ('--config', '.bemlint.json')
regex = (
r'^.+?: line (?P<line>\d+), col (?P<col>\d+), '
r'(?:(?P<error>Error)|(?P<warning>Warning)) - '
r'(?P<message>.+)'
)
multiline = False
line_col_base = (1, 1)
error_stream = util.STREAM_BOTH
tempfile_suffix = 'bem'
defaults = {
'selector': 'text.html',
'--format': 'compact',
}
# the following attributes are marked useless for SL4
version_args = '--version'
version_re = r'v(?P<version>\d+\.\d+\.\d+)'
version_requirement = '>= 1.4.5'
|
<commit_before>
#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Ivan Sobolev
# Copyright (c) 2016 Ivan Sobolev
#
# License: MIT
#
"""This module exports the Bemlint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class Bemlint(NodeLinter):
"""Provides an interface to bemlint."""
name = 'bemlint'
cmd = 'bemlint @ ${args}'
config_file = ('--config', '.bemlint.json')
regex = (
r'^.+?: line (?P<line>\d+), col (?P<col>\d+), '
r'(?:(?P<error>Error)|(?P<warning>Warning)) - '
r'(?P<message>.+)'
)
multiline = False
line_col_base = (1, 1)
error_stream = util.STREAM_BOTH
tempfile_suffix = 'bem'
defaults = {
'selector': 'text.html',
'--format': 'compact',
}
# the following attributes are marked useless for SL4
version_args = '--version'
version_re = r'v(?P<version>\d+\.\d+\.\d+)'
version_requirement = '>= 1.4.5'
<commit_msg>Mark usage of temporary files in `cmd`
The marker `@` was ambiguous in SublimeLinter. Its usage has been deprecated in favor of explicit markers like `$temp_file`.<commit_after>
#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Ivan Sobolev
# Copyright (c) 2016 Ivan Sobolev
#
# License: MIT
#
"""This module exports the Bemlint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class Bemlint(NodeLinter):
"""Provides an interface to bemlint."""
name = 'bemlint'
cmd = 'bemlint ${temp_file} ${args}'
config_file = ('--config', '.bemlint.json')
regex = (
r'^.+?: line (?P<line>\d+), col (?P<col>\d+), '
r'(?:(?P<error>Error)|(?P<warning>Warning)) - '
r'(?P<message>.+)'
)
multiline = False
line_col_base = (1, 1)
error_stream = util.STREAM_BOTH
tempfile_suffix = 'bem'
defaults = {
'selector': 'text.html',
'--format': 'compact',
}
# the following attributes are marked useless for SL4
version_args = '--version'
version_re = r'v(?P<version>\d+\.\d+\.\d+)'
version_requirement = '>= 1.4.5'
|
e1fe3acf94e1358155ce67f6b38c02feb75df074
|
linter.py
|
linter.py
|
#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Dmitry Tsoy
# Copyright (c) 2013 Dmitry Tsoy
#
# License: MIT
#
"""This module exports the Phpcs plugin class."""
from SublimeLinter.lint import Linter
class Phpcs(Linter):
"""Provides an interface to phpcs."""
syntax = ('php', 'html', 'html 5')
regex = (
r'.*line="(?P<line>\d+)" '
r'column="(?P<col>\d+)" '
r'severity="(?:(?P<error>error)|(?P<warning>warning))" '
r'message="(?P<message>.*)" source'
)
executable = 'phpcs'
defaults = {
'--standard=': 'PSR2',
}
inline_overrides = ('standard')
tempfile_suffix = 'php'
def cmd(self):
"""Read cmd from inline settings."""
settings = Linter.get_view_settings(self)
if 'cmd' in settings:
command = [settings.get('cmd')]
else:
command = [self.executable_path]
command.append('--report=checkstyle')
return command
|
#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Dmitry Tsoy
# Copyright (c) 2013 Dmitry Tsoy
#
# License: MIT
#
"""This module exports the Phpcs plugin class."""
from SublimeLinter.lint import Linter
class Phpcs(Linter):
"""Provides an interface to phpcs."""
syntax = ('php', 'html', 'html 5')
regex = (
r'.*line="(?P<line>\d+)" '
r'column="(?P<col>\d+)" '
r'severity="(?:(?P<error>error)|(?P<warning>warning))" '
r'message="(?P<message>.*)" source'
)
defaults = {
'--standard=': 'PSR2',
}
inline_overrides = ('standard')
tempfile_suffix = 'php'
def cmd(self):
"""Read cmd from inline settings."""
settings = Linter.get_view_settings(self)
if 'cmd' in settings:
command = [settings.get('cmd')]
else:
command = ['phpcs']
command.append('--report=checkstyle')
return command
|
Remove the executable property to allow override.
|
Remove the executable property to allow override.
This problem was discussed here : SublimeLinter/SublimeLinter#455
If the `executable` property is defined, the plugin require the host system to have a global `phpcs` binary. If I haven't that binary installed (eg. I use composer to install inside my project folder) and I use the `*.sublime-project` file to configure my linter, the phpcs linter is never executed.
```
{
"folders":
[
{
"path": "."
}
],
"SublimeLinter": {
"linters": {
"phpcs": {
"standard": "${folder}/phpcs.xml",
"cmd": "${folder}/vendor/bin/phpcs"
}
}
}
}
```
With that update suggested by @kaste the global binary is returned only if the configuration doesn't defined a specific one.
|
Python
|
mit
|
SublimeLinter/SublimeLinter-phpcs
|
#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Dmitry Tsoy
# Copyright (c) 2013 Dmitry Tsoy
#
# License: MIT
#
"""This module exports the Phpcs plugin class."""
from SublimeLinter.lint import Linter
class Phpcs(Linter):
"""Provides an interface to phpcs."""
syntax = ('php', 'html', 'html 5')
regex = (
r'.*line="(?P<line>\d+)" '
r'column="(?P<col>\d+)" '
r'severity="(?:(?P<error>error)|(?P<warning>warning))" '
r'message="(?P<message>.*)" source'
)
executable = 'phpcs'
defaults = {
'--standard=': 'PSR2',
}
inline_overrides = ('standard')
tempfile_suffix = 'php'
def cmd(self):
"""Read cmd from inline settings."""
settings = Linter.get_view_settings(self)
if 'cmd' in settings:
command = [settings.get('cmd')]
else:
command = [self.executable_path]
command.append('--report=checkstyle')
return command
Remove the executable property to allow override.
This problem was discussed here : SublimeLinter/SublimeLinter#455
If the `executable` property is defined, the plugin require the host system to have a global `phpcs` binary. If I haven't that binary installed (eg. I use composer to install inside my project folder) and I use the `*.sublime-project` file to configure my linter, the phpcs linter is never executed.
```
{
"folders":
[
{
"path": "."
}
],
"SublimeLinter": {
"linters": {
"phpcs": {
"standard": "${folder}/phpcs.xml",
"cmd": "${folder}/vendor/bin/phpcs"
}
}
}
}
```
With that update suggested by @kaste the global binary is returned only if the configuration doesn't defined a specific one.
|
#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Dmitry Tsoy
# Copyright (c) 2013 Dmitry Tsoy
#
# License: MIT
#
"""This module exports the Phpcs plugin class."""
from SublimeLinter.lint import Linter
class Phpcs(Linter):
"""Provides an interface to phpcs."""
syntax = ('php', 'html', 'html 5')
regex = (
r'.*line="(?P<line>\d+)" '
r'column="(?P<col>\d+)" '
r'severity="(?:(?P<error>error)|(?P<warning>warning))" '
r'message="(?P<message>.*)" source'
)
defaults = {
'--standard=': 'PSR2',
}
inline_overrides = ('standard')
tempfile_suffix = 'php'
def cmd(self):
"""Read cmd from inline settings."""
settings = Linter.get_view_settings(self)
if 'cmd' in settings:
command = [settings.get('cmd')]
else:
command = ['phpcs']
command.append('--report=checkstyle')
return command
|
<commit_before>#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Dmitry Tsoy
# Copyright (c) 2013 Dmitry Tsoy
#
# License: MIT
#
"""This module exports the Phpcs plugin class."""
from SublimeLinter.lint import Linter
class Phpcs(Linter):
"""Provides an interface to phpcs."""
syntax = ('php', 'html', 'html 5')
regex = (
r'.*line="(?P<line>\d+)" '
r'column="(?P<col>\d+)" '
r'severity="(?:(?P<error>error)|(?P<warning>warning))" '
r'message="(?P<message>.*)" source'
)
executable = 'phpcs'
defaults = {
'--standard=': 'PSR2',
}
inline_overrides = ('standard')
tempfile_suffix = 'php'
def cmd(self):
"""Read cmd from inline settings."""
settings = Linter.get_view_settings(self)
if 'cmd' in settings:
command = [settings.get('cmd')]
else:
command = [self.executable_path]
command.append('--report=checkstyle')
return command
<commit_msg>Remove the executable property to allow override.
This problem was discussed here : SublimeLinter/SublimeLinter#455
If the `executable` property is defined, the plugin require the host system to have a global `phpcs` binary. If I haven't that binary installed (eg. I use composer to install inside my project folder) and I use the `*.sublime-project` file to configure my linter, the phpcs linter is never executed.
```
{
"folders":
[
{
"path": "."
}
],
"SublimeLinter": {
"linters": {
"phpcs": {
"standard": "${folder}/phpcs.xml",
"cmd": "${folder}/vendor/bin/phpcs"
}
}
}
}
```
With that update suggested by @kaste the global binary is returned only if the configuration doesn't defined a specific one.<commit_after>
|
#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Dmitry Tsoy
# Copyright (c) 2013 Dmitry Tsoy
#
# License: MIT
#
"""This module exports the Phpcs plugin class."""
from SublimeLinter.lint import Linter
class Phpcs(Linter):
"""Provides an interface to phpcs."""
syntax = ('php', 'html', 'html 5')
regex = (
r'.*line="(?P<line>\d+)" '
r'column="(?P<col>\d+)" '
r'severity="(?:(?P<error>error)|(?P<warning>warning))" '
r'message="(?P<message>.*)" source'
)
defaults = {
'--standard=': 'PSR2',
}
inline_overrides = ('standard')
tempfile_suffix = 'php'
def cmd(self):
"""Read cmd from inline settings."""
settings = Linter.get_view_settings(self)
if 'cmd' in settings:
command = [settings.get('cmd')]
else:
command = ['phpcs']
command.append('--report=checkstyle')
return command
|
#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Dmitry Tsoy
# Copyright (c) 2013 Dmitry Tsoy
#
# License: MIT
#
"""This module exports the Phpcs plugin class."""
from SublimeLinter.lint import Linter
class Phpcs(Linter):
"""Provides an interface to phpcs."""
syntax = ('php', 'html', 'html 5')
regex = (
r'.*line="(?P<line>\d+)" '
r'column="(?P<col>\d+)" '
r'severity="(?:(?P<error>error)|(?P<warning>warning))" '
r'message="(?P<message>.*)" source'
)
executable = 'phpcs'
defaults = {
'--standard=': 'PSR2',
}
inline_overrides = ('standard')
tempfile_suffix = 'php'
def cmd(self):
"""Read cmd from inline settings."""
settings = Linter.get_view_settings(self)
if 'cmd' in settings:
command = [settings.get('cmd')]
else:
command = [self.executable_path]
command.append('--report=checkstyle')
return command
Remove the executable property to allow override.
This problem was discussed here : SublimeLinter/SublimeLinter#455
If the `executable` property is defined, the plugin require the host system to have a global `phpcs` binary. If I haven't that binary installed (eg. I use composer to install inside my project folder) and I use the `*.sublime-project` file to configure my linter, the phpcs linter is never executed.
```
{
"folders":
[
{
"path": "."
}
],
"SublimeLinter": {
"linters": {
"phpcs": {
"standard": "${folder}/phpcs.xml",
"cmd": "${folder}/vendor/bin/phpcs"
}
}
}
}
```
With that update suggested by @kaste the global binary is returned only if the configuration doesn't defined a specific one.#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Dmitry Tsoy
# Copyright (c) 2013 Dmitry Tsoy
#
# License: MIT
#
"""This module exports the Phpcs plugin class."""
from SublimeLinter.lint import Linter
class Phpcs(Linter):
"""Provides an interface to phpcs."""
syntax = ('php', 'html', 'html 5')
regex = (
r'.*line="(?P<line>\d+)" '
r'column="(?P<col>\d+)" '
r'severity="(?:(?P<error>error)|(?P<warning>warning))" '
r'message="(?P<message>.*)" source'
)
defaults = {
'--standard=': 'PSR2',
}
inline_overrides = ('standard')
tempfile_suffix = 'php'
def cmd(self):
"""Read cmd from inline settings."""
settings = Linter.get_view_settings(self)
if 'cmd' in settings:
command = [settings.get('cmd')]
else:
command = ['phpcs']
command.append('--report=checkstyle')
return command
|
<commit_before>#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Dmitry Tsoy
# Copyright (c) 2013 Dmitry Tsoy
#
# License: MIT
#
"""This module exports the Phpcs plugin class."""
from SublimeLinter.lint import Linter
class Phpcs(Linter):
"""Provides an interface to phpcs."""
syntax = ('php', 'html', 'html 5')
regex = (
r'.*line="(?P<line>\d+)" '
r'column="(?P<col>\d+)" '
r'severity="(?:(?P<error>error)|(?P<warning>warning))" '
r'message="(?P<message>.*)" source'
)
executable = 'phpcs'
defaults = {
'--standard=': 'PSR2',
}
inline_overrides = ('standard')
tempfile_suffix = 'php'
def cmd(self):
"""Read cmd from inline settings."""
settings = Linter.get_view_settings(self)
if 'cmd' in settings:
command = [settings.get('cmd')]
else:
command = [self.executable_path]
command.append('--report=checkstyle')
return command
<commit_msg>Remove the executable property to allow override.
This problem was discussed here : SublimeLinter/SublimeLinter#455
If the `executable` property is defined, the plugin require the host system to have a global `phpcs` binary. If I haven't that binary installed (eg. I use composer to install inside my project folder) and I use the `*.sublime-project` file to configure my linter, the phpcs linter is never executed.
```
{
"folders":
[
{
"path": "."
}
],
"SublimeLinter": {
"linters": {
"phpcs": {
"standard": "${folder}/phpcs.xml",
"cmd": "${folder}/vendor/bin/phpcs"
}
}
}
}
```
With that update suggested by @kaste the global binary is returned only if the configuration doesn't defined a specific one.<commit_after>#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Dmitry Tsoy
# Copyright (c) 2013 Dmitry Tsoy
#
# License: MIT
#
"""This module exports the Phpcs plugin class."""
from SublimeLinter.lint import Linter
class Phpcs(Linter):
"""Provides an interface to phpcs."""
syntax = ('php', 'html', 'html 5')
regex = (
r'.*line="(?P<line>\d+)" '
r'column="(?P<col>\d+)" '
r'severity="(?:(?P<error>error)|(?P<warning>warning))" '
r'message="(?P<message>.*)" source'
)
defaults = {
'--standard=': 'PSR2',
}
inline_overrides = ('standard')
tempfile_suffix = 'php'
def cmd(self):
"""Read cmd from inline settings."""
settings = Linter.get_view_settings(self)
if 'cmd' in settings:
command = [settings.get('cmd')]
else:
command = ['phpcs']
command.append('--report=checkstyle')
return command
|
3a4a67a34359c70ac9f3d0f19db3521f6bea7e48
|
linter.py
|
linter.py
|
#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Andrew Grim
# Copyright (c) 2014 Andrew Grim
#
# License: MIT
#
"""This module exports the Puppet plugin class."""
from SublimeLinter.lint import Linter, util
class Puppet(Linter):
"""Provides an interface to puppet."""
syntax = 'puppet'
cmd = ('puppet', 'parser', 'validate', '--color=false')
regex = r'^Error:.+?(?P<message>Syntax error at \'(?P<near>.+?)\'; expected \'.+\').+?line (?P<line>\d+)'
error_stream = util.STREAM_STDERR
|
#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Andrew Grim
# Copyright (c) 2014 Andrew Grim
#
# License: MIT
#
"""This module exports the Puppet plugin class."""
from SublimeLinter.lint import Linter, util
class Puppet(Linter):
"""Provides an interface to puppet."""
syntax = 'puppet'
cmd = ('puppet', 'parser', 'validate', '--color=false')
regex = r'^Error:.+?(?P<message>Syntax error at \'?(?P<near>.+?)\'?(?:; expected \'.+\')?) at line (?P<line>\d+)'
error_stream = util.STREAM_STDERR
|
Support Additional Error Output Formats
|
Support Additional Error Output Formats
Make the 'near' match group more flexible to support multiple error
output styles for some syntax errors.
Examples:
Error: Could not parse for environment production: Syntax error at 'class' at line 27
Error: Could not parse for environment production: Syntax error at end of file at line 32
Error: Could not parse for environment production: Syntax error at ','; expected '}' at line 28
See https://regex101.com/r/aT3aR3/3 for testing
|
Python
|
mit
|
travisgroth/SublimeLinter-puppet
|
#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Andrew Grim
# Copyright (c) 2014 Andrew Grim
#
# License: MIT
#
"""This module exports the Puppet plugin class."""
from SublimeLinter.lint import Linter, util
class Puppet(Linter):
"""Provides an interface to puppet."""
syntax = 'puppet'
cmd = ('puppet', 'parser', 'validate', '--color=false')
regex = r'^Error:.+?(?P<message>Syntax error at \'(?P<near>.+?)\'; expected \'.+\').+?line (?P<line>\d+)'
error_stream = util.STREAM_STDERR
Support Additional Error Output Formats
Make the 'near' match group more flexible to support multiple error
output styles for some syntax errors.
Examples:
Error: Could not parse for environment production: Syntax error at 'class' at line 27
Error: Could not parse for environment production: Syntax error at end of file at line 32
Error: Could not parse for environment production: Syntax error at ','; expected '}' at line 28
See https://regex101.com/r/aT3aR3/3 for testing
|
#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Andrew Grim
# Copyright (c) 2014 Andrew Grim
#
# License: MIT
#
"""This module exports the Puppet plugin class."""
from SublimeLinter.lint import Linter, util
class Puppet(Linter):
"""Provides an interface to puppet."""
syntax = 'puppet'
cmd = ('puppet', 'parser', 'validate', '--color=false')
regex = r'^Error:.+?(?P<message>Syntax error at \'?(?P<near>.+?)\'?(?:; expected \'.+\')?) at line (?P<line>\d+)'
error_stream = util.STREAM_STDERR
|
<commit_before>#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Andrew Grim
# Copyright (c) 2014 Andrew Grim
#
# License: MIT
#
"""This module exports the Puppet plugin class."""
from SublimeLinter.lint import Linter, util
class Puppet(Linter):
"""Provides an interface to puppet."""
syntax = 'puppet'
cmd = ('puppet', 'parser', 'validate', '--color=false')
regex = r'^Error:.+?(?P<message>Syntax error at \'(?P<near>.+?)\'; expected \'.+\').+?line (?P<line>\d+)'
error_stream = util.STREAM_STDERR
<commit_msg>Support Additional Error Output Formats
Make the 'near' match group more flexible to support multiple error
output styles for some syntax errors.
Examples:
Error: Could not parse for environment production: Syntax error at 'class' at line 27
Error: Could not parse for environment production: Syntax error at end of file at line 32
Error: Could not parse for environment production: Syntax error at ','; expected '}' at line 28
See https://regex101.com/r/aT3aR3/3 for testing<commit_after>
|
#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Andrew Grim
# Copyright (c) 2014 Andrew Grim
#
# License: MIT
#
"""This module exports the Puppet plugin class."""
from SublimeLinter.lint import Linter, util
class Puppet(Linter):
"""Provides an interface to puppet."""
syntax = 'puppet'
cmd = ('puppet', 'parser', 'validate', '--color=false')
regex = r'^Error:.+?(?P<message>Syntax error at \'?(?P<near>.+?)\'?(?:; expected \'.+\')?) at line (?P<line>\d+)'
error_stream = util.STREAM_STDERR
|
#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Andrew Grim
# Copyright (c) 2014 Andrew Grim
#
# License: MIT
#
"""This module exports the Puppet plugin class."""
from SublimeLinter.lint import Linter, util
class Puppet(Linter):
"""Provides an interface to puppet."""
syntax = 'puppet'
cmd = ('puppet', 'parser', 'validate', '--color=false')
regex = r'^Error:.+?(?P<message>Syntax error at \'(?P<near>.+?)\'; expected \'.+\').+?line (?P<line>\d+)'
error_stream = util.STREAM_STDERR
Support Additional Error Output Formats
Make the 'near' match group more flexible to support multiple error
output styles for some syntax errors.
Examples:
Error: Could not parse for environment production: Syntax error at 'class' at line 27
Error: Could not parse for environment production: Syntax error at end of file at line 32
Error: Could not parse for environment production: Syntax error at ','; expected '}' at line 28
See https://regex101.com/r/aT3aR3/3 for testing#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Andrew Grim
# Copyright (c) 2014 Andrew Grim
#
# License: MIT
#
"""This module exports the Puppet plugin class."""
from SublimeLinter.lint import Linter, util
class Puppet(Linter):
"""Provides an interface to puppet."""
syntax = 'puppet'
cmd = ('puppet', 'parser', 'validate', '--color=false')
regex = r'^Error:.+?(?P<message>Syntax error at \'?(?P<near>.+?)\'?(?:; expected \'.+\')?) at line (?P<line>\d+)'
error_stream = util.STREAM_STDERR
|
<commit_before>#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Andrew Grim
# Copyright (c) 2014 Andrew Grim
#
# License: MIT
#
"""This module exports the Puppet plugin class."""
from SublimeLinter.lint import Linter, util
class Puppet(Linter):
"""Provides an interface to puppet."""
syntax = 'puppet'
cmd = ('puppet', 'parser', 'validate', '--color=false')
regex = r'^Error:.+?(?P<message>Syntax error at \'(?P<near>.+?)\'; expected \'.+\').+?line (?P<line>\d+)'
error_stream = util.STREAM_STDERR
<commit_msg>Support Additional Error Output Formats
Make the 'near' match group more flexible to support multiple error
output styles for some syntax errors.
Examples:
Error: Could not parse for environment production: Syntax error at 'class' at line 27
Error: Could not parse for environment production: Syntax error at end of file at line 32
Error: Could not parse for environment production: Syntax error at ','; expected '}' at line 28
See https://regex101.com/r/aT3aR3/3 for testing<commit_after>#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Andrew Grim
# Copyright (c) 2014 Andrew Grim
#
# License: MIT
#
"""This module exports the Puppet plugin class."""
from SublimeLinter.lint import Linter, util
class Puppet(Linter):
"""Provides an interface to puppet."""
syntax = 'puppet'
cmd = ('puppet', 'parser', 'validate', '--color=false')
regex = r'^Error:.+?(?P<message>Syntax error at \'?(?P<near>.+?)\'?(?:; expected \'.+\')?) at line (?P<line>\d+)'
error_stream = util.STREAM_STDERR
|
e73db09c343d7159c09783c514a406fc2fb3f04f
|
test_py3/pointfree_test_py3.py
|
test_py3/pointfree_test_py3.py
|
from unittest import TestCase
from pointfree import *
def kwonly_pure_func(a, b, *, c):
return a + b + c
@partial
def kwonly_func(a, b, *, c):
return a + b + c
class KwOnlyArgsCase(TestCase):
def testNormalApplication(self):
self.assertEqual(kwonly_func(1,2,c=3), 6)
def testPartialApplication(self):
self.assertEqual(kwonly_func(1)(2)(c=3), 6)
self.assertEqual(kwonly_func(1,2)(c=3), 6)
self.assertEqual(kwonly_func(1)(2,c=3), 6)
self.assertEqual(kwonly_func(c=3)(1,2), 6)
self.assertEqual(kwonly_func(c=3)(1)(2), 6)
def testKeywordOnlyApplication(self):
self.assertRaises(TypeError, lambda *a: kwonly_func(1,2,3))
|
from unittest import TestCase
from pointfree import *
def kwonly_pure_func(a, b, *, c):
return a + b + c
@partial
def kwonly_func(a, b, *, c):
return a + b + c
@partial
def kwonly_defaults_func(a, b, *, c=3):
return a + b + c
@partial
def kwonly_varkw_func(a, b, *, c, **kwargs):
return (a + b + c, kwargs)
class KwOnlyArgsCase(TestCase):
def testNormalApplication(self):
self.assertEqual(kwonly_func(1,2,c=3), 6)
def testPartialApplication(self):
self.assertEqual(kwonly_func(1)(2)(c=3), 6)
self.assertEqual(kwonly_func(1,2)(c=3), 6)
self.assertEqual(kwonly_func(1)(2,c=3), 6)
self.assertEqual(kwonly_func(c=3)(1,2), 6)
self.assertEqual(kwonly_func(c=3)(1)(2), 6)
self.assertEqual(kwonly_func(a=1)(b=2)(c=3), 6)
def testTooManyPositionalArguments(self):
self.assertRaises(TypeError, lambda: kwonly_func(1,2,3))
def testTooManyKeywordArguments(self):
self.assertRaises(TypeError, lambda: kwonly_func(d=1))
class KwOnlyDefaultsCase(TestCase):
def testNormalApplication(self):
self.assertEqual(kwonly_defaults_func(1,2,c=4), 7)
def testDefaultApplication(self):
self.assertEqual(kwonly_defaults_func(1,2), 6)
class KwOnlyAndVarKargsCase(TestCase):
def testNormalApplication(self):
value, kwargs = kwonly_varkw_func(1,2,c=3,d=4,e=5)
self.assertEqual(value, 6)
self.assertDictEqual(kwargs, {'d': 4, 'e': 5})
|
Add tests for more keyword-only arguments behavior
|
Add tests for more keyword-only arguments behavior
Test for handling of default keyword-only argument values and mixing
keyword-only arguments with variable keyword arguments lists.
|
Python
|
apache-2.0
|
markshroyer/pointfree,markshroyer/pointfree
|
from unittest import TestCase
from pointfree import *
def kwonly_pure_func(a, b, *, c):
return a + b + c
@partial
def kwonly_func(a, b, *, c):
return a + b + c
class KwOnlyArgsCase(TestCase):
def testNormalApplication(self):
self.assertEqual(kwonly_func(1,2,c=3), 6)
def testPartialApplication(self):
self.assertEqual(kwonly_func(1)(2)(c=3), 6)
self.assertEqual(kwonly_func(1,2)(c=3), 6)
self.assertEqual(kwonly_func(1)(2,c=3), 6)
self.assertEqual(kwonly_func(c=3)(1,2), 6)
self.assertEqual(kwonly_func(c=3)(1)(2), 6)
def testKeywordOnlyApplication(self):
self.assertRaises(TypeError, lambda *a: kwonly_func(1,2,3))
Add tests for more keyword-only arguments behavior
Test for handling of default keyword-only argument values and mixing
keyword-only arguments with variable keyword arguments lists.
|
from unittest import TestCase
from pointfree import *
def kwonly_pure_func(a, b, *, c):
return a + b + c
@partial
def kwonly_func(a, b, *, c):
return a + b + c
@partial
def kwonly_defaults_func(a, b, *, c=3):
return a + b + c
@partial
def kwonly_varkw_func(a, b, *, c, **kwargs):
return (a + b + c, kwargs)
class KwOnlyArgsCase(TestCase):
def testNormalApplication(self):
self.assertEqual(kwonly_func(1,2,c=3), 6)
def testPartialApplication(self):
self.assertEqual(kwonly_func(1)(2)(c=3), 6)
self.assertEqual(kwonly_func(1,2)(c=3), 6)
self.assertEqual(kwonly_func(1)(2,c=3), 6)
self.assertEqual(kwonly_func(c=3)(1,2), 6)
self.assertEqual(kwonly_func(c=3)(1)(2), 6)
self.assertEqual(kwonly_func(a=1)(b=2)(c=3), 6)
def testTooManyPositionalArguments(self):
self.assertRaises(TypeError, lambda: kwonly_func(1,2,3))
def testTooManyKeywordArguments(self):
self.assertRaises(TypeError, lambda: kwonly_func(d=1))
class KwOnlyDefaultsCase(TestCase):
def testNormalApplication(self):
self.assertEqual(kwonly_defaults_func(1,2,c=4), 7)
def testDefaultApplication(self):
self.assertEqual(kwonly_defaults_func(1,2), 6)
class KwOnlyAndVarKargsCase(TestCase):
def testNormalApplication(self):
value, kwargs = kwonly_varkw_func(1,2,c=3,d=4,e=5)
self.assertEqual(value, 6)
self.assertDictEqual(kwargs, {'d': 4, 'e': 5})
|
<commit_before>from unittest import TestCase
from pointfree import *
def kwonly_pure_func(a, b, *, c):
return a + b + c
@partial
def kwonly_func(a, b, *, c):
return a + b + c
class KwOnlyArgsCase(TestCase):
def testNormalApplication(self):
self.assertEqual(kwonly_func(1,2,c=3), 6)
def testPartialApplication(self):
self.assertEqual(kwonly_func(1)(2)(c=3), 6)
self.assertEqual(kwonly_func(1,2)(c=3), 6)
self.assertEqual(kwonly_func(1)(2,c=3), 6)
self.assertEqual(kwonly_func(c=3)(1,2), 6)
self.assertEqual(kwonly_func(c=3)(1)(2), 6)
def testKeywordOnlyApplication(self):
self.assertRaises(TypeError, lambda *a: kwonly_func(1,2,3))
<commit_msg>Add tests for more keyword-only arguments behavior
Test for handling of default keyword-only argument values and mixing
keyword-only arguments with variable keyword arguments lists.<commit_after>
|
from unittest import TestCase
from pointfree import *
def kwonly_pure_func(a, b, *, c):
return a + b + c
@partial
def kwonly_func(a, b, *, c):
return a + b + c
@partial
def kwonly_defaults_func(a, b, *, c=3):
return a + b + c
@partial
def kwonly_varkw_func(a, b, *, c, **kwargs):
return (a + b + c, kwargs)
class KwOnlyArgsCase(TestCase):
def testNormalApplication(self):
self.assertEqual(kwonly_func(1,2,c=3), 6)
def testPartialApplication(self):
self.assertEqual(kwonly_func(1)(2)(c=3), 6)
self.assertEqual(kwonly_func(1,2)(c=3), 6)
self.assertEqual(kwonly_func(1)(2,c=3), 6)
self.assertEqual(kwonly_func(c=3)(1,2), 6)
self.assertEqual(kwonly_func(c=3)(1)(2), 6)
self.assertEqual(kwonly_func(a=1)(b=2)(c=3), 6)
def testTooManyPositionalArguments(self):
self.assertRaises(TypeError, lambda: kwonly_func(1,2,3))
def testTooManyKeywordArguments(self):
self.assertRaises(TypeError, lambda: kwonly_func(d=1))
class KwOnlyDefaultsCase(TestCase):
def testNormalApplication(self):
self.assertEqual(kwonly_defaults_func(1,2,c=4), 7)
def testDefaultApplication(self):
self.assertEqual(kwonly_defaults_func(1,2), 6)
class KwOnlyAndVarKargsCase(TestCase):
def testNormalApplication(self):
value, kwargs = kwonly_varkw_func(1,2,c=3,d=4,e=5)
self.assertEqual(value, 6)
self.assertDictEqual(kwargs, {'d': 4, 'e': 5})
|
from unittest import TestCase
from pointfree import *
def kwonly_pure_func(a, b, *, c):
return a + b + c
@partial
def kwonly_func(a, b, *, c):
return a + b + c
class KwOnlyArgsCase(TestCase):
def testNormalApplication(self):
self.assertEqual(kwonly_func(1,2,c=3), 6)
def testPartialApplication(self):
self.assertEqual(kwonly_func(1)(2)(c=3), 6)
self.assertEqual(kwonly_func(1,2)(c=3), 6)
self.assertEqual(kwonly_func(1)(2,c=3), 6)
self.assertEqual(kwonly_func(c=3)(1,2), 6)
self.assertEqual(kwonly_func(c=3)(1)(2), 6)
def testKeywordOnlyApplication(self):
self.assertRaises(TypeError, lambda *a: kwonly_func(1,2,3))
Add tests for more keyword-only arguments behavior
Test for handling of default keyword-only argument values and mixing
keyword-only arguments with variable keyword arguments lists.from unittest import TestCase
from pointfree import *
def kwonly_pure_func(a, b, *, c):
return a + b + c
@partial
def kwonly_func(a, b, *, c):
return a + b + c
@partial
def kwonly_defaults_func(a, b, *, c=3):
return a + b + c
@partial
def kwonly_varkw_func(a, b, *, c, **kwargs):
return (a + b + c, kwargs)
class KwOnlyArgsCase(TestCase):
def testNormalApplication(self):
self.assertEqual(kwonly_func(1,2,c=3), 6)
def testPartialApplication(self):
self.assertEqual(kwonly_func(1)(2)(c=3), 6)
self.assertEqual(kwonly_func(1,2)(c=3), 6)
self.assertEqual(kwonly_func(1)(2,c=3), 6)
self.assertEqual(kwonly_func(c=3)(1,2), 6)
self.assertEqual(kwonly_func(c=3)(1)(2), 6)
self.assertEqual(kwonly_func(a=1)(b=2)(c=3), 6)
def testTooManyPositionalArguments(self):
self.assertRaises(TypeError, lambda: kwonly_func(1,2,3))
def testTooManyKeywordArguments(self):
self.assertRaises(TypeError, lambda: kwonly_func(d=1))
class KwOnlyDefaultsCase(TestCase):
def testNormalApplication(self):
self.assertEqual(kwonly_defaults_func(1,2,c=4), 7)
def testDefaultApplication(self):
self.assertEqual(kwonly_defaults_func(1,2), 6)
class KwOnlyAndVarKargsCase(TestCase):
def testNormalApplication(self):
value, kwargs = kwonly_varkw_func(1,2,c=3,d=4,e=5)
self.assertEqual(value, 6)
self.assertDictEqual(kwargs, {'d': 4, 'e': 5})
|
<commit_before>from unittest import TestCase
from pointfree import *
def kwonly_pure_func(a, b, *, c):
return a + b + c
@partial
def kwonly_func(a, b, *, c):
return a + b + c
class KwOnlyArgsCase(TestCase):
def testNormalApplication(self):
self.assertEqual(kwonly_func(1,2,c=3), 6)
def testPartialApplication(self):
self.assertEqual(kwonly_func(1)(2)(c=3), 6)
self.assertEqual(kwonly_func(1,2)(c=3), 6)
self.assertEqual(kwonly_func(1)(2,c=3), 6)
self.assertEqual(kwonly_func(c=3)(1,2), 6)
self.assertEqual(kwonly_func(c=3)(1)(2), 6)
def testKeywordOnlyApplication(self):
self.assertRaises(TypeError, lambda *a: kwonly_func(1,2,3))
<commit_msg>Add tests for more keyword-only arguments behavior
Test for handling of default keyword-only argument values and mixing
keyword-only arguments with variable keyword arguments lists.<commit_after>from unittest import TestCase
from pointfree import *
def kwonly_pure_func(a, b, *, c):
return a + b + c
@partial
def kwonly_func(a, b, *, c):
return a + b + c
@partial
def kwonly_defaults_func(a, b, *, c=3):
return a + b + c
@partial
def kwonly_varkw_func(a, b, *, c, **kwargs):
return (a + b + c, kwargs)
class KwOnlyArgsCase(TestCase):
def testNormalApplication(self):
self.assertEqual(kwonly_func(1,2,c=3), 6)
def testPartialApplication(self):
self.assertEqual(kwonly_func(1)(2)(c=3), 6)
self.assertEqual(kwonly_func(1,2)(c=3), 6)
self.assertEqual(kwonly_func(1)(2,c=3), 6)
self.assertEqual(kwonly_func(c=3)(1,2), 6)
self.assertEqual(kwonly_func(c=3)(1)(2), 6)
self.assertEqual(kwonly_func(a=1)(b=2)(c=3), 6)
def testTooManyPositionalArguments(self):
self.assertRaises(TypeError, lambda: kwonly_func(1,2,3))
def testTooManyKeywordArguments(self):
self.assertRaises(TypeError, lambda: kwonly_func(d=1))
class KwOnlyDefaultsCase(TestCase):
def testNormalApplication(self):
self.assertEqual(kwonly_defaults_func(1,2,c=4), 7)
def testDefaultApplication(self):
self.assertEqual(kwonly_defaults_func(1,2), 6)
class KwOnlyAndVarKargsCase(TestCase):
def testNormalApplication(self):
value, kwargs = kwonly_varkw_func(1,2,c=3,d=4,e=5)
self.assertEqual(value, 6)
self.assertDictEqual(kwargs, {'d': 4, 'e': 5})
|
9294e302e4987531ac61db0a952fad22d8785e82
|
lowfat/validator.py
|
lowfat/validator.py
|
"""
Validator functions
"""
from urllib import request
from django.core.exceptions import ValidationError
import PyPDF2
def online_document(url):
"""Check if online document is available."""
online_resource = request.urlopen(url)
# Need to test if website didn't redirect the request to another resource.
if url != online_resource.geturl() or online_resource.getcode() != 200:
raise ValidationError("Can't access online document.")
def pdf(value):
"""Check if filename looks like a PDF file."""
filename = value.name.lower()
if not filename.endswith(".pdf"):
raise ValidationError("File name doesn't look to be a PDF file.")
try:
pdf_file = PyPDF2.PdfFileReader(value.file) # pylint: disable=unused-variable
except:
raise ValidationError("File doesn't look to be a PDF file.")
|
"""
Validator functions
"""
from urllib import request
from urllib.error import HTTPError
from django.core.exceptions import ValidationError
import PyPDF2
def online_document(url):
"""Check if online document is available."""
try:
online_resource = request.urlopen(url)
except HTTPError as exception:
if exception.code == 410:
raise ValidationError("Online document was removed.") # This is the code returned by Google Drive
# Need to test if website didn't redirect the request to another resource.
if url != online_resource.geturl() or online_resource.getcode() != 200:
raise ValidationError("Can't access online document.")
def pdf(value):
"""Check if filename looks like a PDF file."""
filename = value.name.lower()
if not filename.endswith(".pdf"):
raise ValidationError("File name doesn't look to be a PDF file.")
try:
pdf_file = PyPDF2.PdfFileReader(value.file) # pylint: disable=unused-variable
except:
raise ValidationError("File doesn't look to be a PDF file.")
|
Handle HTTP Error 410 when checking blog post
|
Handle HTTP Error 410 when checking blog post
|
Python
|
bsd-3-clause
|
softwaresaved/fat,softwaresaved/fat,softwaresaved/fat,softwaresaved/fat
|
"""
Validator functions
"""
from urllib import request
from django.core.exceptions import ValidationError
import PyPDF2
def online_document(url):
"""Check if online document is available."""
online_resource = request.urlopen(url)
# Need to test if website didn't redirect the request to another resource.
if url != online_resource.geturl() or online_resource.getcode() != 200:
raise ValidationError("Can't access online document.")
def pdf(value):
"""Check if filename looks like a PDF file."""
filename = value.name.lower()
if not filename.endswith(".pdf"):
raise ValidationError("File name doesn't look to be a PDF file.")
try:
pdf_file = PyPDF2.PdfFileReader(value.file) # pylint: disable=unused-variable
except:
raise ValidationError("File doesn't look to be a PDF file.")
Handle HTTP Error 410 when checking blog post
|
"""
Validator functions
"""
from urllib import request
from urllib.error import HTTPError
from django.core.exceptions import ValidationError
import PyPDF2
def online_document(url):
"""Check if online document is available."""
try:
online_resource = request.urlopen(url)
except HTTPError as exception:
if exception.code == 410:
raise ValidationError("Online document was removed.") # This is the code returned by Google Drive
# Need to test if website didn't redirect the request to another resource.
if url != online_resource.geturl() or online_resource.getcode() != 200:
raise ValidationError("Can't access online document.")
def pdf(value):
"""Check if filename looks like a PDF file."""
filename = value.name.lower()
if not filename.endswith(".pdf"):
raise ValidationError("File name doesn't look to be a PDF file.")
try:
pdf_file = PyPDF2.PdfFileReader(value.file) # pylint: disable=unused-variable
except:
raise ValidationError("File doesn't look to be a PDF file.")
|
<commit_before>"""
Validator functions
"""
from urllib import request
from django.core.exceptions import ValidationError
import PyPDF2
def online_document(url):
"""Check if online document is available."""
online_resource = request.urlopen(url)
# Need to test if website didn't redirect the request to another resource.
if url != online_resource.geturl() or online_resource.getcode() != 200:
raise ValidationError("Can't access online document.")
def pdf(value):
"""Check if filename looks like a PDF file."""
filename = value.name.lower()
if not filename.endswith(".pdf"):
raise ValidationError("File name doesn't look to be a PDF file.")
try:
pdf_file = PyPDF2.PdfFileReader(value.file) # pylint: disable=unused-variable
except:
raise ValidationError("File doesn't look to be a PDF file.")
<commit_msg>Handle HTTP Error 410 when checking blog post<commit_after>
|
"""
Validator functions
"""
from urllib import request
from urllib.error import HTTPError
from django.core.exceptions import ValidationError
import PyPDF2
def online_document(url):
"""Check if online document is available."""
try:
online_resource = request.urlopen(url)
except HTTPError as exception:
if exception.code == 410:
raise ValidationError("Online document was removed.") # This is the code returned by Google Drive
# Need to test if website didn't redirect the request to another resource.
if url != online_resource.geturl() or online_resource.getcode() != 200:
raise ValidationError("Can't access online document.")
def pdf(value):
"""Check if filename looks like a PDF file."""
filename = value.name.lower()
if not filename.endswith(".pdf"):
raise ValidationError("File name doesn't look to be a PDF file.")
try:
pdf_file = PyPDF2.PdfFileReader(value.file) # pylint: disable=unused-variable
except:
raise ValidationError("File doesn't look to be a PDF file.")
|
"""
Validator functions
"""
from urllib import request
from django.core.exceptions import ValidationError
import PyPDF2
def online_document(url):
"""Check if online document is available."""
online_resource = request.urlopen(url)
# Need to test if website didn't redirect the request to another resource.
if url != online_resource.geturl() or online_resource.getcode() != 200:
raise ValidationError("Can't access online document.")
def pdf(value):
"""Check if filename looks like a PDF file."""
filename = value.name.lower()
if not filename.endswith(".pdf"):
raise ValidationError("File name doesn't look to be a PDF file.")
try:
pdf_file = PyPDF2.PdfFileReader(value.file) # pylint: disable=unused-variable
except:
raise ValidationError("File doesn't look to be a PDF file.")
Handle HTTP Error 410 when checking blog post"""
Validator functions
"""
from urllib import request
from urllib.error import HTTPError
from django.core.exceptions import ValidationError
import PyPDF2
def online_document(url):
"""Check if online document is available."""
try:
online_resource = request.urlopen(url)
except HTTPError as exception:
if exception.code == 410:
raise ValidationError("Online document was removed.") # This is the code returned by Google Drive
# Need to test if website didn't redirect the request to another resource.
if url != online_resource.geturl() or online_resource.getcode() != 200:
raise ValidationError("Can't access online document.")
def pdf(value):
"""Check if filename looks like a PDF file."""
filename = value.name.lower()
if not filename.endswith(".pdf"):
raise ValidationError("File name doesn't look to be a PDF file.")
try:
pdf_file = PyPDF2.PdfFileReader(value.file) # pylint: disable=unused-variable
except:
raise ValidationError("File doesn't look to be a PDF file.")
|
<commit_before>"""
Validator functions
"""
from urllib import request
from django.core.exceptions import ValidationError
import PyPDF2
def online_document(url):
"""Check if online document is available."""
online_resource = request.urlopen(url)
# Need to test if website didn't redirect the request to another resource.
if url != online_resource.geturl() or online_resource.getcode() != 200:
raise ValidationError("Can't access online document.")
def pdf(value):
"""Check if filename looks like a PDF file."""
filename = value.name.lower()
if not filename.endswith(".pdf"):
raise ValidationError("File name doesn't look to be a PDF file.")
try:
pdf_file = PyPDF2.PdfFileReader(value.file) # pylint: disable=unused-variable
except:
raise ValidationError("File doesn't look to be a PDF file.")
<commit_msg>Handle HTTP Error 410 when checking blog post<commit_after>"""
Validator functions
"""
from urllib import request
from urllib.error import HTTPError
from django.core.exceptions import ValidationError
import PyPDF2
def online_document(url):
"""Check if online document is available."""
try:
online_resource = request.urlopen(url)
except HTTPError as exception:
if exception.code == 410:
raise ValidationError("Online document was removed.") # This is the code returned by Google Drive
# Need to test if website didn't redirect the request to another resource.
if url != online_resource.geturl() or online_resource.getcode() != 200:
raise ValidationError("Can't access online document.")
def pdf(value):
"""Check if filename looks like a PDF file."""
filename = value.name.lower()
if not filename.endswith(".pdf"):
raise ValidationError("File name doesn't look to be a PDF file.")
try:
pdf_file = PyPDF2.PdfFileReader(value.file) # pylint: disable=unused-variable
except:
raise ValidationError("File doesn't look to be a PDF file.")
|
9ef096bb067d062ece8bf4310c11759c90e60202
|
triggers/makewaves.py
|
triggers/makewaves.py
|
#!/usr/bin/env python
wavelist = []
for p in range(48):
for s in range(24):
wave = {'method': 'PUT', 'url': 'http://localhost:3520/scenes/_current'}
wave['name'] = 'P{0:02}-S{1:02}'.format(p + 1, s + 1)
wave['data'] = {'id': p * 24 + s}
wavelist.append(wave)
import json
import struct
for wave in wavelist:
reqdata = '\n'.join((wave['method'], wave['url'], json.dumps(wave['data'])))
reqlen = len(reqdata)
if reqlen % 2 == 1:
reqdata += '\n'
reqlen += 1
filelen = 36 + 8 + reqlen
riffchunk = struct.pack('<4sL4s', 'RIFF'.encode(), filelen, 'WAVE'.encode())
fmtchunk = struct.pack('<4sL2H2L2H', 'fmt '.encode(), 16, 1, 1, 22050, 44100, 2, 16)
datachunk = struct.pack('<4sL', 'data'.encode(), 0)
reqchunk = struct.pack('<4sL', 'req '.encode(), reqlen) + reqdata.encode()
with open(wave['name'] + '.wav', 'wb') as f:
f.write(riffchunk + fmtchunk + datachunk + reqchunk)
|
#!/usr/bin/env python
import struct
wavelist = []
for s in range(12):
wave = {'method': 'POST'}
wave['url'] = 'http://localhost:3520/scenes/{0}/_load'.format(s + 1)
wave['name'] = 'Scene {0:02}'.format(s + 1)
wave['data'] = ''
wavelist.append(wave)
for wave in wavelist:
reqdata = '\n'.join((wave['method'], wave['url'], wave['data']))
reqlen = len(reqdata)
if reqlen % 2 == 1:
reqdata += '\n'
reqlen += 1
filelen = 36 + 8 + reqlen
riffchunk = struct.pack('<4sL4s', 'RIFF'.encode(), filelen, 'WAVE'.encode())
fmtchunk = struct.pack('<4sL2H2L2H', 'fmt '.encode(), 16, 1, 1, 22050, 44100, 2, 16)
datachunk = struct.pack('<4sL', 'data'.encode(), 0)
reqchunk = struct.pack('<4sL', 'req '.encode(), reqlen) + reqdata.encode()
with open(wave['name'] + '.wav', 'wb') as f:
f.write(riffchunk + fmtchunk + datachunk + reqchunk)
|
Update format of wave file generator.
|
Update format of wave file generator.
|
Python
|
apache-2.0
|
lordjabez/light-maestro,lordjabez/light-maestro,lordjabez/light-maestro,lordjabez/light-maestro
|
#!/usr/bin/env python
wavelist = []
for p in range(48):
for s in range(24):
wave = {'method': 'PUT', 'url': 'http://localhost:3520/scenes/_current'}
wave['name'] = 'P{0:02}-S{1:02}'.format(p + 1, s + 1)
wave['data'] = {'id': p * 24 + s}
wavelist.append(wave)
import json
import struct
for wave in wavelist:
reqdata = '\n'.join((wave['method'], wave['url'], json.dumps(wave['data'])))
reqlen = len(reqdata)
if reqlen % 2 == 1:
reqdata += '\n'
reqlen += 1
filelen = 36 + 8 + reqlen
riffchunk = struct.pack('<4sL4s', 'RIFF'.encode(), filelen, 'WAVE'.encode())
fmtchunk = struct.pack('<4sL2H2L2H', 'fmt '.encode(), 16, 1, 1, 22050, 44100, 2, 16)
datachunk = struct.pack('<4sL', 'data'.encode(), 0)
reqchunk = struct.pack('<4sL', 'req '.encode(), reqlen) + reqdata.encode()
with open(wave['name'] + '.wav', 'wb') as f:
f.write(riffchunk + fmtchunk + datachunk + reqchunk)
Update format of wave file generator.
|
#!/usr/bin/env python
import struct
wavelist = []
for s in range(12):
wave = {'method': 'POST'}
wave['url'] = 'http://localhost:3520/scenes/{0}/_load'.format(s + 1)
wave['name'] = 'Scene {0:02}'.format(s + 1)
wave['data'] = ''
wavelist.append(wave)
for wave in wavelist:
reqdata = '\n'.join((wave['method'], wave['url'], wave['data']))
reqlen = len(reqdata)
if reqlen % 2 == 1:
reqdata += '\n'
reqlen += 1
filelen = 36 + 8 + reqlen
riffchunk = struct.pack('<4sL4s', 'RIFF'.encode(), filelen, 'WAVE'.encode())
fmtchunk = struct.pack('<4sL2H2L2H', 'fmt '.encode(), 16, 1, 1, 22050, 44100, 2, 16)
datachunk = struct.pack('<4sL', 'data'.encode(), 0)
reqchunk = struct.pack('<4sL', 'req '.encode(), reqlen) + reqdata.encode()
with open(wave['name'] + '.wav', 'wb') as f:
f.write(riffchunk + fmtchunk + datachunk + reqchunk)
|
<commit_before>#!/usr/bin/env python
wavelist = []
for p in range(48):
for s in range(24):
wave = {'method': 'PUT', 'url': 'http://localhost:3520/scenes/_current'}
wave['name'] = 'P{0:02}-S{1:02}'.format(p + 1, s + 1)
wave['data'] = {'id': p * 24 + s}
wavelist.append(wave)
import json
import struct
for wave in wavelist:
reqdata = '\n'.join((wave['method'], wave['url'], json.dumps(wave['data'])))
reqlen = len(reqdata)
if reqlen % 2 == 1:
reqdata += '\n'
reqlen += 1
filelen = 36 + 8 + reqlen
riffchunk = struct.pack('<4sL4s', 'RIFF'.encode(), filelen, 'WAVE'.encode())
fmtchunk = struct.pack('<4sL2H2L2H', 'fmt '.encode(), 16, 1, 1, 22050, 44100, 2, 16)
datachunk = struct.pack('<4sL', 'data'.encode(), 0)
reqchunk = struct.pack('<4sL', 'req '.encode(), reqlen) + reqdata.encode()
with open(wave['name'] + '.wav', 'wb') as f:
f.write(riffchunk + fmtchunk + datachunk + reqchunk)
<commit_msg>Update format of wave file generator.<commit_after>
|
#!/usr/bin/env python
import struct
wavelist = []
for s in range(12):
wave = {'method': 'POST'}
wave['url'] = 'http://localhost:3520/scenes/{0}/_load'.format(s + 1)
wave['name'] = 'Scene {0:02}'.format(s + 1)
wave['data'] = ''
wavelist.append(wave)
for wave in wavelist:
reqdata = '\n'.join((wave['method'], wave['url'], wave['data']))
reqlen = len(reqdata)
if reqlen % 2 == 1:
reqdata += '\n'
reqlen += 1
filelen = 36 + 8 + reqlen
riffchunk = struct.pack('<4sL4s', 'RIFF'.encode(), filelen, 'WAVE'.encode())
fmtchunk = struct.pack('<4sL2H2L2H', 'fmt '.encode(), 16, 1, 1, 22050, 44100, 2, 16)
datachunk = struct.pack('<4sL', 'data'.encode(), 0)
reqchunk = struct.pack('<4sL', 'req '.encode(), reqlen) + reqdata.encode()
with open(wave['name'] + '.wav', 'wb') as f:
f.write(riffchunk + fmtchunk + datachunk + reqchunk)
|
#!/usr/bin/env python
wavelist = []
for p in range(48):
for s in range(24):
wave = {'method': 'PUT', 'url': 'http://localhost:3520/scenes/_current'}
wave['name'] = 'P{0:02}-S{1:02}'.format(p + 1, s + 1)
wave['data'] = {'id': p * 24 + s}
wavelist.append(wave)
import json
import struct
for wave in wavelist:
reqdata = '\n'.join((wave['method'], wave['url'], json.dumps(wave['data'])))
reqlen = len(reqdata)
if reqlen % 2 == 1:
reqdata += '\n'
reqlen += 1
filelen = 36 + 8 + reqlen
riffchunk = struct.pack('<4sL4s', 'RIFF'.encode(), filelen, 'WAVE'.encode())
fmtchunk = struct.pack('<4sL2H2L2H', 'fmt '.encode(), 16, 1, 1, 22050, 44100, 2, 16)
datachunk = struct.pack('<4sL', 'data'.encode(), 0)
reqchunk = struct.pack('<4sL', 'req '.encode(), reqlen) + reqdata.encode()
with open(wave['name'] + '.wav', 'wb') as f:
f.write(riffchunk + fmtchunk + datachunk + reqchunk)
Update format of wave file generator.#!/usr/bin/env python
import struct
wavelist = []
for s in range(12):
wave = {'method': 'POST'}
wave['url'] = 'http://localhost:3520/scenes/{0}/_load'.format(s + 1)
wave['name'] = 'Scene {0:02}'.format(s + 1)
wave['data'] = ''
wavelist.append(wave)
for wave in wavelist:
reqdata = '\n'.join((wave['method'], wave['url'], wave['data']))
reqlen = len(reqdata)
if reqlen % 2 == 1:
reqdata += '\n'
reqlen += 1
filelen = 36 + 8 + reqlen
riffchunk = struct.pack('<4sL4s', 'RIFF'.encode(), filelen, 'WAVE'.encode())
fmtchunk = struct.pack('<4sL2H2L2H', 'fmt '.encode(), 16, 1, 1, 22050, 44100, 2, 16)
datachunk = struct.pack('<4sL', 'data'.encode(), 0)
reqchunk = struct.pack('<4sL', 'req '.encode(), reqlen) + reqdata.encode()
with open(wave['name'] + '.wav', 'wb') as f:
f.write(riffchunk + fmtchunk + datachunk + reqchunk)
|
<commit_before>#!/usr/bin/env python
wavelist = []
for p in range(48):
for s in range(24):
wave = {'method': 'PUT', 'url': 'http://localhost:3520/scenes/_current'}
wave['name'] = 'P{0:02}-S{1:02}'.format(p + 1, s + 1)
wave['data'] = {'id': p * 24 + s}
wavelist.append(wave)
import json
import struct
for wave in wavelist:
reqdata = '\n'.join((wave['method'], wave['url'], json.dumps(wave['data'])))
reqlen = len(reqdata)
if reqlen % 2 == 1:
reqdata += '\n'
reqlen += 1
filelen = 36 + 8 + reqlen
riffchunk = struct.pack('<4sL4s', 'RIFF'.encode(), filelen, 'WAVE'.encode())
fmtchunk = struct.pack('<4sL2H2L2H', 'fmt '.encode(), 16, 1, 1, 22050, 44100, 2, 16)
datachunk = struct.pack('<4sL', 'data'.encode(), 0)
reqchunk = struct.pack('<4sL', 'req '.encode(), reqlen) + reqdata.encode()
with open(wave['name'] + '.wav', 'wb') as f:
f.write(riffchunk + fmtchunk + datachunk + reqchunk)
<commit_msg>Update format of wave file generator.<commit_after>#!/usr/bin/env python
import struct
wavelist = []
for s in range(12):
wave = {'method': 'POST'}
wave['url'] = 'http://localhost:3520/scenes/{0}/_load'.format(s + 1)
wave['name'] = 'Scene {0:02}'.format(s + 1)
wave['data'] = ''
wavelist.append(wave)
for wave in wavelist:
reqdata = '\n'.join((wave['method'], wave['url'], wave['data']))
reqlen = len(reqdata)
if reqlen % 2 == 1:
reqdata += '\n'
reqlen += 1
filelen = 36 + 8 + reqlen
riffchunk = struct.pack('<4sL4s', 'RIFF'.encode(), filelen, 'WAVE'.encode())
fmtchunk = struct.pack('<4sL2H2L2H', 'fmt '.encode(), 16, 1, 1, 22050, 44100, 2, 16)
datachunk = struct.pack('<4sL', 'data'.encode(), 0)
reqchunk = struct.pack('<4sL', 'req '.encode(), reqlen) + reqdata.encode()
with open(wave['name'] + '.wav', 'wb') as f:
f.write(riffchunk + fmtchunk + datachunk + reqchunk)
|
95abf6608d2deb1759f5911bdfd11f6a66fcf4ca
|
scripts/slave/chromium/test_webkitpy_wrapper.py
|
scripts/slave/chromium/test_webkitpy_wrapper.py
|
#!/usr/bin/env python
# Copyright 2013 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.
"""A wrapper script that invokes test-webkitpy."""
import optparse
import os
import sys
from common import chromium_utils
from slave import build_directory
from slave import slave_utils
def main():
option_parser = optparse.OptionParser()
option_parser.add_option('--build-dir', help='ignored')
# Note that --target isn't needed for --lint-test-files, but the
# RunPythonCommandInBuildDir() will get upset if we don't say something.
option_parser.add_option('', '--target', default='release',
help='DumpRenderTree build configuration (Release or Debug)')
options, _ = option_parser.parse_args()
options.build_dir = build_directory.GetBuildOutputDirectory()
build_dir = os.path.abspath(options.build_dir)
webkit_tests_dir = chromium_utils.FindUpward(build_dir,
'third_party', 'WebKit',
'Tools', 'Scripts')
command = [os.path.join(webkit_tests_dir, 'test-webkitpy')]
return slave_utils.RunPythonCommandInBuildDir(build_dir, options.target,
command)
if '__main__' == __name__:
sys.exit(main())
|
#!/usr/bin/env python
# Copyright 2013 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.
"""A wrapper script that invokes test-webkitpy."""
import optparse
import os
import sys
from common import chromium_utils
from slave import build_directory
from slave import slave_utils
def main():
option_parser = optparse.OptionParser()
option_parser.add_option('--build-dir', help='ignored')
# Note that --target isn't needed for --lint-test-files, but the
# RunPythonCommandInBuildDir() will get upset if we don't say something.
option_parser.add_option('', '--target', default='release',
help='DumpRenderTree build configuration (Release or Debug)')
options, _ = option_parser.parse_args()
options.build_dir, _ = build_directory.GetBuildOutputDirectory()
build_dir = os.path.abspath(options.build_dir)
webkit_tests_dir = chromium_utils.FindUpward(build_dir,
'third_party', 'WebKit',
'Tools', 'Scripts')
command = [os.path.join(webkit_tests_dir, 'test-webkitpy')]
return slave_utils.RunPythonCommandInBuildDir(build_dir, options.target,
command)
if '__main__' == __name__:
sys.exit(main())
|
Revert 232670 "Fix script after r232641"
|
Revert 232670 "Fix script after r232641"
Needs to be out to speculatively revert r232641.
> Fix script after r232641
>
> BUG=314253
> [email protected]
>
> Review URL: https://codereview.chromium.org/49753004
[email protected]
Review URL: https://codereview.chromium.org/57293002
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@232677 0039d316-1c4b-4281-b951-d872f2087c98
|
Python
|
bsd-3-clause
|
eunchong/build,eunchong/build,eunchong/build,eunchong/build
|
#!/usr/bin/env python
# Copyright 2013 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.
"""A wrapper script that invokes test-webkitpy."""
import optparse
import os
import sys
from common import chromium_utils
from slave import build_directory
from slave import slave_utils
def main():
option_parser = optparse.OptionParser()
option_parser.add_option('--build-dir', help='ignored')
# Note that --target isn't needed for --lint-test-files, but the
# RunPythonCommandInBuildDir() will get upset if we don't say something.
option_parser.add_option('', '--target', default='release',
help='DumpRenderTree build configuration (Release or Debug)')
options, _ = option_parser.parse_args()
options.build_dir = build_directory.GetBuildOutputDirectory()
build_dir = os.path.abspath(options.build_dir)
webkit_tests_dir = chromium_utils.FindUpward(build_dir,
'third_party', 'WebKit',
'Tools', 'Scripts')
command = [os.path.join(webkit_tests_dir, 'test-webkitpy')]
return slave_utils.RunPythonCommandInBuildDir(build_dir, options.target,
command)
if '__main__' == __name__:
sys.exit(main())
Revert 232670 "Fix script after r232641"
Needs to be out to speculatively revert r232641.
> Fix script after r232641
>
> BUG=314253
> [email protected]
>
> Review URL: https://codereview.chromium.org/49753004
[email protected]
Review URL: https://codereview.chromium.org/57293002
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@232677 0039d316-1c4b-4281-b951-d872f2087c98
|
#!/usr/bin/env python
# Copyright 2013 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.
"""A wrapper script that invokes test-webkitpy."""
import optparse
import os
import sys
from common import chromium_utils
from slave import build_directory
from slave import slave_utils
def main():
option_parser = optparse.OptionParser()
option_parser.add_option('--build-dir', help='ignored')
# Note that --target isn't needed for --lint-test-files, but the
# RunPythonCommandInBuildDir() will get upset if we don't say something.
option_parser.add_option('', '--target', default='release',
help='DumpRenderTree build configuration (Release or Debug)')
options, _ = option_parser.parse_args()
options.build_dir, _ = build_directory.GetBuildOutputDirectory()
build_dir = os.path.abspath(options.build_dir)
webkit_tests_dir = chromium_utils.FindUpward(build_dir,
'third_party', 'WebKit',
'Tools', 'Scripts')
command = [os.path.join(webkit_tests_dir, 'test-webkitpy')]
return slave_utils.RunPythonCommandInBuildDir(build_dir, options.target,
command)
if '__main__' == __name__:
sys.exit(main())
|
<commit_before>#!/usr/bin/env python
# Copyright 2013 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.
"""A wrapper script that invokes test-webkitpy."""
import optparse
import os
import sys
from common import chromium_utils
from slave import build_directory
from slave import slave_utils
def main():
option_parser = optparse.OptionParser()
option_parser.add_option('--build-dir', help='ignored')
# Note that --target isn't needed for --lint-test-files, but the
# RunPythonCommandInBuildDir() will get upset if we don't say something.
option_parser.add_option('', '--target', default='release',
help='DumpRenderTree build configuration (Release or Debug)')
options, _ = option_parser.parse_args()
options.build_dir = build_directory.GetBuildOutputDirectory()
build_dir = os.path.abspath(options.build_dir)
webkit_tests_dir = chromium_utils.FindUpward(build_dir,
'third_party', 'WebKit',
'Tools', 'Scripts')
command = [os.path.join(webkit_tests_dir, 'test-webkitpy')]
return slave_utils.RunPythonCommandInBuildDir(build_dir, options.target,
command)
if '__main__' == __name__:
sys.exit(main())
<commit_msg>Revert 232670 "Fix script after r232641"
Needs to be out to speculatively revert r232641.
> Fix script after r232641
>
> BUG=314253
> [email protected]
>
> Review URL: https://codereview.chromium.org/49753004
[email protected]
Review URL: https://codereview.chromium.org/57293002
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@232677 0039d316-1c4b-4281-b951-d872f2087c98<commit_after>
|
#!/usr/bin/env python
# Copyright 2013 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.
"""A wrapper script that invokes test-webkitpy."""
import optparse
import os
import sys
from common import chromium_utils
from slave import build_directory
from slave import slave_utils
def main():
option_parser = optparse.OptionParser()
option_parser.add_option('--build-dir', help='ignored')
# Note that --target isn't needed for --lint-test-files, but the
# RunPythonCommandInBuildDir() will get upset if we don't say something.
option_parser.add_option('', '--target', default='release',
help='DumpRenderTree build configuration (Release or Debug)')
options, _ = option_parser.parse_args()
options.build_dir, _ = build_directory.GetBuildOutputDirectory()
build_dir = os.path.abspath(options.build_dir)
webkit_tests_dir = chromium_utils.FindUpward(build_dir,
'third_party', 'WebKit',
'Tools', 'Scripts')
command = [os.path.join(webkit_tests_dir, 'test-webkitpy')]
return slave_utils.RunPythonCommandInBuildDir(build_dir, options.target,
command)
if '__main__' == __name__:
sys.exit(main())
|
#!/usr/bin/env python
# Copyright 2013 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.
"""A wrapper script that invokes test-webkitpy."""
import optparse
import os
import sys
from common import chromium_utils
from slave import build_directory
from slave import slave_utils
def main():
option_parser = optparse.OptionParser()
option_parser.add_option('--build-dir', help='ignored')
# Note that --target isn't needed for --lint-test-files, but the
# RunPythonCommandInBuildDir() will get upset if we don't say something.
option_parser.add_option('', '--target', default='release',
help='DumpRenderTree build configuration (Release or Debug)')
options, _ = option_parser.parse_args()
options.build_dir = build_directory.GetBuildOutputDirectory()
build_dir = os.path.abspath(options.build_dir)
webkit_tests_dir = chromium_utils.FindUpward(build_dir,
'third_party', 'WebKit',
'Tools', 'Scripts')
command = [os.path.join(webkit_tests_dir, 'test-webkitpy')]
return slave_utils.RunPythonCommandInBuildDir(build_dir, options.target,
command)
if '__main__' == __name__:
sys.exit(main())
Revert 232670 "Fix script after r232641"
Needs to be out to speculatively revert r232641.
> Fix script after r232641
>
> BUG=314253
> [email protected]
>
> Review URL: https://codereview.chromium.org/49753004
[email protected]
Review URL: https://codereview.chromium.org/57293002
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@232677 0039d316-1c4b-4281-b951-d872f2087c98#!/usr/bin/env python
# Copyright 2013 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.
"""A wrapper script that invokes test-webkitpy."""
import optparse
import os
import sys
from common import chromium_utils
from slave import build_directory
from slave import slave_utils
def main():
option_parser = optparse.OptionParser()
option_parser.add_option('--build-dir', help='ignored')
# Note that --target isn't needed for --lint-test-files, but the
# RunPythonCommandInBuildDir() will get upset if we don't say something.
option_parser.add_option('', '--target', default='release',
help='DumpRenderTree build configuration (Release or Debug)')
options, _ = option_parser.parse_args()
options.build_dir, _ = build_directory.GetBuildOutputDirectory()
build_dir = os.path.abspath(options.build_dir)
webkit_tests_dir = chromium_utils.FindUpward(build_dir,
'third_party', 'WebKit',
'Tools', 'Scripts')
command = [os.path.join(webkit_tests_dir, 'test-webkitpy')]
return slave_utils.RunPythonCommandInBuildDir(build_dir, options.target,
command)
if '__main__' == __name__:
sys.exit(main())
|
<commit_before>#!/usr/bin/env python
# Copyright 2013 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.
"""A wrapper script that invokes test-webkitpy."""
import optparse
import os
import sys
from common import chromium_utils
from slave import build_directory
from slave import slave_utils
def main():
option_parser = optparse.OptionParser()
option_parser.add_option('--build-dir', help='ignored')
# Note that --target isn't needed for --lint-test-files, but the
# RunPythonCommandInBuildDir() will get upset if we don't say something.
option_parser.add_option('', '--target', default='release',
help='DumpRenderTree build configuration (Release or Debug)')
options, _ = option_parser.parse_args()
options.build_dir = build_directory.GetBuildOutputDirectory()
build_dir = os.path.abspath(options.build_dir)
webkit_tests_dir = chromium_utils.FindUpward(build_dir,
'third_party', 'WebKit',
'Tools', 'Scripts')
command = [os.path.join(webkit_tests_dir, 'test-webkitpy')]
return slave_utils.RunPythonCommandInBuildDir(build_dir, options.target,
command)
if '__main__' == __name__:
sys.exit(main())
<commit_msg>Revert 232670 "Fix script after r232641"
Needs to be out to speculatively revert r232641.
> Fix script after r232641
>
> BUG=314253
> [email protected]
>
> Review URL: https://codereview.chromium.org/49753004
[email protected]
Review URL: https://codereview.chromium.org/57293002
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@232677 0039d316-1c4b-4281-b951-d872f2087c98<commit_after>#!/usr/bin/env python
# Copyright 2013 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.
"""A wrapper script that invokes test-webkitpy."""
import optparse
import os
import sys
from common import chromium_utils
from slave import build_directory
from slave import slave_utils
def main():
option_parser = optparse.OptionParser()
option_parser.add_option('--build-dir', help='ignored')
# Note that --target isn't needed for --lint-test-files, but the
# RunPythonCommandInBuildDir() will get upset if we don't say something.
option_parser.add_option('', '--target', default='release',
help='DumpRenderTree build configuration (Release or Debug)')
options, _ = option_parser.parse_args()
options.build_dir, _ = build_directory.GetBuildOutputDirectory()
build_dir = os.path.abspath(options.build_dir)
webkit_tests_dir = chromium_utils.FindUpward(build_dir,
'third_party', 'WebKit',
'Tools', 'Scripts')
command = [os.path.join(webkit_tests_dir, 'test-webkitpy')]
return slave_utils.RunPythonCommandInBuildDir(build_dir, options.target,
command)
if '__main__' == __name__:
sys.exit(main())
|
cbef288c363c70d6085f7f9390aec126919376bc
|
bin/isy_showevents.py
|
bin/isy_showevents.py
|
#!/usr/local/bin/python2.7 -u
__author__ = "Peter Shipley"
import os
import keyring
import ConfigParser
from ISY.IsyEvent import ISYEvent
def main() :
config = ConfigParser.ConfigParser()
config.read('isy.cfg')
server = ISYEvent()
# you can subscribe to multiple devices
# server.subscribe('10.1.1.25')
isy_addr = config.get('isy', 'addr')
isy_user = config.get('isy', 'user')
server.subscribe(
addr=isy_addr,
userl=isy_user,
userp=keyring.get_password("isy", isy_user) )
server.set_process_func(ISYEvent.print_event, "")
try:
print('Use Control-C to exit')
server.events_loop() #no return
# for d in server.event_iter( ignorelist=["_0", "_11"] ):
# server.print_event(d, "")
except KeyboardInterrupt:
print('Exiting')
if __name__ == '__main__' :
main()
exit(0)
|
#!/usr/local/bin/python2.7 -u
__author__ = "Peter Shipley"
import os
import keyring
import ConfigParser
from ISY.IsyEvent import ISYEvent
def main() :
config = ConfigParser.ConfigParser()
config.read(os.path.expanduser('~/isy.cfg'))
server = ISYEvent()
# you can subscribe to multiple devices
# server.subscribe('10.1.1.25')
isy_addr = config.get('isy', 'addr')
isy_user = config.get('isy', 'user')
server.subscribe(
addr=isy_addr,
userl=isy_user,
userp=keyring.get_password("isy", isy_user) )
server.set_process_func(ISYEvent.print_event, "")
try:
print('Use Control-C to exit')
server.events_loop() #no return
# for d in server.event_iter( ignorelist=["_0", "_11"] ):
# server.print_event(d, "")
except KeyboardInterrupt:
print('Exiting')
if __name__ == '__main__' :
main()
exit(0)
|
Move config file to user home directory
|
Move config file to user home directory
|
Python
|
bsd-2-clause
|
fxstein/ISYlib-python
|
#!/usr/local/bin/python2.7 -u
__author__ = "Peter Shipley"
import os
import keyring
import ConfigParser
from ISY.IsyEvent import ISYEvent
def main() :
config = ConfigParser.ConfigParser()
config.read('isy.cfg')
server = ISYEvent()
# you can subscribe to multiple devices
# server.subscribe('10.1.1.25')
isy_addr = config.get('isy', 'addr')
isy_user = config.get('isy', 'user')
server.subscribe(
addr=isy_addr,
userl=isy_user,
userp=keyring.get_password("isy", isy_user) )
server.set_process_func(ISYEvent.print_event, "")
try:
print('Use Control-C to exit')
server.events_loop() #no return
# for d in server.event_iter( ignorelist=["_0", "_11"] ):
# server.print_event(d, "")
except KeyboardInterrupt:
print('Exiting')
if __name__ == '__main__' :
main()
exit(0)
Move config file to user home directory
|
#!/usr/local/bin/python2.7 -u
__author__ = "Peter Shipley"
import os
import keyring
import ConfigParser
from ISY.IsyEvent import ISYEvent
def main() :
config = ConfigParser.ConfigParser()
config.read(os.path.expanduser('~/isy.cfg'))
server = ISYEvent()
# you can subscribe to multiple devices
# server.subscribe('10.1.1.25')
isy_addr = config.get('isy', 'addr')
isy_user = config.get('isy', 'user')
server.subscribe(
addr=isy_addr,
userl=isy_user,
userp=keyring.get_password("isy", isy_user) )
server.set_process_func(ISYEvent.print_event, "")
try:
print('Use Control-C to exit')
server.events_loop() #no return
# for d in server.event_iter( ignorelist=["_0", "_11"] ):
# server.print_event(d, "")
except KeyboardInterrupt:
print('Exiting')
if __name__ == '__main__' :
main()
exit(0)
|
<commit_before>#!/usr/local/bin/python2.7 -u
__author__ = "Peter Shipley"
import os
import keyring
import ConfigParser
from ISY.IsyEvent import ISYEvent
def main() :
config = ConfigParser.ConfigParser()
config.read('isy.cfg')
server = ISYEvent()
# you can subscribe to multiple devices
# server.subscribe('10.1.1.25')
isy_addr = config.get('isy', 'addr')
isy_user = config.get('isy', 'user')
server.subscribe(
addr=isy_addr,
userl=isy_user,
userp=keyring.get_password("isy", isy_user) )
server.set_process_func(ISYEvent.print_event, "")
try:
print('Use Control-C to exit')
server.events_loop() #no return
# for d in server.event_iter( ignorelist=["_0", "_11"] ):
# server.print_event(d, "")
except KeyboardInterrupt:
print('Exiting')
if __name__ == '__main__' :
main()
exit(0)
<commit_msg>Move config file to user home directory<commit_after>
|
#!/usr/local/bin/python2.7 -u
__author__ = "Peter Shipley"
import os
import keyring
import ConfigParser
from ISY.IsyEvent import ISYEvent
def main() :
config = ConfigParser.ConfigParser()
config.read(os.path.expanduser('~/isy.cfg'))
server = ISYEvent()
# you can subscribe to multiple devices
# server.subscribe('10.1.1.25')
isy_addr = config.get('isy', 'addr')
isy_user = config.get('isy', 'user')
server.subscribe(
addr=isy_addr,
userl=isy_user,
userp=keyring.get_password("isy", isy_user) )
server.set_process_func(ISYEvent.print_event, "")
try:
print('Use Control-C to exit')
server.events_loop() #no return
# for d in server.event_iter( ignorelist=["_0", "_11"] ):
# server.print_event(d, "")
except KeyboardInterrupt:
print('Exiting')
if __name__ == '__main__' :
main()
exit(0)
|
#!/usr/local/bin/python2.7 -u
__author__ = "Peter Shipley"
import os
import keyring
import ConfigParser
from ISY.IsyEvent import ISYEvent
def main() :
config = ConfigParser.ConfigParser()
config.read('isy.cfg')
server = ISYEvent()
# you can subscribe to multiple devices
# server.subscribe('10.1.1.25')
isy_addr = config.get('isy', 'addr')
isy_user = config.get('isy', 'user')
server.subscribe(
addr=isy_addr,
userl=isy_user,
userp=keyring.get_password("isy", isy_user) )
server.set_process_func(ISYEvent.print_event, "")
try:
print('Use Control-C to exit')
server.events_loop() #no return
# for d in server.event_iter( ignorelist=["_0", "_11"] ):
# server.print_event(d, "")
except KeyboardInterrupt:
print('Exiting')
if __name__ == '__main__' :
main()
exit(0)
Move config file to user home directory#!/usr/local/bin/python2.7 -u
__author__ = "Peter Shipley"
import os
import keyring
import ConfigParser
from ISY.IsyEvent import ISYEvent
def main() :
config = ConfigParser.ConfigParser()
config.read(os.path.expanduser('~/isy.cfg'))
server = ISYEvent()
# you can subscribe to multiple devices
# server.subscribe('10.1.1.25')
isy_addr = config.get('isy', 'addr')
isy_user = config.get('isy', 'user')
server.subscribe(
addr=isy_addr,
userl=isy_user,
userp=keyring.get_password("isy", isy_user) )
server.set_process_func(ISYEvent.print_event, "")
try:
print('Use Control-C to exit')
server.events_loop() #no return
# for d in server.event_iter( ignorelist=["_0", "_11"] ):
# server.print_event(d, "")
except KeyboardInterrupt:
print('Exiting')
if __name__ == '__main__' :
main()
exit(0)
|
<commit_before>#!/usr/local/bin/python2.7 -u
__author__ = "Peter Shipley"
import os
import keyring
import ConfigParser
from ISY.IsyEvent import ISYEvent
def main() :
config = ConfigParser.ConfigParser()
config.read('isy.cfg')
server = ISYEvent()
# you can subscribe to multiple devices
# server.subscribe('10.1.1.25')
isy_addr = config.get('isy', 'addr')
isy_user = config.get('isy', 'user')
server.subscribe(
addr=isy_addr,
userl=isy_user,
userp=keyring.get_password("isy", isy_user) )
server.set_process_func(ISYEvent.print_event, "")
try:
print('Use Control-C to exit')
server.events_loop() #no return
# for d in server.event_iter( ignorelist=["_0", "_11"] ):
# server.print_event(d, "")
except KeyboardInterrupt:
print('Exiting')
if __name__ == '__main__' :
main()
exit(0)
<commit_msg>Move config file to user home directory<commit_after>#!/usr/local/bin/python2.7 -u
__author__ = "Peter Shipley"
import os
import keyring
import ConfigParser
from ISY.IsyEvent import ISYEvent
def main() :
config = ConfigParser.ConfigParser()
config.read(os.path.expanduser('~/isy.cfg'))
server = ISYEvent()
# you can subscribe to multiple devices
# server.subscribe('10.1.1.25')
isy_addr = config.get('isy', 'addr')
isy_user = config.get('isy', 'user')
server.subscribe(
addr=isy_addr,
userl=isy_user,
userp=keyring.get_password("isy", isy_user) )
server.set_process_func(ISYEvent.print_event, "")
try:
print('Use Control-C to exit')
server.events_loop() #no return
# for d in server.event_iter( ignorelist=["_0", "_11"] ):
# server.print_event(d, "")
except KeyboardInterrupt:
print('Exiting')
if __name__ == '__main__' :
main()
exit(0)
|
35555b568d926caef8a7ad3471e3dd5ba8624c0e
|
norsourceparser/core/constants.py
|
norsourceparser/core/constants.py
|
REDUCED_RULE_VALENCY_TOKEN = 0
REDUCED_RULE_POS = 1
REDUCED_RULE_MORPHOLOGICAL_BREAKUP = 2
REDUCED_RULE_GLOSSES = 3
|
REDUCED_RULE_POS = 1
REDUCED_RULE_MORPHOLOGICAL_BREAKUP = 2
REDUCED_RULE_GLOSSES = 3
REDUCED_RULE_VALENCY = 4
|
Rename VALENCY constant and change index
|
Rename VALENCY constant and change index
|
Python
|
mit
|
Typecraft/norsourceparser
|
REDUCED_RULE_VALENCY_TOKEN = 0
REDUCED_RULE_POS = 1
REDUCED_RULE_MORPHOLOGICAL_BREAKUP = 2
REDUCED_RULE_GLOSSES = 3
Rename VALENCY constant and change index
|
REDUCED_RULE_POS = 1
REDUCED_RULE_MORPHOLOGICAL_BREAKUP = 2
REDUCED_RULE_GLOSSES = 3
REDUCED_RULE_VALENCY = 4
|
<commit_before>REDUCED_RULE_VALENCY_TOKEN = 0
REDUCED_RULE_POS = 1
REDUCED_RULE_MORPHOLOGICAL_BREAKUP = 2
REDUCED_RULE_GLOSSES = 3
<commit_msg>Rename VALENCY constant and change index<commit_after>
|
REDUCED_RULE_POS = 1
REDUCED_RULE_MORPHOLOGICAL_BREAKUP = 2
REDUCED_RULE_GLOSSES = 3
REDUCED_RULE_VALENCY = 4
|
REDUCED_RULE_VALENCY_TOKEN = 0
REDUCED_RULE_POS = 1
REDUCED_RULE_MORPHOLOGICAL_BREAKUP = 2
REDUCED_RULE_GLOSSES = 3
Rename VALENCY constant and change indexREDUCED_RULE_POS = 1
REDUCED_RULE_MORPHOLOGICAL_BREAKUP = 2
REDUCED_RULE_GLOSSES = 3
REDUCED_RULE_VALENCY = 4
|
<commit_before>REDUCED_RULE_VALENCY_TOKEN = 0
REDUCED_RULE_POS = 1
REDUCED_RULE_MORPHOLOGICAL_BREAKUP = 2
REDUCED_RULE_GLOSSES = 3
<commit_msg>Rename VALENCY constant and change index<commit_after>REDUCED_RULE_POS = 1
REDUCED_RULE_MORPHOLOGICAL_BREAKUP = 2
REDUCED_RULE_GLOSSES = 3
REDUCED_RULE_VALENCY = 4
|
838063cc08da66a31666f798437b8dcdde0286f0
|
mpf/config_players/flasher_player.py
|
mpf/config_players/flasher_player.py
|
"""Flasher config player."""
from mpf.config_players.device_config_player import DeviceConfigPlayer
from mpf.core.delays import DelayManager
class FlasherPlayer(DeviceConfigPlayer):
"""Triggers flashers based on config."""
config_file_section = 'flasher_player'
show_section = 'flashers'
__slots__ = ["delay"]
def __init__(self, machine):
"""Initialise flasher_player."""
super().__init__(machine)
self.delay = DelayManager(self.machine.delayRegistry)
def play(self, settings, context, calling_context, priority=0, **kwargs):
"""Flash flashers."""
del kwargs
for flasher, s in settings.items():
if isinstance(flasher, str):
self._flash(self.machine.lights[flasher],
duration_ms=s['ms'],
key=context)
else:
self._flash(flasher, duration_ms=s['ms'], key=context)
def _flash(self, light, duration_ms, key):
light.color("white", fade_ms=0, key=key)
self.delay.add(duration_ms, self._remove_flash, light=light, key=key)
@staticmethod
def _remove_flash(light, key):
light.remove_from_stack_by_key(key=key, fade_ms=0)
def get_express_config(self, value):
"""Parse express config."""
return dict(ms=value)
|
"""Flasher config player."""
from mpf.config_players.device_config_player import DeviceConfigPlayer
from mpf.core.delays import DelayManager
from mpf.core.utility_functions import Util
class FlasherPlayer(DeviceConfigPlayer):
"""Triggers flashers based on config."""
config_file_section = 'flasher_player'
show_section = 'flashers'
__slots__ = ["delay"]
def __init__(self, machine):
"""Initialise flasher_player."""
super().__init__(machine)
self.delay = DelayManager(self.machine.delayRegistry)
def play(self, settings, context, calling_context, priority=0, **kwargs):
"""Flash flashers."""
del kwargs
for flasher, s in settings.items():
if isinstance(flasher, str):
flasher_names = Util.string_to_list(flasher)
for flasher_name in flasher_names:
self._flash(self.machine.lights[flasher_name],
duration_ms=s['ms'],
key=context)
else:
self._flash(flasher, duration_ms=s['ms'], key=context)
def _flash(self, light, duration_ms, key):
light.color("white", fade_ms=0, key=key)
self.delay.add(duration_ms, self._remove_flash, light=light, key=key)
@staticmethod
def _remove_flash(light, key):
light.remove_from_stack_by_key(key=key, fade_ms=0)
def get_express_config(self, value):
"""Parse express config."""
return dict(ms=value)
|
Allow list of flashers as show token value
|
Allow list of flashers as show token value
|
Python
|
mit
|
missionpinball/mpf,missionpinball/mpf
|
"""Flasher config player."""
from mpf.config_players.device_config_player import DeviceConfigPlayer
from mpf.core.delays import DelayManager
class FlasherPlayer(DeviceConfigPlayer):
"""Triggers flashers based on config."""
config_file_section = 'flasher_player'
show_section = 'flashers'
__slots__ = ["delay"]
def __init__(self, machine):
"""Initialise flasher_player."""
super().__init__(machine)
self.delay = DelayManager(self.machine.delayRegistry)
def play(self, settings, context, calling_context, priority=0, **kwargs):
"""Flash flashers."""
del kwargs
for flasher, s in settings.items():
if isinstance(flasher, str):
self._flash(self.machine.lights[flasher],
duration_ms=s['ms'],
key=context)
else:
self._flash(flasher, duration_ms=s['ms'], key=context)
def _flash(self, light, duration_ms, key):
light.color("white", fade_ms=0, key=key)
self.delay.add(duration_ms, self._remove_flash, light=light, key=key)
@staticmethod
def _remove_flash(light, key):
light.remove_from_stack_by_key(key=key, fade_ms=0)
def get_express_config(self, value):
"""Parse express config."""
return dict(ms=value)
Allow list of flashers as show token value
|
"""Flasher config player."""
from mpf.config_players.device_config_player import DeviceConfigPlayer
from mpf.core.delays import DelayManager
from mpf.core.utility_functions import Util
class FlasherPlayer(DeviceConfigPlayer):
"""Triggers flashers based on config."""
config_file_section = 'flasher_player'
show_section = 'flashers'
__slots__ = ["delay"]
def __init__(self, machine):
"""Initialise flasher_player."""
super().__init__(machine)
self.delay = DelayManager(self.machine.delayRegistry)
def play(self, settings, context, calling_context, priority=0, **kwargs):
"""Flash flashers."""
del kwargs
for flasher, s in settings.items():
if isinstance(flasher, str):
flasher_names = Util.string_to_list(flasher)
for flasher_name in flasher_names:
self._flash(self.machine.lights[flasher_name],
duration_ms=s['ms'],
key=context)
else:
self._flash(flasher, duration_ms=s['ms'], key=context)
def _flash(self, light, duration_ms, key):
light.color("white", fade_ms=0, key=key)
self.delay.add(duration_ms, self._remove_flash, light=light, key=key)
@staticmethod
def _remove_flash(light, key):
light.remove_from_stack_by_key(key=key, fade_ms=0)
def get_express_config(self, value):
"""Parse express config."""
return dict(ms=value)
|
<commit_before>"""Flasher config player."""
from mpf.config_players.device_config_player import DeviceConfigPlayer
from mpf.core.delays import DelayManager
class FlasherPlayer(DeviceConfigPlayer):
"""Triggers flashers based on config."""
config_file_section = 'flasher_player'
show_section = 'flashers'
__slots__ = ["delay"]
def __init__(self, machine):
"""Initialise flasher_player."""
super().__init__(machine)
self.delay = DelayManager(self.machine.delayRegistry)
def play(self, settings, context, calling_context, priority=0, **kwargs):
"""Flash flashers."""
del kwargs
for flasher, s in settings.items():
if isinstance(flasher, str):
self._flash(self.machine.lights[flasher],
duration_ms=s['ms'],
key=context)
else:
self._flash(flasher, duration_ms=s['ms'], key=context)
def _flash(self, light, duration_ms, key):
light.color("white", fade_ms=0, key=key)
self.delay.add(duration_ms, self._remove_flash, light=light, key=key)
@staticmethod
def _remove_flash(light, key):
light.remove_from_stack_by_key(key=key, fade_ms=0)
def get_express_config(self, value):
"""Parse express config."""
return dict(ms=value)
<commit_msg>Allow list of flashers as show token value<commit_after>
|
"""Flasher config player."""
from mpf.config_players.device_config_player import DeviceConfigPlayer
from mpf.core.delays import DelayManager
from mpf.core.utility_functions import Util
class FlasherPlayer(DeviceConfigPlayer):
"""Triggers flashers based on config."""
config_file_section = 'flasher_player'
show_section = 'flashers'
__slots__ = ["delay"]
def __init__(self, machine):
"""Initialise flasher_player."""
super().__init__(machine)
self.delay = DelayManager(self.machine.delayRegistry)
def play(self, settings, context, calling_context, priority=0, **kwargs):
"""Flash flashers."""
del kwargs
for flasher, s in settings.items():
if isinstance(flasher, str):
flasher_names = Util.string_to_list(flasher)
for flasher_name in flasher_names:
self._flash(self.machine.lights[flasher_name],
duration_ms=s['ms'],
key=context)
else:
self._flash(flasher, duration_ms=s['ms'], key=context)
def _flash(self, light, duration_ms, key):
light.color("white", fade_ms=0, key=key)
self.delay.add(duration_ms, self._remove_flash, light=light, key=key)
@staticmethod
def _remove_flash(light, key):
light.remove_from_stack_by_key(key=key, fade_ms=0)
def get_express_config(self, value):
"""Parse express config."""
return dict(ms=value)
|
"""Flasher config player."""
from mpf.config_players.device_config_player import DeviceConfigPlayer
from mpf.core.delays import DelayManager
class FlasherPlayer(DeviceConfigPlayer):
"""Triggers flashers based on config."""
config_file_section = 'flasher_player'
show_section = 'flashers'
__slots__ = ["delay"]
def __init__(self, machine):
"""Initialise flasher_player."""
super().__init__(machine)
self.delay = DelayManager(self.machine.delayRegistry)
def play(self, settings, context, calling_context, priority=0, **kwargs):
"""Flash flashers."""
del kwargs
for flasher, s in settings.items():
if isinstance(flasher, str):
self._flash(self.machine.lights[flasher],
duration_ms=s['ms'],
key=context)
else:
self._flash(flasher, duration_ms=s['ms'], key=context)
def _flash(self, light, duration_ms, key):
light.color("white", fade_ms=0, key=key)
self.delay.add(duration_ms, self._remove_flash, light=light, key=key)
@staticmethod
def _remove_flash(light, key):
light.remove_from_stack_by_key(key=key, fade_ms=0)
def get_express_config(self, value):
"""Parse express config."""
return dict(ms=value)
Allow list of flashers as show token value"""Flasher config player."""
from mpf.config_players.device_config_player import DeviceConfigPlayer
from mpf.core.delays import DelayManager
from mpf.core.utility_functions import Util
class FlasherPlayer(DeviceConfigPlayer):
"""Triggers flashers based on config."""
config_file_section = 'flasher_player'
show_section = 'flashers'
__slots__ = ["delay"]
def __init__(self, machine):
"""Initialise flasher_player."""
super().__init__(machine)
self.delay = DelayManager(self.machine.delayRegistry)
def play(self, settings, context, calling_context, priority=0, **kwargs):
"""Flash flashers."""
del kwargs
for flasher, s in settings.items():
if isinstance(flasher, str):
flasher_names = Util.string_to_list(flasher)
for flasher_name in flasher_names:
self._flash(self.machine.lights[flasher_name],
duration_ms=s['ms'],
key=context)
else:
self._flash(flasher, duration_ms=s['ms'], key=context)
def _flash(self, light, duration_ms, key):
light.color("white", fade_ms=0, key=key)
self.delay.add(duration_ms, self._remove_flash, light=light, key=key)
@staticmethod
def _remove_flash(light, key):
light.remove_from_stack_by_key(key=key, fade_ms=0)
def get_express_config(self, value):
"""Parse express config."""
return dict(ms=value)
|
<commit_before>"""Flasher config player."""
from mpf.config_players.device_config_player import DeviceConfigPlayer
from mpf.core.delays import DelayManager
class FlasherPlayer(DeviceConfigPlayer):
"""Triggers flashers based on config."""
config_file_section = 'flasher_player'
show_section = 'flashers'
__slots__ = ["delay"]
def __init__(self, machine):
"""Initialise flasher_player."""
super().__init__(machine)
self.delay = DelayManager(self.machine.delayRegistry)
def play(self, settings, context, calling_context, priority=0, **kwargs):
"""Flash flashers."""
del kwargs
for flasher, s in settings.items():
if isinstance(flasher, str):
self._flash(self.machine.lights[flasher],
duration_ms=s['ms'],
key=context)
else:
self._flash(flasher, duration_ms=s['ms'], key=context)
def _flash(self, light, duration_ms, key):
light.color("white", fade_ms=0, key=key)
self.delay.add(duration_ms, self._remove_flash, light=light, key=key)
@staticmethod
def _remove_flash(light, key):
light.remove_from_stack_by_key(key=key, fade_ms=0)
def get_express_config(self, value):
"""Parse express config."""
return dict(ms=value)
<commit_msg>Allow list of flashers as show token value<commit_after>"""Flasher config player."""
from mpf.config_players.device_config_player import DeviceConfigPlayer
from mpf.core.delays import DelayManager
from mpf.core.utility_functions import Util
class FlasherPlayer(DeviceConfigPlayer):
"""Triggers flashers based on config."""
config_file_section = 'flasher_player'
show_section = 'flashers'
__slots__ = ["delay"]
def __init__(self, machine):
"""Initialise flasher_player."""
super().__init__(machine)
self.delay = DelayManager(self.machine.delayRegistry)
def play(self, settings, context, calling_context, priority=0, **kwargs):
"""Flash flashers."""
del kwargs
for flasher, s in settings.items():
if isinstance(flasher, str):
flasher_names = Util.string_to_list(flasher)
for flasher_name in flasher_names:
self._flash(self.machine.lights[flasher_name],
duration_ms=s['ms'],
key=context)
else:
self._flash(flasher, duration_ms=s['ms'], key=context)
def _flash(self, light, duration_ms, key):
light.color("white", fade_ms=0, key=key)
self.delay.add(duration_ms, self._remove_flash, light=light, key=key)
@staticmethod
def _remove_flash(light, key):
light.remove_from_stack_by_key(key=key, fade_ms=0)
def get_express_config(self, value):
"""Parse express config."""
return dict(ms=value)
|
67b03b45c338143d0e1496dc0c48046ca000b8e8
|
tests/integration/aiohttp_utils.py
|
tests/integration/aiohttp_utils.py
|
# flake8: noqa
import asyncio
import aiohttp
from aiohttp.test_utils import TestClient
async def aiohttp_request(loop, method, url, output='text', encoding='utf-8', content_type=None, **kwargs):
session = aiohttp.ClientSession(loop=loop)
response_ctx = session.request(method, url, **kwargs)
response = await response_ctx.__aenter__()
if output == 'text':
content = await response.text()
elif output == 'json':
content_type = content_type or 'application/json'
content = await response.json(encoding=encoding, content_type=content_type)
elif output == 'raw':
content = await response.read()
response_ctx._resp.close()
await session.close()
return response, content
def aiohttp_app():
async def hello(request):
return aiohttp.web.Response(text='hello')
app = aiohttp.web.Application()
app.router.add_get('/', hello)
return app
|
# flake8: noqa
import asyncio
import aiohttp
from aiohttp.test_utils import TestClient
async def aiohttp_request(loop, method, url, output='text', encoding='utf-8', content_type=None, **kwargs):
session = aiohttp.ClientSession(loop=loop)
response_ctx = session.request(method, url, **kwargs)
response = await response_ctx.__aenter__()
if output == 'text':
content = await response.text()
elif output == 'json':
content_type = content_type or 'application/json'
content = await response.json(encoding=encoding, content_type=content_type)
elif output == 'raw':
content = await response.read()
elif output == 'stream':
content = await response.content.read()
response_ctx._resp.close()
await session.close()
return response, content
def aiohttp_app():
async def hello(request):
return aiohttp.web.Response(text='hello')
app = aiohttp.web.Application()
app.router.add_get('/', hello)
return app
|
Add output option to use response.content stream
|
Add output option to use response.content stream
|
Python
|
mit
|
kevin1024/vcrpy,kevin1024/vcrpy,graingert/vcrpy,graingert/vcrpy
|
# flake8: noqa
import asyncio
import aiohttp
from aiohttp.test_utils import TestClient
async def aiohttp_request(loop, method, url, output='text', encoding='utf-8', content_type=None, **kwargs):
session = aiohttp.ClientSession(loop=loop)
response_ctx = session.request(method, url, **kwargs)
response = await response_ctx.__aenter__()
if output == 'text':
content = await response.text()
elif output == 'json':
content_type = content_type or 'application/json'
content = await response.json(encoding=encoding, content_type=content_type)
elif output == 'raw':
content = await response.read()
response_ctx._resp.close()
await session.close()
return response, content
def aiohttp_app():
async def hello(request):
return aiohttp.web.Response(text='hello')
app = aiohttp.web.Application()
app.router.add_get('/', hello)
return app
Add output option to use response.content stream
|
# flake8: noqa
import asyncio
import aiohttp
from aiohttp.test_utils import TestClient
async def aiohttp_request(loop, method, url, output='text', encoding='utf-8', content_type=None, **kwargs):
session = aiohttp.ClientSession(loop=loop)
response_ctx = session.request(method, url, **kwargs)
response = await response_ctx.__aenter__()
if output == 'text':
content = await response.text()
elif output == 'json':
content_type = content_type or 'application/json'
content = await response.json(encoding=encoding, content_type=content_type)
elif output == 'raw':
content = await response.read()
elif output == 'stream':
content = await response.content.read()
response_ctx._resp.close()
await session.close()
return response, content
def aiohttp_app():
async def hello(request):
return aiohttp.web.Response(text='hello')
app = aiohttp.web.Application()
app.router.add_get('/', hello)
return app
|
<commit_before># flake8: noqa
import asyncio
import aiohttp
from aiohttp.test_utils import TestClient
async def aiohttp_request(loop, method, url, output='text', encoding='utf-8', content_type=None, **kwargs):
session = aiohttp.ClientSession(loop=loop)
response_ctx = session.request(method, url, **kwargs)
response = await response_ctx.__aenter__()
if output == 'text':
content = await response.text()
elif output == 'json':
content_type = content_type or 'application/json'
content = await response.json(encoding=encoding, content_type=content_type)
elif output == 'raw':
content = await response.read()
response_ctx._resp.close()
await session.close()
return response, content
def aiohttp_app():
async def hello(request):
return aiohttp.web.Response(text='hello')
app = aiohttp.web.Application()
app.router.add_get('/', hello)
return app
<commit_msg>Add output option to use response.content stream<commit_after>
|
# flake8: noqa
import asyncio
import aiohttp
from aiohttp.test_utils import TestClient
async def aiohttp_request(loop, method, url, output='text', encoding='utf-8', content_type=None, **kwargs):
session = aiohttp.ClientSession(loop=loop)
response_ctx = session.request(method, url, **kwargs)
response = await response_ctx.__aenter__()
if output == 'text':
content = await response.text()
elif output == 'json':
content_type = content_type or 'application/json'
content = await response.json(encoding=encoding, content_type=content_type)
elif output == 'raw':
content = await response.read()
elif output == 'stream':
content = await response.content.read()
response_ctx._resp.close()
await session.close()
return response, content
def aiohttp_app():
async def hello(request):
return aiohttp.web.Response(text='hello')
app = aiohttp.web.Application()
app.router.add_get('/', hello)
return app
|
# flake8: noqa
import asyncio
import aiohttp
from aiohttp.test_utils import TestClient
async def aiohttp_request(loop, method, url, output='text', encoding='utf-8', content_type=None, **kwargs):
session = aiohttp.ClientSession(loop=loop)
response_ctx = session.request(method, url, **kwargs)
response = await response_ctx.__aenter__()
if output == 'text':
content = await response.text()
elif output == 'json':
content_type = content_type or 'application/json'
content = await response.json(encoding=encoding, content_type=content_type)
elif output == 'raw':
content = await response.read()
response_ctx._resp.close()
await session.close()
return response, content
def aiohttp_app():
async def hello(request):
return aiohttp.web.Response(text='hello')
app = aiohttp.web.Application()
app.router.add_get('/', hello)
return app
Add output option to use response.content stream# flake8: noqa
import asyncio
import aiohttp
from aiohttp.test_utils import TestClient
async def aiohttp_request(loop, method, url, output='text', encoding='utf-8', content_type=None, **kwargs):
session = aiohttp.ClientSession(loop=loop)
response_ctx = session.request(method, url, **kwargs)
response = await response_ctx.__aenter__()
if output == 'text':
content = await response.text()
elif output == 'json':
content_type = content_type or 'application/json'
content = await response.json(encoding=encoding, content_type=content_type)
elif output == 'raw':
content = await response.read()
elif output == 'stream':
content = await response.content.read()
response_ctx._resp.close()
await session.close()
return response, content
def aiohttp_app():
async def hello(request):
return aiohttp.web.Response(text='hello')
app = aiohttp.web.Application()
app.router.add_get('/', hello)
return app
|
<commit_before># flake8: noqa
import asyncio
import aiohttp
from aiohttp.test_utils import TestClient
async def aiohttp_request(loop, method, url, output='text', encoding='utf-8', content_type=None, **kwargs):
session = aiohttp.ClientSession(loop=loop)
response_ctx = session.request(method, url, **kwargs)
response = await response_ctx.__aenter__()
if output == 'text':
content = await response.text()
elif output == 'json':
content_type = content_type or 'application/json'
content = await response.json(encoding=encoding, content_type=content_type)
elif output == 'raw':
content = await response.read()
response_ctx._resp.close()
await session.close()
return response, content
def aiohttp_app():
async def hello(request):
return aiohttp.web.Response(text='hello')
app = aiohttp.web.Application()
app.router.add_get('/', hello)
return app
<commit_msg>Add output option to use response.content stream<commit_after># flake8: noqa
import asyncio
import aiohttp
from aiohttp.test_utils import TestClient
async def aiohttp_request(loop, method, url, output='text', encoding='utf-8', content_type=None, **kwargs):
session = aiohttp.ClientSession(loop=loop)
response_ctx = session.request(method, url, **kwargs)
response = await response_ctx.__aenter__()
if output == 'text':
content = await response.text()
elif output == 'json':
content_type = content_type or 'application/json'
content = await response.json(encoding=encoding, content_type=content_type)
elif output == 'raw':
content = await response.read()
elif output == 'stream':
content = await response.content.read()
response_ctx._resp.close()
await session.close()
return response, content
def aiohttp_app():
async def hello(request):
return aiohttp.web.Response(text='hello')
app = aiohttp.web.Application()
app.router.add_get('/', hello)
return app
|
208c850982734e109fe408114f595fe9a459cd8e
|
client/python/rndlib/conf.py
|
client/python/rndlib/conf.py
|
import os
NETWORK_DISABLED = True
NETWORK_PORT = 11338
PLOW_HOSTS = ["localhost:11337"]
|
import os
NETWORK_DISABLED = False
NETWORK_PORT = 11338
PLOW_HOSTS = ["localhost:11337"]
|
Enable the network by default.
|
Enable the network by default.
|
Python
|
apache-2.0
|
chadmv/plow,Br3nda/plow,Br3nda/plow,Br3nda/plow,chadmv/plow,chadmv/plow,Br3nda/plow,Br3nda/plow,chadmv/plow,chadmv/plow,chadmv/plow,chadmv/plow
|
import os
NETWORK_DISABLED = True
NETWORK_PORT = 11338
PLOW_HOSTS = ["localhost:11337"]
Enable the network by default.
|
import os
NETWORK_DISABLED = False
NETWORK_PORT = 11338
PLOW_HOSTS = ["localhost:11337"]
|
<commit_before>import os
NETWORK_DISABLED = True
NETWORK_PORT = 11338
PLOW_HOSTS = ["localhost:11337"]
<commit_msg>Enable the network by default.<commit_after>
|
import os
NETWORK_DISABLED = False
NETWORK_PORT = 11338
PLOW_HOSTS = ["localhost:11337"]
|
import os
NETWORK_DISABLED = True
NETWORK_PORT = 11338
PLOW_HOSTS = ["localhost:11337"]
Enable the network by default.import os
NETWORK_DISABLED = False
NETWORK_PORT = 11338
PLOW_HOSTS = ["localhost:11337"]
|
<commit_before>import os
NETWORK_DISABLED = True
NETWORK_PORT = 11338
PLOW_HOSTS = ["localhost:11337"]
<commit_msg>Enable the network by default.<commit_after>import os
NETWORK_DISABLED = False
NETWORK_PORT = 11338
PLOW_HOSTS = ["localhost:11337"]
|
0983986f6fc75b1acf0e76255844f7c96ba9838f
|
pip_refresh/__init__.py
|
pip_refresh/__init__.py
|
from functools import partial
import subprocess
import requests
def get_pkg_info(pkg_name, session):
r = session.get('http://pypi.python.org/pypi/%s/json' % (pkg_name,))
if r.status_code == requests.codes.ok:
return r.json
else:
raise ValueError('Package %r not found on PyPI.' % (pkg_name,))
def latest_version(pkg_name, session, silent=False):
try:
info = get_pkg_info(pkg_name, session)
except ValueError:
if silent:
return None
else:
raise
return info['info']['version']
def get_latest_versions(pkg_names):
with requests.session() as session:
get_latest = partial(latest_version, session=session, silent=True)
versions = map(get_latest, pkg_names)
return zip(pkg_names, versions)
def get_installed_pkgs(editables=False):
for line in subprocess.check_output(['pip', 'freeze']).split('\n'):
if not line:
continue
if line.startswith('-e'):
if editables:
yield line.split('#egg=', 1)[1], None, True
else:
name, version = line.split('==')
yield name, version, False
|
from functools import partial
import subprocess
import multiprocessing
import requests
def get_pkg_info(pkg_name, session):
r = session.get('http://pypi.python.org/pypi/%s/json' % (pkg_name,))
if r.status_code == requests.codes.ok:
return r.json
else:
raise ValueError('Package %r not found on PyPI.' % (pkg_name,))
def latest_version(pkg_name, session, silent=False):
try:
info = get_pkg_info(pkg_name, session)
except ValueError:
if silent:
return None
else:
raise
return info['info']['version']
def get_latest_versions(pkg_names):
with requests.session() as session:
pool = multiprocessing.Pool(min(12, len(pkg_names)))
get_latest = partial(latest_version, session=session, silent=True)
versions = pool.map(get_latest, pkg_names)
return zip(pkg_names, versions)
def get_installed_pkgs(editables=False):
for line in subprocess.check_output(['pip', 'freeze']).split('\n'):
if not line:
continue
if line.startswith('-e'):
if editables:
yield line.split('#egg=', 1)[1], None, True
else:
name, version = line.split('==')
yield name, version, False
|
Use multiprocessing to get quicker updates from PyPI.
|
Use multiprocessing to get quicker updates from PyPI.
|
Python
|
bsd-2-clause
|
suutari/prequ,suutari/prequ,suutari-ai/prequ
|
from functools import partial
import subprocess
import requests
def get_pkg_info(pkg_name, session):
r = session.get('http://pypi.python.org/pypi/%s/json' % (pkg_name,))
if r.status_code == requests.codes.ok:
return r.json
else:
raise ValueError('Package %r not found on PyPI.' % (pkg_name,))
def latest_version(pkg_name, session, silent=False):
try:
info = get_pkg_info(pkg_name, session)
except ValueError:
if silent:
return None
else:
raise
return info['info']['version']
def get_latest_versions(pkg_names):
with requests.session() as session:
get_latest = partial(latest_version, session=session, silent=True)
versions = map(get_latest, pkg_names)
return zip(pkg_names, versions)
def get_installed_pkgs(editables=False):
for line in subprocess.check_output(['pip', 'freeze']).split('\n'):
if not line:
continue
if line.startswith('-e'):
if editables:
yield line.split('#egg=', 1)[1], None, True
else:
name, version = line.split('==')
yield name, version, False
Use multiprocessing to get quicker updates from PyPI.
|
from functools import partial
import subprocess
import multiprocessing
import requests
def get_pkg_info(pkg_name, session):
r = session.get('http://pypi.python.org/pypi/%s/json' % (pkg_name,))
if r.status_code == requests.codes.ok:
return r.json
else:
raise ValueError('Package %r not found on PyPI.' % (pkg_name,))
def latest_version(pkg_name, session, silent=False):
try:
info = get_pkg_info(pkg_name, session)
except ValueError:
if silent:
return None
else:
raise
return info['info']['version']
def get_latest_versions(pkg_names):
with requests.session() as session:
pool = multiprocessing.Pool(min(12, len(pkg_names)))
get_latest = partial(latest_version, session=session, silent=True)
versions = pool.map(get_latest, pkg_names)
return zip(pkg_names, versions)
def get_installed_pkgs(editables=False):
for line in subprocess.check_output(['pip', 'freeze']).split('\n'):
if not line:
continue
if line.startswith('-e'):
if editables:
yield line.split('#egg=', 1)[1], None, True
else:
name, version = line.split('==')
yield name, version, False
|
<commit_before>from functools import partial
import subprocess
import requests
def get_pkg_info(pkg_name, session):
r = session.get('http://pypi.python.org/pypi/%s/json' % (pkg_name,))
if r.status_code == requests.codes.ok:
return r.json
else:
raise ValueError('Package %r not found on PyPI.' % (pkg_name,))
def latest_version(pkg_name, session, silent=False):
try:
info = get_pkg_info(pkg_name, session)
except ValueError:
if silent:
return None
else:
raise
return info['info']['version']
def get_latest_versions(pkg_names):
with requests.session() as session:
get_latest = partial(latest_version, session=session, silent=True)
versions = map(get_latest, pkg_names)
return zip(pkg_names, versions)
def get_installed_pkgs(editables=False):
for line in subprocess.check_output(['pip', 'freeze']).split('\n'):
if not line:
continue
if line.startswith('-e'):
if editables:
yield line.split('#egg=', 1)[1], None, True
else:
name, version = line.split('==')
yield name, version, False
<commit_msg>Use multiprocessing to get quicker updates from PyPI.<commit_after>
|
from functools import partial
import subprocess
import multiprocessing
import requests
def get_pkg_info(pkg_name, session):
r = session.get('http://pypi.python.org/pypi/%s/json' % (pkg_name,))
if r.status_code == requests.codes.ok:
return r.json
else:
raise ValueError('Package %r not found on PyPI.' % (pkg_name,))
def latest_version(pkg_name, session, silent=False):
try:
info = get_pkg_info(pkg_name, session)
except ValueError:
if silent:
return None
else:
raise
return info['info']['version']
def get_latest_versions(pkg_names):
with requests.session() as session:
pool = multiprocessing.Pool(min(12, len(pkg_names)))
get_latest = partial(latest_version, session=session, silent=True)
versions = pool.map(get_latest, pkg_names)
return zip(pkg_names, versions)
def get_installed_pkgs(editables=False):
for line in subprocess.check_output(['pip', 'freeze']).split('\n'):
if not line:
continue
if line.startswith('-e'):
if editables:
yield line.split('#egg=', 1)[1], None, True
else:
name, version = line.split('==')
yield name, version, False
|
from functools import partial
import subprocess
import requests
def get_pkg_info(pkg_name, session):
r = session.get('http://pypi.python.org/pypi/%s/json' % (pkg_name,))
if r.status_code == requests.codes.ok:
return r.json
else:
raise ValueError('Package %r not found on PyPI.' % (pkg_name,))
def latest_version(pkg_name, session, silent=False):
try:
info = get_pkg_info(pkg_name, session)
except ValueError:
if silent:
return None
else:
raise
return info['info']['version']
def get_latest_versions(pkg_names):
with requests.session() as session:
get_latest = partial(latest_version, session=session, silent=True)
versions = map(get_latest, pkg_names)
return zip(pkg_names, versions)
def get_installed_pkgs(editables=False):
for line in subprocess.check_output(['pip', 'freeze']).split('\n'):
if not line:
continue
if line.startswith('-e'):
if editables:
yield line.split('#egg=', 1)[1], None, True
else:
name, version = line.split('==')
yield name, version, False
Use multiprocessing to get quicker updates from PyPI.from functools import partial
import subprocess
import multiprocessing
import requests
def get_pkg_info(pkg_name, session):
r = session.get('http://pypi.python.org/pypi/%s/json' % (pkg_name,))
if r.status_code == requests.codes.ok:
return r.json
else:
raise ValueError('Package %r not found on PyPI.' % (pkg_name,))
def latest_version(pkg_name, session, silent=False):
try:
info = get_pkg_info(pkg_name, session)
except ValueError:
if silent:
return None
else:
raise
return info['info']['version']
def get_latest_versions(pkg_names):
with requests.session() as session:
pool = multiprocessing.Pool(min(12, len(pkg_names)))
get_latest = partial(latest_version, session=session, silent=True)
versions = pool.map(get_latest, pkg_names)
return zip(pkg_names, versions)
def get_installed_pkgs(editables=False):
for line in subprocess.check_output(['pip', 'freeze']).split('\n'):
if not line:
continue
if line.startswith('-e'):
if editables:
yield line.split('#egg=', 1)[1], None, True
else:
name, version = line.split('==')
yield name, version, False
|
<commit_before>from functools import partial
import subprocess
import requests
def get_pkg_info(pkg_name, session):
r = session.get('http://pypi.python.org/pypi/%s/json' % (pkg_name,))
if r.status_code == requests.codes.ok:
return r.json
else:
raise ValueError('Package %r not found on PyPI.' % (pkg_name,))
def latest_version(pkg_name, session, silent=False):
try:
info = get_pkg_info(pkg_name, session)
except ValueError:
if silent:
return None
else:
raise
return info['info']['version']
def get_latest_versions(pkg_names):
with requests.session() as session:
get_latest = partial(latest_version, session=session, silent=True)
versions = map(get_latest, pkg_names)
return zip(pkg_names, versions)
def get_installed_pkgs(editables=False):
for line in subprocess.check_output(['pip', 'freeze']).split('\n'):
if not line:
continue
if line.startswith('-e'):
if editables:
yield line.split('#egg=', 1)[1], None, True
else:
name, version = line.split('==')
yield name, version, False
<commit_msg>Use multiprocessing to get quicker updates from PyPI.<commit_after>from functools import partial
import subprocess
import multiprocessing
import requests
def get_pkg_info(pkg_name, session):
r = session.get('http://pypi.python.org/pypi/%s/json' % (pkg_name,))
if r.status_code == requests.codes.ok:
return r.json
else:
raise ValueError('Package %r not found on PyPI.' % (pkg_name,))
def latest_version(pkg_name, session, silent=False):
try:
info = get_pkg_info(pkg_name, session)
except ValueError:
if silent:
return None
else:
raise
return info['info']['version']
def get_latest_versions(pkg_names):
with requests.session() as session:
pool = multiprocessing.Pool(min(12, len(pkg_names)))
get_latest = partial(latest_version, session=session, silent=True)
versions = pool.map(get_latest, pkg_names)
return zip(pkg_names, versions)
def get_installed_pkgs(editables=False):
for line in subprocess.check_output(['pip', 'freeze']).split('\n'):
if not line:
continue
if line.startswith('-e'):
if editables:
yield line.split('#egg=', 1)[1], None, True
else:
name, version = line.split('==')
yield name, version, False
|
2994466719ce4f096d68a24c2e20fdd9ffc4232d
|
project/api/backends.py
|
project/api/backends.py
|
# Third-Party
from django_filters.rest_framework.backends import DjangoFilterBackend
from dry_rest_permissions.generics import DRYPermissionFiltersBase
class CoalesceFilterBackend(DjangoFilterBackend):
"""Support Ember Data coalesceFindRequests."""
def filter_queryset(self, request, queryset, view):
raw = request.query_params.get('filter[id]')
if raw:
ids = raw.split(',')
view.pagination_class = None
queryset = queryset.filter(id__in=ids)
return queryset
class ScoreFilterBackend(DRYPermissionFiltersBase):
def filter_list_queryset(self, request, queryset, view):
"""Limit all requests to superuser."""
if request.user.is_authenticated():
if request.user.is_staff:
return queryset.all()
# else:
# return queryset.filter(
# song__appearance__entry__entity__officers__person__user=request.user,
# )
return queryset.none()
|
# Third-Party
from django_filters.rest_framework.backends import DjangoFilterBackend
class CoalesceFilterBackend(DjangoFilterBackend):
"""Support Ember Data coalesceFindRequests."""
def filter_queryset(self, request, queryset, view):
raw = request.query_params.get('filter[id]')
if raw:
ids = raw.split(',')
view.pagination_class = None
queryset = queryset.filter(id__in=ids)
return queryset
|
Remove unused score filter backend
|
Remove unused score filter backend
|
Python
|
bsd-2-clause
|
dbinetti/barberscore-django,dbinetti/barberscore-django,dbinetti/barberscore,barberscore/barberscore-api,barberscore/barberscore-api,barberscore/barberscore-api,dbinetti/barberscore,barberscore/barberscore-api
|
# Third-Party
from django_filters.rest_framework.backends import DjangoFilterBackend
from dry_rest_permissions.generics import DRYPermissionFiltersBase
class CoalesceFilterBackend(DjangoFilterBackend):
"""Support Ember Data coalesceFindRequests."""
def filter_queryset(self, request, queryset, view):
raw = request.query_params.get('filter[id]')
if raw:
ids = raw.split(',')
view.pagination_class = None
queryset = queryset.filter(id__in=ids)
return queryset
class ScoreFilterBackend(DRYPermissionFiltersBase):
def filter_list_queryset(self, request, queryset, view):
"""Limit all requests to superuser."""
if request.user.is_authenticated():
if request.user.is_staff:
return queryset.all()
# else:
# return queryset.filter(
# song__appearance__entry__entity__officers__person__user=request.user,
# )
return queryset.none()
Remove unused score filter backend
|
# Third-Party
from django_filters.rest_framework.backends import DjangoFilterBackend
class CoalesceFilterBackend(DjangoFilterBackend):
"""Support Ember Data coalesceFindRequests."""
def filter_queryset(self, request, queryset, view):
raw = request.query_params.get('filter[id]')
if raw:
ids = raw.split(',')
view.pagination_class = None
queryset = queryset.filter(id__in=ids)
return queryset
|
<commit_before>
# Third-Party
from django_filters.rest_framework.backends import DjangoFilterBackend
from dry_rest_permissions.generics import DRYPermissionFiltersBase
class CoalesceFilterBackend(DjangoFilterBackend):
"""Support Ember Data coalesceFindRequests."""
def filter_queryset(self, request, queryset, view):
raw = request.query_params.get('filter[id]')
if raw:
ids = raw.split(',')
view.pagination_class = None
queryset = queryset.filter(id__in=ids)
return queryset
class ScoreFilterBackend(DRYPermissionFiltersBase):
def filter_list_queryset(self, request, queryset, view):
"""Limit all requests to superuser."""
if request.user.is_authenticated():
if request.user.is_staff:
return queryset.all()
# else:
# return queryset.filter(
# song__appearance__entry__entity__officers__person__user=request.user,
# )
return queryset.none()
<commit_msg>Remove unused score filter backend<commit_after>
|
# Third-Party
from django_filters.rest_framework.backends import DjangoFilterBackend
class CoalesceFilterBackend(DjangoFilterBackend):
"""Support Ember Data coalesceFindRequests."""
def filter_queryset(self, request, queryset, view):
raw = request.query_params.get('filter[id]')
if raw:
ids = raw.split(',')
view.pagination_class = None
queryset = queryset.filter(id__in=ids)
return queryset
|
# Third-Party
from django_filters.rest_framework.backends import DjangoFilterBackend
from dry_rest_permissions.generics import DRYPermissionFiltersBase
class CoalesceFilterBackend(DjangoFilterBackend):
"""Support Ember Data coalesceFindRequests."""
def filter_queryset(self, request, queryset, view):
raw = request.query_params.get('filter[id]')
if raw:
ids = raw.split(',')
view.pagination_class = None
queryset = queryset.filter(id__in=ids)
return queryset
class ScoreFilterBackend(DRYPermissionFiltersBase):
def filter_list_queryset(self, request, queryset, view):
"""Limit all requests to superuser."""
if request.user.is_authenticated():
if request.user.is_staff:
return queryset.all()
# else:
# return queryset.filter(
# song__appearance__entry__entity__officers__person__user=request.user,
# )
return queryset.none()
Remove unused score filter backend
# Third-Party
from django_filters.rest_framework.backends import DjangoFilterBackend
class CoalesceFilterBackend(DjangoFilterBackend):
"""Support Ember Data coalesceFindRequests."""
def filter_queryset(self, request, queryset, view):
raw = request.query_params.get('filter[id]')
if raw:
ids = raw.split(',')
view.pagination_class = None
queryset = queryset.filter(id__in=ids)
return queryset
|
<commit_before>
# Third-Party
from django_filters.rest_framework.backends import DjangoFilterBackend
from dry_rest_permissions.generics import DRYPermissionFiltersBase
class CoalesceFilterBackend(DjangoFilterBackend):
"""Support Ember Data coalesceFindRequests."""
def filter_queryset(self, request, queryset, view):
raw = request.query_params.get('filter[id]')
if raw:
ids = raw.split(',')
view.pagination_class = None
queryset = queryset.filter(id__in=ids)
return queryset
class ScoreFilterBackend(DRYPermissionFiltersBase):
def filter_list_queryset(self, request, queryset, view):
"""Limit all requests to superuser."""
if request.user.is_authenticated():
if request.user.is_staff:
return queryset.all()
# else:
# return queryset.filter(
# song__appearance__entry__entity__officers__person__user=request.user,
# )
return queryset.none()
<commit_msg>Remove unused score filter backend<commit_after>
# Third-Party
from django_filters.rest_framework.backends import DjangoFilterBackend
class CoalesceFilterBackend(DjangoFilterBackend):
"""Support Ember Data coalesceFindRequests."""
def filter_queryset(self, request, queryset, view):
raw = request.query_params.get('filter[id]')
if raw:
ids = raw.split(',')
view.pagination_class = None
queryset = queryset.filter(id__in=ids)
return queryset
|
693ce5f8b1344f072e1f116ebf3ad79ffaad42b6
|
fungui.py
|
fungui.py
|
#!/usr/bin/env python
"""
fungui is a software to help measuring the shell of a fungi.
"""
# Import modules
from PyQt4 import QtGui, QtCore
|
#!/usr/bin/env python
"""
fungui is a software to help measuring the shell of a fungi.
"""
# Import modules
from PyQt4 import QtGui, QtCore
import sys
# Global variables
FRAME_WIDTH = 1020
FRAME_HEIGHT = 480
class MainWindow(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
# create stuff
self.wdg = Widget()
self.setCentralWidget(self.wdg)
self.createActions()
self.createMenus()
#self.createStatusBar()
# format the main window
self.resize(FRAME_WIDTH, FRAME_HEIGHT)
self.center()
self.setWindowTitle('Fungui')
# show windows
self.show()
self.wdg.show()
def center(self):
qr = self.frameGeometry()
cp = QtGui.QDesktopWidget().availableGeometry().center()
qr.moveCenter(cp)
self.move(qr.topLeft())
def about(self):
QtGui.QMessageBox.about(self, self.tr("About fungui"),
self.tr("fungui..."))
def createActions(self):
self.exitAct = QtGui.QAction(self.tr("E&xit"), self)
self.exitAct.setShortcut(self.tr("Ctrl+Q"))
self.exitAct.setStatusTip(self.tr("Exit the application"))
self.exitAct.triggered.connect(self.close)
self.aboutAct = QtGui.QAction(self.tr("&About"), self)
self.aboutAct.setStatusTip(self.tr("Show the application's About box"))
self.aboutAct.triggered.connect(self.about)
self.aboutQtAct = QtGui.QAction(self.tr("About &Qt"), self)
self.aboutQtAct.setStatusTip(self.tr("Show the Qt library's About box"))
self.aboutQtAct.triggered.connect(QtGui.qApp.aboutQt)
def createMenus(self):
self.fileMenu = self.menuBar().addMenu(self.tr("&File"))
self.fileMenu.addAction(self.exitAct)
self.helpMenu = self.menuBar().addMenu(self.tr("&Help"))
self.helpMenu.addAction(self.aboutAct)
self.helpMenu.addAction(self.aboutQtAct)
class Widget(QtGui.QWidget):
def __init__(self):
super(Widget, self).__init__()
# set font for tips
QtGui.QToolTip.setFont(QtGui.QFont('SansSerif', 10))
self.create_frame()
def create_frame(self):
"""The frame"""
self.main_frame = QtGui.QWidget()
def main():
app = QtGui.QApplication(sys.argv)
mw = MainWindow()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
|
Create a frame with a menu bar.
|
Create a frame with a menu bar.
The software will have several buttons, but the idea of the menu
bar is to have redundancy on the commands and to inform the user
of the shortcuts.
|
Python
|
bsd-3-clause
|
leouieda/funghi
|
#!/usr/bin/env python
"""
fungui is a software to help measuring the shell of a fungi.
"""
# Import modules
from PyQt4 import QtGui, QtCore
Create a frame with a menu bar.
The software will have several buttons, but the idea of the menu
bar is to have redundancy on the commands and to inform the user
of the shortcuts.
|
#!/usr/bin/env python
"""
fungui is a software to help measuring the shell of a fungi.
"""
# Import modules
from PyQt4 import QtGui, QtCore
import sys
# Global variables
FRAME_WIDTH = 1020
FRAME_HEIGHT = 480
class MainWindow(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
# create stuff
self.wdg = Widget()
self.setCentralWidget(self.wdg)
self.createActions()
self.createMenus()
#self.createStatusBar()
# format the main window
self.resize(FRAME_WIDTH, FRAME_HEIGHT)
self.center()
self.setWindowTitle('Fungui')
# show windows
self.show()
self.wdg.show()
def center(self):
qr = self.frameGeometry()
cp = QtGui.QDesktopWidget().availableGeometry().center()
qr.moveCenter(cp)
self.move(qr.topLeft())
def about(self):
QtGui.QMessageBox.about(self, self.tr("About fungui"),
self.tr("fungui..."))
def createActions(self):
self.exitAct = QtGui.QAction(self.tr("E&xit"), self)
self.exitAct.setShortcut(self.tr("Ctrl+Q"))
self.exitAct.setStatusTip(self.tr("Exit the application"))
self.exitAct.triggered.connect(self.close)
self.aboutAct = QtGui.QAction(self.tr("&About"), self)
self.aboutAct.setStatusTip(self.tr("Show the application's About box"))
self.aboutAct.triggered.connect(self.about)
self.aboutQtAct = QtGui.QAction(self.tr("About &Qt"), self)
self.aboutQtAct.setStatusTip(self.tr("Show the Qt library's About box"))
self.aboutQtAct.triggered.connect(QtGui.qApp.aboutQt)
def createMenus(self):
self.fileMenu = self.menuBar().addMenu(self.tr("&File"))
self.fileMenu.addAction(self.exitAct)
self.helpMenu = self.menuBar().addMenu(self.tr("&Help"))
self.helpMenu.addAction(self.aboutAct)
self.helpMenu.addAction(self.aboutQtAct)
class Widget(QtGui.QWidget):
def __init__(self):
super(Widget, self).__init__()
# set font for tips
QtGui.QToolTip.setFont(QtGui.QFont('SansSerif', 10))
self.create_frame()
def create_frame(self):
"""The frame"""
self.main_frame = QtGui.QWidget()
def main():
app = QtGui.QApplication(sys.argv)
mw = MainWindow()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
|
<commit_before>#!/usr/bin/env python
"""
fungui is a software to help measuring the shell of a fungi.
"""
# Import modules
from PyQt4 import QtGui, QtCore
<commit_msg>Create a frame with a menu bar.
The software will have several buttons, but the idea of the menu
bar is to have redundancy on the commands and to inform the user
of the shortcuts.<commit_after>
|
#!/usr/bin/env python
"""
fungui is a software to help measuring the shell of a fungi.
"""
# Import modules
from PyQt4 import QtGui, QtCore
import sys
# Global variables
FRAME_WIDTH = 1020
FRAME_HEIGHT = 480
class MainWindow(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
# create stuff
self.wdg = Widget()
self.setCentralWidget(self.wdg)
self.createActions()
self.createMenus()
#self.createStatusBar()
# format the main window
self.resize(FRAME_WIDTH, FRAME_HEIGHT)
self.center()
self.setWindowTitle('Fungui')
# show windows
self.show()
self.wdg.show()
def center(self):
qr = self.frameGeometry()
cp = QtGui.QDesktopWidget().availableGeometry().center()
qr.moveCenter(cp)
self.move(qr.topLeft())
def about(self):
QtGui.QMessageBox.about(self, self.tr("About fungui"),
self.tr("fungui..."))
def createActions(self):
self.exitAct = QtGui.QAction(self.tr("E&xit"), self)
self.exitAct.setShortcut(self.tr("Ctrl+Q"))
self.exitAct.setStatusTip(self.tr("Exit the application"))
self.exitAct.triggered.connect(self.close)
self.aboutAct = QtGui.QAction(self.tr("&About"), self)
self.aboutAct.setStatusTip(self.tr("Show the application's About box"))
self.aboutAct.triggered.connect(self.about)
self.aboutQtAct = QtGui.QAction(self.tr("About &Qt"), self)
self.aboutQtAct.setStatusTip(self.tr("Show the Qt library's About box"))
self.aboutQtAct.triggered.connect(QtGui.qApp.aboutQt)
def createMenus(self):
self.fileMenu = self.menuBar().addMenu(self.tr("&File"))
self.fileMenu.addAction(self.exitAct)
self.helpMenu = self.menuBar().addMenu(self.tr("&Help"))
self.helpMenu.addAction(self.aboutAct)
self.helpMenu.addAction(self.aboutQtAct)
class Widget(QtGui.QWidget):
def __init__(self):
super(Widget, self).__init__()
# set font for tips
QtGui.QToolTip.setFont(QtGui.QFont('SansSerif', 10))
self.create_frame()
def create_frame(self):
"""The frame"""
self.main_frame = QtGui.QWidget()
def main():
app = QtGui.QApplication(sys.argv)
mw = MainWindow()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
|
#!/usr/bin/env python
"""
fungui is a software to help measuring the shell of a fungi.
"""
# Import modules
from PyQt4 import QtGui, QtCore
Create a frame with a menu bar.
The software will have several buttons, but the idea of the menu
bar is to have redundancy on the commands and to inform the user
of the shortcuts.#!/usr/bin/env python
"""
fungui is a software to help measuring the shell of a fungi.
"""
# Import modules
from PyQt4 import QtGui, QtCore
import sys
# Global variables
FRAME_WIDTH = 1020
FRAME_HEIGHT = 480
class MainWindow(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
# create stuff
self.wdg = Widget()
self.setCentralWidget(self.wdg)
self.createActions()
self.createMenus()
#self.createStatusBar()
# format the main window
self.resize(FRAME_WIDTH, FRAME_HEIGHT)
self.center()
self.setWindowTitle('Fungui')
# show windows
self.show()
self.wdg.show()
def center(self):
qr = self.frameGeometry()
cp = QtGui.QDesktopWidget().availableGeometry().center()
qr.moveCenter(cp)
self.move(qr.topLeft())
def about(self):
QtGui.QMessageBox.about(self, self.tr("About fungui"),
self.tr("fungui..."))
def createActions(self):
self.exitAct = QtGui.QAction(self.tr("E&xit"), self)
self.exitAct.setShortcut(self.tr("Ctrl+Q"))
self.exitAct.setStatusTip(self.tr("Exit the application"))
self.exitAct.triggered.connect(self.close)
self.aboutAct = QtGui.QAction(self.tr("&About"), self)
self.aboutAct.setStatusTip(self.tr("Show the application's About box"))
self.aboutAct.triggered.connect(self.about)
self.aboutQtAct = QtGui.QAction(self.tr("About &Qt"), self)
self.aboutQtAct.setStatusTip(self.tr("Show the Qt library's About box"))
self.aboutQtAct.triggered.connect(QtGui.qApp.aboutQt)
def createMenus(self):
self.fileMenu = self.menuBar().addMenu(self.tr("&File"))
self.fileMenu.addAction(self.exitAct)
self.helpMenu = self.menuBar().addMenu(self.tr("&Help"))
self.helpMenu.addAction(self.aboutAct)
self.helpMenu.addAction(self.aboutQtAct)
class Widget(QtGui.QWidget):
def __init__(self):
super(Widget, self).__init__()
# set font for tips
QtGui.QToolTip.setFont(QtGui.QFont('SansSerif', 10))
self.create_frame()
def create_frame(self):
"""The frame"""
self.main_frame = QtGui.QWidget()
def main():
app = QtGui.QApplication(sys.argv)
mw = MainWindow()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
|
<commit_before>#!/usr/bin/env python
"""
fungui is a software to help measuring the shell of a fungi.
"""
# Import modules
from PyQt4 import QtGui, QtCore
<commit_msg>Create a frame with a menu bar.
The software will have several buttons, but the idea of the menu
bar is to have redundancy on the commands and to inform the user
of the shortcuts.<commit_after>#!/usr/bin/env python
"""
fungui is a software to help measuring the shell of a fungi.
"""
# Import modules
from PyQt4 import QtGui, QtCore
import sys
# Global variables
FRAME_WIDTH = 1020
FRAME_HEIGHT = 480
class MainWindow(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
# create stuff
self.wdg = Widget()
self.setCentralWidget(self.wdg)
self.createActions()
self.createMenus()
#self.createStatusBar()
# format the main window
self.resize(FRAME_WIDTH, FRAME_HEIGHT)
self.center()
self.setWindowTitle('Fungui')
# show windows
self.show()
self.wdg.show()
def center(self):
qr = self.frameGeometry()
cp = QtGui.QDesktopWidget().availableGeometry().center()
qr.moveCenter(cp)
self.move(qr.topLeft())
def about(self):
QtGui.QMessageBox.about(self, self.tr("About fungui"),
self.tr("fungui..."))
def createActions(self):
self.exitAct = QtGui.QAction(self.tr("E&xit"), self)
self.exitAct.setShortcut(self.tr("Ctrl+Q"))
self.exitAct.setStatusTip(self.tr("Exit the application"))
self.exitAct.triggered.connect(self.close)
self.aboutAct = QtGui.QAction(self.tr("&About"), self)
self.aboutAct.setStatusTip(self.tr("Show the application's About box"))
self.aboutAct.triggered.connect(self.about)
self.aboutQtAct = QtGui.QAction(self.tr("About &Qt"), self)
self.aboutQtAct.setStatusTip(self.tr("Show the Qt library's About box"))
self.aboutQtAct.triggered.connect(QtGui.qApp.aboutQt)
def createMenus(self):
self.fileMenu = self.menuBar().addMenu(self.tr("&File"))
self.fileMenu.addAction(self.exitAct)
self.helpMenu = self.menuBar().addMenu(self.tr("&Help"))
self.helpMenu.addAction(self.aboutAct)
self.helpMenu.addAction(self.aboutQtAct)
class Widget(QtGui.QWidget):
def __init__(self):
super(Widget, self).__init__()
# set font for tips
QtGui.QToolTip.setFont(QtGui.QFont('SansSerif', 10))
self.create_frame()
def create_frame(self):
"""The frame"""
self.main_frame = QtGui.QWidget()
def main():
app = QtGui.QApplication(sys.argv)
mw = MainWindow()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
|
38ceb6d04f7b09b3ab29468c2fa9ccc94e1b5dc5
|
casepro/pods/views.py
|
casepro/pods/views.py
|
from __future__ import unicode_literals
import json
from django.http import JsonResponse
from casepro.pods import registry
def read_pod_data(request, index):
"""Delegates to the `read_data` function of the correct pod."""
if request.method != 'GET':
return JsonResponse({'reason': 'Method not allowed'}, status=405)
try:
pod = registry.pods[int(index)]
except IndexError:
return JsonResponse({'reason': 'Pod does not exist'}, status=404)
return JsonResponse(pod.read_data(request.GET))
def perform_pod_action(request, index):
"""Deletegates to the `perform_action` function of the correct pod."""
if request.method != 'POST':
return JsonResponse({'reason': 'Method not allowed'}, status=405)
try:
pod = registry.pods[int(index)]
except IndexError:
return JsonResponse({'reason': 'Pod does not exist'}, status=404)
try:
data = json.loads(request.body)
except ValueError as e:
return JsonResponse({'reason': 'JSON decode error', 'details': e.message}, status=400)
return JsonResponse(pod.perform_action(data))
|
from __future__ import unicode_literals
import json
from django.http import JsonResponse
from casepro.cases.models import Case, CaseAction
from casepro.pods import registry
def read_pod_data(request, index):
"""Delegates to the `read_data` function of the correct pod."""
if request.method != 'GET':
return JsonResponse({'reason': 'Method not allowed'}, status=405)
try:
pod = registry.pods[int(index)]
except IndexError:
return JsonResponse({'reason': 'Pod does not exist'}, status=404)
return JsonResponse(pod.read_data(request.GET))
def perform_pod_action(request, index):
"""Deletegates to the `perform_action` function of the correct pod."""
if request.method != 'POST':
return JsonResponse({'reason': 'Method not allowed'}, status=405)
try:
pod = registry.pods[int(index)]
except IndexError:
return JsonResponse({'reason': 'Pod does not exist'}, status=404)
try:
data = json.loads(request.body)
except ValueError as e:
return JsonResponse({'reason': 'JSON decode error', 'details': e.message}, status=400)
case_id = data.get('case_id')
if case_id is None:
return JsonResponse(
{'reason': 'Request object needs to have a "case_id" field'}, status=400)
action_data = data.get('action', {})
success, payload = pod.perform_action(action_data.get('type'), action_data.get('payload', {}))
if success is True:
case = Case.objects.get(id=case_id)
CaseAction.create(case, request.user, CaseAction.ADD_NOTE, note=payload.get('message'))
return JsonResponse(pod.perform_action(data))
|
Change case field to case_id in error message
|
Change case field to case_id in error message
|
Python
|
bsd-3-clause
|
xkmato/casepro,praekelt/casepro,rapidpro/casepro,rapidpro/casepro,rapidpro/casepro,praekelt/casepro,xkmato/casepro,praekelt/casepro
|
from __future__ import unicode_literals
import json
from django.http import JsonResponse
from casepro.pods import registry
def read_pod_data(request, index):
"""Delegates to the `read_data` function of the correct pod."""
if request.method != 'GET':
return JsonResponse({'reason': 'Method not allowed'}, status=405)
try:
pod = registry.pods[int(index)]
except IndexError:
return JsonResponse({'reason': 'Pod does not exist'}, status=404)
return JsonResponse(pod.read_data(request.GET))
def perform_pod_action(request, index):
"""Deletegates to the `perform_action` function of the correct pod."""
if request.method != 'POST':
return JsonResponse({'reason': 'Method not allowed'}, status=405)
try:
pod = registry.pods[int(index)]
except IndexError:
return JsonResponse({'reason': 'Pod does not exist'}, status=404)
try:
data = json.loads(request.body)
except ValueError as e:
return JsonResponse({'reason': 'JSON decode error', 'details': e.message}, status=400)
return JsonResponse(pod.perform_action(data))
Change case field to case_id in error message
|
from __future__ import unicode_literals
import json
from django.http import JsonResponse
from casepro.cases.models import Case, CaseAction
from casepro.pods import registry
def read_pod_data(request, index):
"""Delegates to the `read_data` function of the correct pod."""
if request.method != 'GET':
return JsonResponse({'reason': 'Method not allowed'}, status=405)
try:
pod = registry.pods[int(index)]
except IndexError:
return JsonResponse({'reason': 'Pod does not exist'}, status=404)
return JsonResponse(pod.read_data(request.GET))
def perform_pod_action(request, index):
"""Deletegates to the `perform_action` function of the correct pod."""
if request.method != 'POST':
return JsonResponse({'reason': 'Method not allowed'}, status=405)
try:
pod = registry.pods[int(index)]
except IndexError:
return JsonResponse({'reason': 'Pod does not exist'}, status=404)
try:
data = json.loads(request.body)
except ValueError as e:
return JsonResponse({'reason': 'JSON decode error', 'details': e.message}, status=400)
case_id = data.get('case_id')
if case_id is None:
return JsonResponse(
{'reason': 'Request object needs to have a "case_id" field'}, status=400)
action_data = data.get('action', {})
success, payload = pod.perform_action(action_data.get('type'), action_data.get('payload', {}))
if success is True:
case = Case.objects.get(id=case_id)
CaseAction.create(case, request.user, CaseAction.ADD_NOTE, note=payload.get('message'))
return JsonResponse(pod.perform_action(data))
|
<commit_before>from __future__ import unicode_literals
import json
from django.http import JsonResponse
from casepro.pods import registry
def read_pod_data(request, index):
"""Delegates to the `read_data` function of the correct pod."""
if request.method != 'GET':
return JsonResponse({'reason': 'Method not allowed'}, status=405)
try:
pod = registry.pods[int(index)]
except IndexError:
return JsonResponse({'reason': 'Pod does not exist'}, status=404)
return JsonResponse(pod.read_data(request.GET))
def perform_pod_action(request, index):
"""Deletegates to the `perform_action` function of the correct pod."""
if request.method != 'POST':
return JsonResponse({'reason': 'Method not allowed'}, status=405)
try:
pod = registry.pods[int(index)]
except IndexError:
return JsonResponse({'reason': 'Pod does not exist'}, status=404)
try:
data = json.loads(request.body)
except ValueError as e:
return JsonResponse({'reason': 'JSON decode error', 'details': e.message}, status=400)
return JsonResponse(pod.perform_action(data))
<commit_msg>Change case field to case_id in error message<commit_after>
|
from __future__ import unicode_literals
import json
from django.http import JsonResponse
from casepro.cases.models import Case, CaseAction
from casepro.pods import registry
def read_pod_data(request, index):
"""Delegates to the `read_data` function of the correct pod."""
if request.method != 'GET':
return JsonResponse({'reason': 'Method not allowed'}, status=405)
try:
pod = registry.pods[int(index)]
except IndexError:
return JsonResponse({'reason': 'Pod does not exist'}, status=404)
return JsonResponse(pod.read_data(request.GET))
def perform_pod_action(request, index):
"""Deletegates to the `perform_action` function of the correct pod."""
if request.method != 'POST':
return JsonResponse({'reason': 'Method not allowed'}, status=405)
try:
pod = registry.pods[int(index)]
except IndexError:
return JsonResponse({'reason': 'Pod does not exist'}, status=404)
try:
data = json.loads(request.body)
except ValueError as e:
return JsonResponse({'reason': 'JSON decode error', 'details': e.message}, status=400)
case_id = data.get('case_id')
if case_id is None:
return JsonResponse(
{'reason': 'Request object needs to have a "case_id" field'}, status=400)
action_data = data.get('action', {})
success, payload = pod.perform_action(action_data.get('type'), action_data.get('payload', {}))
if success is True:
case = Case.objects.get(id=case_id)
CaseAction.create(case, request.user, CaseAction.ADD_NOTE, note=payload.get('message'))
return JsonResponse(pod.perform_action(data))
|
from __future__ import unicode_literals
import json
from django.http import JsonResponse
from casepro.pods import registry
def read_pod_data(request, index):
"""Delegates to the `read_data` function of the correct pod."""
if request.method != 'GET':
return JsonResponse({'reason': 'Method not allowed'}, status=405)
try:
pod = registry.pods[int(index)]
except IndexError:
return JsonResponse({'reason': 'Pod does not exist'}, status=404)
return JsonResponse(pod.read_data(request.GET))
def perform_pod_action(request, index):
"""Deletegates to the `perform_action` function of the correct pod."""
if request.method != 'POST':
return JsonResponse({'reason': 'Method not allowed'}, status=405)
try:
pod = registry.pods[int(index)]
except IndexError:
return JsonResponse({'reason': 'Pod does not exist'}, status=404)
try:
data = json.loads(request.body)
except ValueError as e:
return JsonResponse({'reason': 'JSON decode error', 'details': e.message}, status=400)
return JsonResponse(pod.perform_action(data))
Change case field to case_id in error messagefrom __future__ import unicode_literals
import json
from django.http import JsonResponse
from casepro.cases.models import Case, CaseAction
from casepro.pods import registry
def read_pod_data(request, index):
"""Delegates to the `read_data` function of the correct pod."""
if request.method != 'GET':
return JsonResponse({'reason': 'Method not allowed'}, status=405)
try:
pod = registry.pods[int(index)]
except IndexError:
return JsonResponse({'reason': 'Pod does not exist'}, status=404)
return JsonResponse(pod.read_data(request.GET))
def perform_pod_action(request, index):
"""Deletegates to the `perform_action` function of the correct pod."""
if request.method != 'POST':
return JsonResponse({'reason': 'Method not allowed'}, status=405)
try:
pod = registry.pods[int(index)]
except IndexError:
return JsonResponse({'reason': 'Pod does not exist'}, status=404)
try:
data = json.loads(request.body)
except ValueError as e:
return JsonResponse({'reason': 'JSON decode error', 'details': e.message}, status=400)
case_id = data.get('case_id')
if case_id is None:
return JsonResponse(
{'reason': 'Request object needs to have a "case_id" field'}, status=400)
action_data = data.get('action', {})
success, payload = pod.perform_action(action_data.get('type'), action_data.get('payload', {}))
if success is True:
case = Case.objects.get(id=case_id)
CaseAction.create(case, request.user, CaseAction.ADD_NOTE, note=payload.get('message'))
return JsonResponse(pod.perform_action(data))
|
<commit_before>from __future__ import unicode_literals
import json
from django.http import JsonResponse
from casepro.pods import registry
def read_pod_data(request, index):
"""Delegates to the `read_data` function of the correct pod."""
if request.method != 'GET':
return JsonResponse({'reason': 'Method not allowed'}, status=405)
try:
pod = registry.pods[int(index)]
except IndexError:
return JsonResponse({'reason': 'Pod does not exist'}, status=404)
return JsonResponse(pod.read_data(request.GET))
def perform_pod_action(request, index):
"""Deletegates to the `perform_action` function of the correct pod."""
if request.method != 'POST':
return JsonResponse({'reason': 'Method not allowed'}, status=405)
try:
pod = registry.pods[int(index)]
except IndexError:
return JsonResponse({'reason': 'Pod does not exist'}, status=404)
try:
data = json.loads(request.body)
except ValueError as e:
return JsonResponse({'reason': 'JSON decode error', 'details': e.message}, status=400)
return JsonResponse(pod.perform_action(data))
<commit_msg>Change case field to case_id in error message<commit_after>from __future__ import unicode_literals
import json
from django.http import JsonResponse
from casepro.cases.models import Case, CaseAction
from casepro.pods import registry
def read_pod_data(request, index):
"""Delegates to the `read_data` function of the correct pod."""
if request.method != 'GET':
return JsonResponse({'reason': 'Method not allowed'}, status=405)
try:
pod = registry.pods[int(index)]
except IndexError:
return JsonResponse({'reason': 'Pod does not exist'}, status=404)
return JsonResponse(pod.read_data(request.GET))
def perform_pod_action(request, index):
"""Deletegates to the `perform_action` function of the correct pod."""
if request.method != 'POST':
return JsonResponse({'reason': 'Method not allowed'}, status=405)
try:
pod = registry.pods[int(index)]
except IndexError:
return JsonResponse({'reason': 'Pod does not exist'}, status=404)
try:
data = json.loads(request.body)
except ValueError as e:
return JsonResponse({'reason': 'JSON decode error', 'details': e.message}, status=400)
case_id = data.get('case_id')
if case_id is None:
return JsonResponse(
{'reason': 'Request object needs to have a "case_id" field'}, status=400)
action_data = data.get('action', {})
success, payload = pod.perform_action(action_data.get('type'), action_data.get('payload', {}))
if success is True:
case = Case.objects.get(id=case_id)
CaseAction.create(case, request.user, CaseAction.ADD_NOTE, note=payload.get('message'))
return JsonResponse(pod.perform_action(data))
|
d3fc9414effb4c49104cc4a0888872d9eb4c20a9
|
py/garage/garage/sql/utils.py
|
py/garage/garage/sql/utils.py
|
__all__ = [
'ensure_only_one_row',
'insert_or_ignore',
]
def ensure_only_one_row(rows):
row = rows.fetchone()
if row is None or rows.fetchone() is not None:
raise KeyError
return row
def insert_or_ignore(conn, table, values):
conn.execute(table.insert().prefix_with('OR IGNORE'), values)
|
__all__ = [
'add_if_not_exists_clause',
'ensure_only_one_row',
'insert_or_ignore',
]
from garage import asserts
from sqlalchemy.schema import CreateIndex
def add_if_not_exists_clause(index, engine):
# `sqlalchemy.Index.create()` does not take `checkfirst` for reasons
# that I am unaware of, and here is a hack for sidestep that.
stmt = str(CreateIndex(index).compile(engine))
stmt = stmt.replace('CREATE INDEX', 'CREATE INDEX IF NOT EXISTS', 1)
asserts.postcond('IF NOT EXISTS' in stmt, stmt)
return stmt
def ensure_only_one_row(rows):
row = rows.fetchone()
if row is None or rows.fetchone() is not None:
raise KeyError
return row
def insert_or_ignore(conn, table, values):
conn.execute(table.insert().prefix_with('OR IGNORE'), values)
|
Add a hack for appending "IF NOT EXISTS" clause to "CREATE INDEX"
|
Add a hack for appending "IF NOT EXISTS" clause to "CREATE INDEX"
|
Python
|
mit
|
clchiou/garage,clchiou/garage,clchiou/garage,clchiou/garage
|
__all__ = [
'ensure_only_one_row',
'insert_or_ignore',
]
def ensure_only_one_row(rows):
row = rows.fetchone()
if row is None or rows.fetchone() is not None:
raise KeyError
return row
def insert_or_ignore(conn, table, values):
conn.execute(table.insert().prefix_with('OR IGNORE'), values)
Add a hack for appending "IF NOT EXISTS" clause to "CREATE INDEX"
|
__all__ = [
'add_if_not_exists_clause',
'ensure_only_one_row',
'insert_or_ignore',
]
from garage import asserts
from sqlalchemy.schema import CreateIndex
def add_if_not_exists_clause(index, engine):
# `sqlalchemy.Index.create()` does not take `checkfirst` for reasons
# that I am unaware of, and here is a hack for sidestep that.
stmt = str(CreateIndex(index).compile(engine))
stmt = stmt.replace('CREATE INDEX', 'CREATE INDEX IF NOT EXISTS', 1)
asserts.postcond('IF NOT EXISTS' in stmt, stmt)
return stmt
def ensure_only_one_row(rows):
row = rows.fetchone()
if row is None or rows.fetchone() is not None:
raise KeyError
return row
def insert_or_ignore(conn, table, values):
conn.execute(table.insert().prefix_with('OR IGNORE'), values)
|
<commit_before>__all__ = [
'ensure_only_one_row',
'insert_or_ignore',
]
def ensure_only_one_row(rows):
row = rows.fetchone()
if row is None or rows.fetchone() is not None:
raise KeyError
return row
def insert_or_ignore(conn, table, values):
conn.execute(table.insert().prefix_with('OR IGNORE'), values)
<commit_msg>Add a hack for appending "IF NOT EXISTS" clause to "CREATE INDEX"<commit_after>
|
__all__ = [
'add_if_not_exists_clause',
'ensure_only_one_row',
'insert_or_ignore',
]
from garage import asserts
from sqlalchemy.schema import CreateIndex
def add_if_not_exists_clause(index, engine):
# `sqlalchemy.Index.create()` does not take `checkfirst` for reasons
# that I am unaware of, and here is a hack for sidestep that.
stmt = str(CreateIndex(index).compile(engine))
stmt = stmt.replace('CREATE INDEX', 'CREATE INDEX IF NOT EXISTS', 1)
asserts.postcond('IF NOT EXISTS' in stmt, stmt)
return stmt
def ensure_only_one_row(rows):
row = rows.fetchone()
if row is None or rows.fetchone() is not None:
raise KeyError
return row
def insert_or_ignore(conn, table, values):
conn.execute(table.insert().prefix_with('OR IGNORE'), values)
|
__all__ = [
'ensure_only_one_row',
'insert_or_ignore',
]
def ensure_only_one_row(rows):
row = rows.fetchone()
if row is None or rows.fetchone() is not None:
raise KeyError
return row
def insert_or_ignore(conn, table, values):
conn.execute(table.insert().prefix_with('OR IGNORE'), values)
Add a hack for appending "IF NOT EXISTS" clause to "CREATE INDEX"__all__ = [
'add_if_not_exists_clause',
'ensure_only_one_row',
'insert_or_ignore',
]
from garage import asserts
from sqlalchemy.schema import CreateIndex
def add_if_not_exists_clause(index, engine):
# `sqlalchemy.Index.create()` does not take `checkfirst` for reasons
# that I am unaware of, and here is a hack for sidestep that.
stmt = str(CreateIndex(index).compile(engine))
stmt = stmt.replace('CREATE INDEX', 'CREATE INDEX IF NOT EXISTS', 1)
asserts.postcond('IF NOT EXISTS' in stmt, stmt)
return stmt
def ensure_only_one_row(rows):
row = rows.fetchone()
if row is None or rows.fetchone() is not None:
raise KeyError
return row
def insert_or_ignore(conn, table, values):
conn.execute(table.insert().prefix_with('OR IGNORE'), values)
|
<commit_before>__all__ = [
'ensure_only_one_row',
'insert_or_ignore',
]
def ensure_only_one_row(rows):
row = rows.fetchone()
if row is None or rows.fetchone() is not None:
raise KeyError
return row
def insert_or_ignore(conn, table, values):
conn.execute(table.insert().prefix_with('OR IGNORE'), values)
<commit_msg>Add a hack for appending "IF NOT EXISTS" clause to "CREATE INDEX"<commit_after>__all__ = [
'add_if_not_exists_clause',
'ensure_only_one_row',
'insert_or_ignore',
]
from garage import asserts
from sqlalchemy.schema import CreateIndex
def add_if_not_exists_clause(index, engine):
# `sqlalchemy.Index.create()` does not take `checkfirst` for reasons
# that I am unaware of, and here is a hack for sidestep that.
stmt = str(CreateIndex(index).compile(engine))
stmt = stmt.replace('CREATE INDEX', 'CREATE INDEX IF NOT EXISTS', 1)
asserts.postcond('IF NOT EXISTS' in stmt, stmt)
return stmt
def ensure_only_one_row(rows):
row = rows.fetchone()
if row is None or rows.fetchone() is not None:
raise KeyError
return row
def insert_or_ignore(conn, table, values):
conn.execute(table.insert().prefix_with('OR IGNORE'), values)
|
04b785a9761e4d49c3f0e3dfc5d3df06cd3209a1
|
coffer/utils/ccopy.py
|
coffer/utils/ccopy.py
|
import os
import shutil
def copy(orig, dest, useShutil=False):
if os.path.isdir(orig):
if useShutil:
shutil.copytree(orig, dest, symlinks=True)
else:
os.popen("cp -rf {} {}".format(orig, dest))
else:
if useShutil:
shutil.copy(orig, dest)
else:
os.popen("cp {} {}".format(orig, dest))
|
import os
import shutil
def copy(orig, dest, useShutil=False):
if os.path.isdir(orig):
if useShutil:
shutil.copytree(orig, dest, symlinks=True)
else:
os.system("cp -rf {} {}".format(orig, dest))
else:
if useShutil:
shutil.copy(orig, dest)
else:
os.system("cp {} {}".format(orig, dest))
|
Copy now waits for files to be copies over
|
Copy now waits for files to be copies over
|
Python
|
mit
|
Max00355/Coffer
|
import os
import shutil
def copy(orig, dest, useShutil=False):
if os.path.isdir(orig):
if useShutil:
shutil.copytree(orig, dest, symlinks=True)
else:
os.popen("cp -rf {} {}".format(orig, dest))
else:
if useShutil:
shutil.copy(orig, dest)
else:
os.popen("cp {} {}".format(orig, dest))
Copy now waits for files to be copies over
|
import os
import shutil
def copy(orig, dest, useShutil=False):
if os.path.isdir(orig):
if useShutil:
shutil.copytree(orig, dest, symlinks=True)
else:
os.system("cp -rf {} {}".format(orig, dest))
else:
if useShutil:
shutil.copy(orig, dest)
else:
os.system("cp {} {}".format(orig, dest))
|
<commit_before>import os
import shutil
def copy(orig, dest, useShutil=False):
if os.path.isdir(orig):
if useShutil:
shutil.copytree(orig, dest, symlinks=True)
else:
os.popen("cp -rf {} {}".format(orig, dest))
else:
if useShutil:
shutil.copy(orig, dest)
else:
os.popen("cp {} {}".format(orig, dest))
<commit_msg>Copy now waits for files to be copies over<commit_after>
|
import os
import shutil
def copy(orig, dest, useShutil=False):
if os.path.isdir(orig):
if useShutil:
shutil.copytree(orig, dest, symlinks=True)
else:
os.system("cp -rf {} {}".format(orig, dest))
else:
if useShutil:
shutil.copy(orig, dest)
else:
os.system("cp {} {}".format(orig, dest))
|
import os
import shutil
def copy(orig, dest, useShutil=False):
if os.path.isdir(orig):
if useShutil:
shutil.copytree(orig, dest, symlinks=True)
else:
os.popen("cp -rf {} {}".format(orig, dest))
else:
if useShutil:
shutil.copy(orig, dest)
else:
os.popen("cp {} {}".format(orig, dest))
Copy now waits for files to be copies overimport os
import shutil
def copy(orig, dest, useShutil=False):
if os.path.isdir(orig):
if useShutil:
shutil.copytree(orig, dest, symlinks=True)
else:
os.system("cp -rf {} {}".format(orig, dest))
else:
if useShutil:
shutil.copy(orig, dest)
else:
os.system("cp {} {}".format(orig, dest))
|
<commit_before>import os
import shutil
def copy(orig, dest, useShutil=False):
if os.path.isdir(orig):
if useShutil:
shutil.copytree(orig, dest, symlinks=True)
else:
os.popen("cp -rf {} {}".format(orig, dest))
else:
if useShutil:
shutil.copy(orig, dest)
else:
os.popen("cp {} {}".format(orig, dest))
<commit_msg>Copy now waits for files to be copies over<commit_after>import os
import shutil
def copy(orig, dest, useShutil=False):
if os.path.isdir(orig):
if useShutil:
shutil.copytree(orig, dest, symlinks=True)
else:
os.system("cp -rf {} {}".format(orig, dest))
else:
if useShutil:
shutil.copy(orig, dest)
else:
os.system("cp {} {}".format(orig, dest))
|
0434baddfc2eb3691180e6fa461be3323852eea9
|
clubadm/middleware.py
|
clubadm/middleware.py
|
from django.http import Http404
from django.utils import timezone
from clubadm.models import Member, Season
class SeasonMiddleware(object):
def process_view(self, request, view_func, view_args, view_kwargs):
if "year" in view_kwargs:
year = int(view_kwargs["year"])
try:
request.season = Season.objects.get_by_year(year)
except Season.DoesNotExist:
raise Http404("Такой сезон еще не создан")
class MemberMiddleware(object):
def process_view(self, request, view_func, view_args, view_kwargs):
if "year" in view_kwargs and request.user.is_authenticated:
year = int(view_kwargs["year"])
try:
request.member = Member.objects.get_by_user_and_year(
request.user, year)
except Member.DoesNotExist:
request.member = None
class XUserMiddleware(object):
def process_response(self, request, response):
if request.user.is_anonymous:
return response
# Чтобы Nginx мог писать имя пользователя в логи
response["X-User"] = request.user.username
return response
|
from django.http import Http404
from django.utils import timezone
from clubadm.models import Member, Season
class SeasonMiddleware(object):
def process_view(self, request, view_func, view_args, view_kwargs):
if "year" in view_kwargs:
year = int(view_kwargs["year"])
try:
request.season = Season.objects.get_by_year(year)
except Season.DoesNotExist:
raise Http404("Такой сезон еще не создан")
class MemberMiddleware(object):
def process_view(self, request, view_func, view_args, view_kwargs):
if "year" in view_kwargs and request.user.is_authenticated:
year = int(view_kwargs["year"])
try:
request.member = Member.objects.get_by_user_and_year(
request.user, year)
except Member.DoesNotExist:
request.member = None
class XUserMiddleware(object):
def process_response(self, request, response):
if not hasattr(request, "user"):
return response
if request.user.is_anonymous:
return response
# Чтобы Nginx мог писать имя пользователя в логи
response["X-User"] = request.user.username
return response
|
Handle an authentication edge case
|
Handle an authentication edge case
|
Python
|
mit
|
clubadm/clubadm,clubadm/clubadm,clubadm/clubadm
|
from django.http import Http404
from django.utils import timezone
from clubadm.models import Member, Season
class SeasonMiddleware(object):
def process_view(self, request, view_func, view_args, view_kwargs):
if "year" in view_kwargs:
year = int(view_kwargs["year"])
try:
request.season = Season.objects.get_by_year(year)
except Season.DoesNotExist:
raise Http404("Такой сезон еще не создан")
class MemberMiddleware(object):
def process_view(self, request, view_func, view_args, view_kwargs):
if "year" in view_kwargs and request.user.is_authenticated:
year = int(view_kwargs["year"])
try:
request.member = Member.objects.get_by_user_and_year(
request.user, year)
except Member.DoesNotExist:
request.member = None
class XUserMiddleware(object):
def process_response(self, request, response):
if request.user.is_anonymous:
return response
# Чтобы Nginx мог писать имя пользователя в логи
response["X-User"] = request.user.username
return response
Handle an authentication edge case
|
from django.http import Http404
from django.utils import timezone
from clubadm.models import Member, Season
class SeasonMiddleware(object):
def process_view(self, request, view_func, view_args, view_kwargs):
if "year" in view_kwargs:
year = int(view_kwargs["year"])
try:
request.season = Season.objects.get_by_year(year)
except Season.DoesNotExist:
raise Http404("Такой сезон еще не создан")
class MemberMiddleware(object):
def process_view(self, request, view_func, view_args, view_kwargs):
if "year" in view_kwargs and request.user.is_authenticated:
year = int(view_kwargs["year"])
try:
request.member = Member.objects.get_by_user_and_year(
request.user, year)
except Member.DoesNotExist:
request.member = None
class XUserMiddleware(object):
def process_response(self, request, response):
if not hasattr(request, "user"):
return response
if request.user.is_anonymous:
return response
# Чтобы Nginx мог писать имя пользователя в логи
response["X-User"] = request.user.username
return response
|
<commit_before>from django.http import Http404
from django.utils import timezone
from clubadm.models import Member, Season
class SeasonMiddleware(object):
def process_view(self, request, view_func, view_args, view_kwargs):
if "year" in view_kwargs:
year = int(view_kwargs["year"])
try:
request.season = Season.objects.get_by_year(year)
except Season.DoesNotExist:
raise Http404("Такой сезон еще не создан")
class MemberMiddleware(object):
def process_view(self, request, view_func, view_args, view_kwargs):
if "year" in view_kwargs and request.user.is_authenticated:
year = int(view_kwargs["year"])
try:
request.member = Member.objects.get_by_user_and_year(
request.user, year)
except Member.DoesNotExist:
request.member = None
class XUserMiddleware(object):
def process_response(self, request, response):
if request.user.is_anonymous:
return response
# Чтобы Nginx мог писать имя пользователя в логи
response["X-User"] = request.user.username
return response
<commit_msg>Handle an authentication edge case<commit_after>
|
from django.http import Http404
from django.utils import timezone
from clubadm.models import Member, Season
class SeasonMiddleware(object):
def process_view(self, request, view_func, view_args, view_kwargs):
if "year" in view_kwargs:
year = int(view_kwargs["year"])
try:
request.season = Season.objects.get_by_year(year)
except Season.DoesNotExist:
raise Http404("Такой сезон еще не создан")
class MemberMiddleware(object):
def process_view(self, request, view_func, view_args, view_kwargs):
if "year" in view_kwargs and request.user.is_authenticated:
year = int(view_kwargs["year"])
try:
request.member = Member.objects.get_by_user_and_year(
request.user, year)
except Member.DoesNotExist:
request.member = None
class XUserMiddleware(object):
def process_response(self, request, response):
if not hasattr(request, "user"):
return response
if request.user.is_anonymous:
return response
# Чтобы Nginx мог писать имя пользователя в логи
response["X-User"] = request.user.username
return response
|
from django.http import Http404
from django.utils import timezone
from clubadm.models import Member, Season
class SeasonMiddleware(object):
def process_view(self, request, view_func, view_args, view_kwargs):
if "year" in view_kwargs:
year = int(view_kwargs["year"])
try:
request.season = Season.objects.get_by_year(year)
except Season.DoesNotExist:
raise Http404("Такой сезон еще не создан")
class MemberMiddleware(object):
def process_view(self, request, view_func, view_args, view_kwargs):
if "year" in view_kwargs and request.user.is_authenticated:
year = int(view_kwargs["year"])
try:
request.member = Member.objects.get_by_user_and_year(
request.user, year)
except Member.DoesNotExist:
request.member = None
class XUserMiddleware(object):
def process_response(self, request, response):
if request.user.is_anonymous:
return response
# Чтобы Nginx мог писать имя пользователя в логи
response["X-User"] = request.user.username
return response
Handle an authentication edge casefrom django.http import Http404
from django.utils import timezone
from clubadm.models import Member, Season
class SeasonMiddleware(object):
def process_view(self, request, view_func, view_args, view_kwargs):
if "year" in view_kwargs:
year = int(view_kwargs["year"])
try:
request.season = Season.objects.get_by_year(year)
except Season.DoesNotExist:
raise Http404("Такой сезон еще не создан")
class MemberMiddleware(object):
def process_view(self, request, view_func, view_args, view_kwargs):
if "year" in view_kwargs and request.user.is_authenticated:
year = int(view_kwargs["year"])
try:
request.member = Member.objects.get_by_user_and_year(
request.user, year)
except Member.DoesNotExist:
request.member = None
class XUserMiddleware(object):
def process_response(self, request, response):
if not hasattr(request, "user"):
return response
if request.user.is_anonymous:
return response
# Чтобы Nginx мог писать имя пользователя в логи
response["X-User"] = request.user.username
return response
|
<commit_before>from django.http import Http404
from django.utils import timezone
from clubadm.models import Member, Season
class SeasonMiddleware(object):
def process_view(self, request, view_func, view_args, view_kwargs):
if "year" in view_kwargs:
year = int(view_kwargs["year"])
try:
request.season = Season.objects.get_by_year(year)
except Season.DoesNotExist:
raise Http404("Такой сезон еще не создан")
class MemberMiddleware(object):
def process_view(self, request, view_func, view_args, view_kwargs):
if "year" in view_kwargs and request.user.is_authenticated:
year = int(view_kwargs["year"])
try:
request.member = Member.objects.get_by_user_and_year(
request.user, year)
except Member.DoesNotExist:
request.member = None
class XUserMiddleware(object):
def process_response(self, request, response):
if request.user.is_anonymous:
return response
# Чтобы Nginx мог писать имя пользователя в логи
response["X-User"] = request.user.username
return response
<commit_msg>Handle an authentication edge case<commit_after>from django.http import Http404
from django.utils import timezone
from clubadm.models import Member, Season
class SeasonMiddleware(object):
def process_view(self, request, view_func, view_args, view_kwargs):
if "year" in view_kwargs:
year = int(view_kwargs["year"])
try:
request.season = Season.objects.get_by_year(year)
except Season.DoesNotExist:
raise Http404("Такой сезон еще не создан")
class MemberMiddleware(object):
def process_view(self, request, view_func, view_args, view_kwargs):
if "year" in view_kwargs and request.user.is_authenticated:
year = int(view_kwargs["year"])
try:
request.member = Member.objects.get_by_user_and_year(
request.user, year)
except Member.DoesNotExist:
request.member = None
class XUserMiddleware(object):
def process_response(self, request, response):
if not hasattr(request, "user"):
return response
if request.user.is_anonymous:
return response
# Чтобы Nginx мог писать имя пользователя в логи
response["X-User"] = request.user.username
return response
|
d6bec06d22eb8337ed22a536389c6f4ca794106a
|
py/templates.py
|
py/templates.py
|
import os.path
import jinja2
import configmanager
configs = configmanager.ConfigManager(os.path.abspath(os.path.join(os.path.dirname(__file__), "../configs")))
templateConfig = configs["templates"]
templatePath = os.path.abspath(os.path.join(os.path.dirname(__file__), "../", templateConfig["template_directory"]))
class TemplateManager():
def __init__(self):
self.environment = jinja2.Environment(loader = jinja2.FileSystemLoader(templatePath))
def __getitem__(self, attr):
try:
return self.environment.get_template(attr)
except jinja2.TemplateNotFound:
try:
return self.environment.get_template(attr+".html")
except jinja2.TemplateNotFound:
return None
|
import os.path
import jinja2
import configmanager
configs = configmanager.ConfigManager(os.path.abspath(os.path.join(os.path.dirname(__file__), "../configs")))
templateConfig = configs["templates"]
templatePath = os.path.abspath(os.path.join(os.path.dirname(__file__), "../", templateConfig["template_directory"]))
class TemplateManager():
def __init__(self, path = templatePath):
self.environment = jinja2.Environment(loader = jinja2.FileSystemLoader(path))
def __getitem__(self, attr):
try:
return self.environment.get_template(attr)
except jinja2.TemplateNotFound:
try:
return self.environment.get_template(attr+".html")
except jinja2.TemplateNotFound:
return None
|
Add paramater for template path
|
Add paramater for template path
|
Python
|
mit
|
ollien/Timpani,ollien/Timpani,ollien/Timpani
|
import os.path
import jinja2
import configmanager
configs = configmanager.ConfigManager(os.path.abspath(os.path.join(os.path.dirname(__file__), "../configs")))
templateConfig = configs["templates"]
templatePath = os.path.abspath(os.path.join(os.path.dirname(__file__), "../", templateConfig["template_directory"]))
class TemplateManager():
def __init__(self):
self.environment = jinja2.Environment(loader = jinja2.FileSystemLoader(templatePath))
def __getitem__(self, attr):
try:
return self.environment.get_template(attr)
except jinja2.TemplateNotFound:
try:
return self.environment.get_template(attr+".html")
except jinja2.TemplateNotFound:
return None
Add paramater for template path
|
import os.path
import jinja2
import configmanager
configs = configmanager.ConfigManager(os.path.abspath(os.path.join(os.path.dirname(__file__), "../configs")))
templateConfig = configs["templates"]
templatePath = os.path.abspath(os.path.join(os.path.dirname(__file__), "../", templateConfig["template_directory"]))
class TemplateManager():
def __init__(self, path = templatePath):
self.environment = jinja2.Environment(loader = jinja2.FileSystemLoader(path))
def __getitem__(self, attr):
try:
return self.environment.get_template(attr)
except jinja2.TemplateNotFound:
try:
return self.environment.get_template(attr+".html")
except jinja2.TemplateNotFound:
return None
|
<commit_before>import os.path
import jinja2
import configmanager
configs = configmanager.ConfigManager(os.path.abspath(os.path.join(os.path.dirname(__file__), "../configs")))
templateConfig = configs["templates"]
templatePath = os.path.abspath(os.path.join(os.path.dirname(__file__), "../", templateConfig["template_directory"]))
class TemplateManager():
def __init__(self):
self.environment = jinja2.Environment(loader = jinja2.FileSystemLoader(templatePath))
def __getitem__(self, attr):
try:
return self.environment.get_template(attr)
except jinja2.TemplateNotFound:
try:
return self.environment.get_template(attr+".html")
except jinja2.TemplateNotFound:
return None
<commit_msg>Add paramater for template path<commit_after>
|
import os.path
import jinja2
import configmanager
configs = configmanager.ConfigManager(os.path.abspath(os.path.join(os.path.dirname(__file__), "../configs")))
templateConfig = configs["templates"]
templatePath = os.path.abspath(os.path.join(os.path.dirname(__file__), "../", templateConfig["template_directory"]))
class TemplateManager():
def __init__(self, path = templatePath):
self.environment = jinja2.Environment(loader = jinja2.FileSystemLoader(path))
def __getitem__(self, attr):
try:
return self.environment.get_template(attr)
except jinja2.TemplateNotFound:
try:
return self.environment.get_template(attr+".html")
except jinja2.TemplateNotFound:
return None
|
import os.path
import jinja2
import configmanager
configs = configmanager.ConfigManager(os.path.abspath(os.path.join(os.path.dirname(__file__), "../configs")))
templateConfig = configs["templates"]
templatePath = os.path.abspath(os.path.join(os.path.dirname(__file__), "../", templateConfig["template_directory"]))
class TemplateManager():
def __init__(self):
self.environment = jinja2.Environment(loader = jinja2.FileSystemLoader(templatePath))
def __getitem__(self, attr):
try:
return self.environment.get_template(attr)
except jinja2.TemplateNotFound:
try:
return self.environment.get_template(attr+".html")
except jinja2.TemplateNotFound:
return None
Add paramater for template pathimport os.path
import jinja2
import configmanager
configs = configmanager.ConfigManager(os.path.abspath(os.path.join(os.path.dirname(__file__), "../configs")))
templateConfig = configs["templates"]
templatePath = os.path.abspath(os.path.join(os.path.dirname(__file__), "../", templateConfig["template_directory"]))
class TemplateManager():
def __init__(self, path = templatePath):
self.environment = jinja2.Environment(loader = jinja2.FileSystemLoader(path))
def __getitem__(self, attr):
try:
return self.environment.get_template(attr)
except jinja2.TemplateNotFound:
try:
return self.environment.get_template(attr+".html")
except jinja2.TemplateNotFound:
return None
|
<commit_before>import os.path
import jinja2
import configmanager
configs = configmanager.ConfigManager(os.path.abspath(os.path.join(os.path.dirname(__file__), "../configs")))
templateConfig = configs["templates"]
templatePath = os.path.abspath(os.path.join(os.path.dirname(__file__), "../", templateConfig["template_directory"]))
class TemplateManager():
def __init__(self):
self.environment = jinja2.Environment(loader = jinja2.FileSystemLoader(templatePath))
def __getitem__(self, attr):
try:
return self.environment.get_template(attr)
except jinja2.TemplateNotFound:
try:
return self.environment.get_template(attr+".html")
except jinja2.TemplateNotFound:
return None
<commit_msg>Add paramater for template path<commit_after>import os.path
import jinja2
import configmanager
configs = configmanager.ConfigManager(os.path.abspath(os.path.join(os.path.dirname(__file__), "../configs")))
templateConfig = configs["templates"]
templatePath = os.path.abspath(os.path.join(os.path.dirname(__file__), "../", templateConfig["template_directory"]))
class TemplateManager():
def __init__(self, path = templatePath):
self.environment = jinja2.Environment(loader = jinja2.FileSystemLoader(path))
def __getitem__(self, attr):
try:
return self.environment.get_template(attr)
except jinja2.TemplateNotFound:
try:
return self.environment.get_template(attr+".html")
except jinja2.TemplateNotFound:
return None
|
1339be71399a7fc8efaea4f2bd892f1b54ced011
|
libcontextsubscriber/multithreading-tests/stress-test/provider.py
|
libcontextsubscriber/multithreading-tests/stress-test/provider.py
|
#!/usr/bin/python
"""A test provider for the stress testing."""
# change registry this often [msec]
registryChangeTimeout = 2017
from ContextKit.flexiprovider import *
import gobject
import time
import os
def update():
t = time.time()
dt = int(1000*(t - round(t)))
gobject.timeout_add(1000 - dt, update)
v = int(round(t))
fp.set('test.int', v)
fp.set('test.int2', v)
print t
return False
pcnt = 0
def chgRegistry():
global pcnt
pcnt += 1
if pcnt % 2:
print "1 provider"
os.system('cp 1provider.cdb cache.cdb')
else:
print "2 providers"
os.system('cp 2providers.cdb cache.cdb')
return True
gobject.timeout_add(1000, update)
# uncoment this to see the "Bus error" XXX
gobject.timeout_add(registryChangeTimeout, chgRegistry)
fp = Flexiprovider([INT('test.int'), INT('test.int2')], 'my.test.provider', 'session')
fp.run()
|
#!/usr/bin/python
"""A test provider for the stress testing."""
# change registry this often [msec]
registryChangeTimeout = 2017
from ContextKit.flexiprovider import *
import gobject
import time
import os
def update():
t = time.time()
dt = int(1000*(t - round(t)))
gobject.timeout_add(1000 - dt, update)
v = int(round(t))
fp.set('test.int', v)
fp.set('test.int2', v)
print t
return False
pcnt = 0
def chgRegistry():
global pcnt
pcnt += 1
if pcnt % 2:
print "1 provider"
os.system('cp 1provider.cdb tmp.cdb; mv tmp.cdb cache.cdb')
else:
print "2 providers"
os.system('cp 2providers.cdb tmp.cdb; mv tmp.cdb cache.cdb')
return True
gobject.timeout_add(1000, update)
# uncoment this to see the "Bus error" XXX
gobject.timeout_add(registryChangeTimeout, chgRegistry)
fp = Flexiprovider([INT('test.int'), INT('test.int2')], 'my.test.provider', 'session')
fp.run()
|
Fix stress test to avoid cdb bus error bug ref 125505
|
Fix stress test to avoid cdb bus error
bug ref 125505
Signed-off-by: Marja Hassinen <[email protected]>
|
Python
|
lgpl-2.1
|
rburchell/ck,rburchell/ck,rburchell/ck,rburchell/ck,rburchell/ck
|
#!/usr/bin/python
"""A test provider for the stress testing."""
# change registry this often [msec]
registryChangeTimeout = 2017
from ContextKit.flexiprovider import *
import gobject
import time
import os
def update():
t = time.time()
dt = int(1000*(t - round(t)))
gobject.timeout_add(1000 - dt, update)
v = int(round(t))
fp.set('test.int', v)
fp.set('test.int2', v)
print t
return False
pcnt = 0
def chgRegistry():
global pcnt
pcnt += 1
if pcnt % 2:
print "1 provider"
os.system('cp 1provider.cdb cache.cdb')
else:
print "2 providers"
os.system('cp 2providers.cdb cache.cdb')
return True
gobject.timeout_add(1000, update)
# uncoment this to see the "Bus error" XXX
gobject.timeout_add(registryChangeTimeout, chgRegistry)
fp = Flexiprovider([INT('test.int'), INT('test.int2')], 'my.test.provider', 'session')
fp.run()
Fix stress test to avoid cdb bus error
bug ref 125505
Signed-off-by: Marja Hassinen <[email protected]>
|
#!/usr/bin/python
"""A test provider for the stress testing."""
# change registry this often [msec]
registryChangeTimeout = 2017
from ContextKit.flexiprovider import *
import gobject
import time
import os
def update():
t = time.time()
dt = int(1000*(t - round(t)))
gobject.timeout_add(1000 - dt, update)
v = int(round(t))
fp.set('test.int', v)
fp.set('test.int2', v)
print t
return False
pcnt = 0
def chgRegistry():
global pcnt
pcnt += 1
if pcnt % 2:
print "1 provider"
os.system('cp 1provider.cdb tmp.cdb; mv tmp.cdb cache.cdb')
else:
print "2 providers"
os.system('cp 2providers.cdb tmp.cdb; mv tmp.cdb cache.cdb')
return True
gobject.timeout_add(1000, update)
# uncoment this to see the "Bus error" XXX
gobject.timeout_add(registryChangeTimeout, chgRegistry)
fp = Flexiprovider([INT('test.int'), INT('test.int2')], 'my.test.provider', 'session')
fp.run()
|
<commit_before>#!/usr/bin/python
"""A test provider for the stress testing."""
# change registry this often [msec]
registryChangeTimeout = 2017
from ContextKit.flexiprovider import *
import gobject
import time
import os
def update():
t = time.time()
dt = int(1000*(t - round(t)))
gobject.timeout_add(1000 - dt, update)
v = int(round(t))
fp.set('test.int', v)
fp.set('test.int2', v)
print t
return False
pcnt = 0
def chgRegistry():
global pcnt
pcnt += 1
if pcnt % 2:
print "1 provider"
os.system('cp 1provider.cdb cache.cdb')
else:
print "2 providers"
os.system('cp 2providers.cdb cache.cdb')
return True
gobject.timeout_add(1000, update)
# uncoment this to see the "Bus error" XXX
gobject.timeout_add(registryChangeTimeout, chgRegistry)
fp = Flexiprovider([INT('test.int'), INT('test.int2')], 'my.test.provider', 'session')
fp.run()
<commit_msg>Fix stress test to avoid cdb bus error
bug ref 125505
Signed-off-by: Marja Hassinen <[email protected]><commit_after>
|
#!/usr/bin/python
"""A test provider for the stress testing."""
# change registry this often [msec]
registryChangeTimeout = 2017
from ContextKit.flexiprovider import *
import gobject
import time
import os
def update():
t = time.time()
dt = int(1000*(t - round(t)))
gobject.timeout_add(1000 - dt, update)
v = int(round(t))
fp.set('test.int', v)
fp.set('test.int2', v)
print t
return False
pcnt = 0
def chgRegistry():
global pcnt
pcnt += 1
if pcnt % 2:
print "1 provider"
os.system('cp 1provider.cdb tmp.cdb; mv tmp.cdb cache.cdb')
else:
print "2 providers"
os.system('cp 2providers.cdb tmp.cdb; mv tmp.cdb cache.cdb')
return True
gobject.timeout_add(1000, update)
# uncoment this to see the "Bus error" XXX
gobject.timeout_add(registryChangeTimeout, chgRegistry)
fp = Flexiprovider([INT('test.int'), INT('test.int2')], 'my.test.provider', 'session')
fp.run()
|
#!/usr/bin/python
"""A test provider for the stress testing."""
# change registry this often [msec]
registryChangeTimeout = 2017
from ContextKit.flexiprovider import *
import gobject
import time
import os
def update():
t = time.time()
dt = int(1000*(t - round(t)))
gobject.timeout_add(1000 - dt, update)
v = int(round(t))
fp.set('test.int', v)
fp.set('test.int2', v)
print t
return False
pcnt = 0
def chgRegistry():
global pcnt
pcnt += 1
if pcnt % 2:
print "1 provider"
os.system('cp 1provider.cdb cache.cdb')
else:
print "2 providers"
os.system('cp 2providers.cdb cache.cdb')
return True
gobject.timeout_add(1000, update)
# uncoment this to see the "Bus error" XXX
gobject.timeout_add(registryChangeTimeout, chgRegistry)
fp = Flexiprovider([INT('test.int'), INT('test.int2')], 'my.test.provider', 'session')
fp.run()
Fix stress test to avoid cdb bus error
bug ref 125505
Signed-off-by: Marja Hassinen <[email protected]>#!/usr/bin/python
"""A test provider for the stress testing."""
# change registry this often [msec]
registryChangeTimeout = 2017
from ContextKit.flexiprovider import *
import gobject
import time
import os
def update():
t = time.time()
dt = int(1000*(t - round(t)))
gobject.timeout_add(1000 - dt, update)
v = int(round(t))
fp.set('test.int', v)
fp.set('test.int2', v)
print t
return False
pcnt = 0
def chgRegistry():
global pcnt
pcnt += 1
if pcnt % 2:
print "1 provider"
os.system('cp 1provider.cdb tmp.cdb; mv tmp.cdb cache.cdb')
else:
print "2 providers"
os.system('cp 2providers.cdb tmp.cdb; mv tmp.cdb cache.cdb')
return True
gobject.timeout_add(1000, update)
# uncoment this to see the "Bus error" XXX
gobject.timeout_add(registryChangeTimeout, chgRegistry)
fp = Flexiprovider([INT('test.int'), INT('test.int2')], 'my.test.provider', 'session')
fp.run()
|
<commit_before>#!/usr/bin/python
"""A test provider for the stress testing."""
# change registry this often [msec]
registryChangeTimeout = 2017
from ContextKit.flexiprovider import *
import gobject
import time
import os
def update():
t = time.time()
dt = int(1000*(t - round(t)))
gobject.timeout_add(1000 - dt, update)
v = int(round(t))
fp.set('test.int', v)
fp.set('test.int2', v)
print t
return False
pcnt = 0
def chgRegistry():
global pcnt
pcnt += 1
if pcnt % 2:
print "1 provider"
os.system('cp 1provider.cdb cache.cdb')
else:
print "2 providers"
os.system('cp 2providers.cdb cache.cdb')
return True
gobject.timeout_add(1000, update)
# uncoment this to see the "Bus error" XXX
gobject.timeout_add(registryChangeTimeout, chgRegistry)
fp = Flexiprovider([INT('test.int'), INT('test.int2')], 'my.test.provider', 'session')
fp.run()
<commit_msg>Fix stress test to avoid cdb bus error
bug ref 125505
Signed-off-by: Marja Hassinen <[email protected]><commit_after>#!/usr/bin/python
"""A test provider for the stress testing."""
# change registry this often [msec]
registryChangeTimeout = 2017
from ContextKit.flexiprovider import *
import gobject
import time
import os
def update():
t = time.time()
dt = int(1000*(t - round(t)))
gobject.timeout_add(1000 - dt, update)
v = int(round(t))
fp.set('test.int', v)
fp.set('test.int2', v)
print t
return False
pcnt = 0
def chgRegistry():
global pcnt
pcnt += 1
if pcnt % 2:
print "1 provider"
os.system('cp 1provider.cdb tmp.cdb; mv tmp.cdb cache.cdb')
else:
print "2 providers"
os.system('cp 2providers.cdb tmp.cdb; mv tmp.cdb cache.cdb')
return True
gobject.timeout_add(1000, update)
# uncoment this to see the "Bus error" XXX
gobject.timeout_add(registryChangeTimeout, chgRegistry)
fp = Flexiprovider([INT('test.int'), INT('test.int2')], 'my.test.provider', 'session')
fp.run()
|
312f6d380ed81b420878bb32ea996fef14ba3f6d
|
run_doctests.py
|
run_doctests.py
|
if __name__ == '__main__':
import doctest
from lesion import trace
doctest.testmod(trace)
|
if __name__ == '__main__':
import doctest
from lesion import lifio, stats, trace
map(doctest.testmod, [lifio, stats, trace])
|
Add new modules to doctests
|
Add new modules to doctests
|
Python
|
bsd-3-clause
|
jni/lesion
|
if __name__ == '__main__':
import doctest
from lesion import trace
doctest.testmod(trace)
Add new modules to doctests
|
if __name__ == '__main__':
import doctest
from lesion import lifio, stats, trace
map(doctest.testmod, [lifio, stats, trace])
|
<commit_before>
if __name__ == '__main__':
import doctest
from lesion import trace
doctest.testmod(trace)
<commit_msg>Add new modules to doctests<commit_after>
|
if __name__ == '__main__':
import doctest
from lesion import lifio, stats, trace
map(doctest.testmod, [lifio, stats, trace])
|
if __name__ == '__main__':
import doctest
from lesion import trace
doctest.testmod(trace)
Add new modules to doctests
if __name__ == '__main__':
import doctest
from lesion import lifio, stats, trace
map(doctest.testmod, [lifio, stats, trace])
|
<commit_before>
if __name__ == '__main__':
import doctest
from lesion import trace
doctest.testmod(trace)
<commit_msg>Add new modules to doctests<commit_after>
if __name__ == '__main__':
import doctest
from lesion import lifio, stats, trace
map(doctest.testmod, [lifio, stats, trace])
|
205324a8fdc9742688952421ed5646877f66f583
|
pydub/exceptions.py
|
pydub/exceptions.py
|
class PydubException(Exception):
"""
Base class for any Pydub exception
"""
class TooManyMissingFrames(PydubException):
pass
class InvalidDuration(PydubException):
pass
class InvalidTag(PydubException):
pass
class InvalidID3TagVersion(PydubException):
pass
class CouldntDecodeError(PydubException):
pass
class CouldntEncodeError(PydubException):
pass
class MissingAudioParameter(PydubException):
pass
|
class PydubException(Exception):
"""
Base class for any Pydub exception
"""
class TooManyMissingFrames(PydubException):
pass
class InvalidDuration(PydubException):
pass
class InvalidTag(PydubException):
pass
class InvalidID3TagVersion(PydubException):
pass
class CouldntDecodeError(PydubException):
pass
class CouldntEncodeError(PydubException):
pass
class MissingAudioParameter(PydubException):
pass
|
Add blank lines to comply with PEP8
|
Add blank lines to comply with PEP8
|
Python
|
mit
|
jiaaro/pydub
|
class PydubException(Exception):
"""
Base class for any Pydub exception
"""
class TooManyMissingFrames(PydubException):
pass
class InvalidDuration(PydubException):
pass
class InvalidTag(PydubException):
pass
class InvalidID3TagVersion(PydubException):
pass
class CouldntDecodeError(PydubException):
pass
class CouldntEncodeError(PydubException):
pass
class MissingAudioParameter(PydubException):
pass
Add blank lines to comply with PEP8
|
class PydubException(Exception):
"""
Base class for any Pydub exception
"""
class TooManyMissingFrames(PydubException):
pass
class InvalidDuration(PydubException):
pass
class InvalidTag(PydubException):
pass
class InvalidID3TagVersion(PydubException):
pass
class CouldntDecodeError(PydubException):
pass
class CouldntEncodeError(PydubException):
pass
class MissingAudioParameter(PydubException):
pass
|
<commit_before>class PydubException(Exception):
"""
Base class for any Pydub exception
"""
class TooManyMissingFrames(PydubException):
pass
class InvalidDuration(PydubException):
pass
class InvalidTag(PydubException):
pass
class InvalidID3TagVersion(PydubException):
pass
class CouldntDecodeError(PydubException):
pass
class CouldntEncodeError(PydubException):
pass
class MissingAudioParameter(PydubException):
pass
<commit_msg>Add blank lines to comply with PEP8<commit_after>
|
class PydubException(Exception):
"""
Base class for any Pydub exception
"""
class TooManyMissingFrames(PydubException):
pass
class InvalidDuration(PydubException):
pass
class InvalidTag(PydubException):
pass
class InvalidID3TagVersion(PydubException):
pass
class CouldntDecodeError(PydubException):
pass
class CouldntEncodeError(PydubException):
pass
class MissingAudioParameter(PydubException):
pass
|
class PydubException(Exception):
"""
Base class for any Pydub exception
"""
class TooManyMissingFrames(PydubException):
pass
class InvalidDuration(PydubException):
pass
class InvalidTag(PydubException):
pass
class InvalidID3TagVersion(PydubException):
pass
class CouldntDecodeError(PydubException):
pass
class CouldntEncodeError(PydubException):
pass
class MissingAudioParameter(PydubException):
pass
Add blank lines to comply with PEP8class PydubException(Exception):
"""
Base class for any Pydub exception
"""
class TooManyMissingFrames(PydubException):
pass
class InvalidDuration(PydubException):
pass
class InvalidTag(PydubException):
pass
class InvalidID3TagVersion(PydubException):
pass
class CouldntDecodeError(PydubException):
pass
class CouldntEncodeError(PydubException):
pass
class MissingAudioParameter(PydubException):
pass
|
<commit_before>class PydubException(Exception):
"""
Base class for any Pydub exception
"""
class TooManyMissingFrames(PydubException):
pass
class InvalidDuration(PydubException):
pass
class InvalidTag(PydubException):
pass
class InvalidID3TagVersion(PydubException):
pass
class CouldntDecodeError(PydubException):
pass
class CouldntEncodeError(PydubException):
pass
class MissingAudioParameter(PydubException):
pass
<commit_msg>Add blank lines to comply with PEP8<commit_after>class PydubException(Exception):
"""
Base class for any Pydub exception
"""
class TooManyMissingFrames(PydubException):
pass
class InvalidDuration(PydubException):
pass
class InvalidTag(PydubException):
pass
class InvalidID3TagVersion(PydubException):
pass
class CouldntDecodeError(PydubException):
pass
class CouldntEncodeError(PydubException):
pass
class MissingAudioParameter(PydubException):
pass
|
3aae3ff16118c8ab743f664c58e4ee3cc9d2b74a
|
lib/rpnpy/__init__.py
|
lib/rpnpy/__init__.py
|
import sys
import ctypes as _ct
if sys.version_info < (3,):
integer_types = (int, long,)
range = xrange
else:
integer_types = (int,)
long = int
# xrange = range
C_WCHAR2CHAR = lambda x: bytes(str(x).encode('ascii'))
C_WCHAR2CHAR.__doc__ = 'Convert str to bytes'
C_CHAR2WCHAR = lambda x: str(x.decode('ascii'))
C_CHAR2WCHAR.__doc__ = 'Convert bytes to str'
C_MKSTR = lambda x: _ct.create_string_buffer(C_WCHAR2CHAR(x))
C_MKSTR.__doc__ = 'alias to ctypes.create_string_buffer, make sure bytes are provided'
|
import sys
import ctypes as _ct
if sys.version_info < (3,):
integer_types = (int, long,)
range = xrange
else:
integer_types = (int,)
long = int
range = range
C_WCHAR2CHAR = lambda x: bytes(str(x).encode('ascii'))
C_WCHAR2CHAR.__doc__ = 'Convert str to bytes'
C_CHAR2WCHAR = lambda x: str(x.decode('ascii'))
C_CHAR2WCHAR.__doc__ = 'Convert bytes to str'
C_MKSTR = lambda x: _ct.create_string_buffer(C_WCHAR2CHAR(x))
C_MKSTR.__doc__ = 'alias to ctypes.create_string_buffer, make sure bytes are provided'
|
Add missing rpnpy.range reference for Python 3.
|
Add missing rpnpy.range reference for Python 3.
Signed-off-by: Stephane_Chamberland <[email protected]>
|
Python
|
lgpl-2.1
|
meteokid/python-rpn,meteokid/python-rpn,meteokid/python-rpn,meteokid/python-rpn
|
import sys
import ctypes as _ct
if sys.version_info < (3,):
integer_types = (int, long,)
range = xrange
else:
integer_types = (int,)
long = int
# xrange = range
C_WCHAR2CHAR = lambda x: bytes(str(x).encode('ascii'))
C_WCHAR2CHAR.__doc__ = 'Convert str to bytes'
C_CHAR2WCHAR = lambda x: str(x.decode('ascii'))
C_CHAR2WCHAR.__doc__ = 'Convert bytes to str'
C_MKSTR = lambda x: _ct.create_string_buffer(C_WCHAR2CHAR(x))
C_MKSTR.__doc__ = 'alias to ctypes.create_string_buffer, make sure bytes are provided'
Add missing rpnpy.range reference for Python 3.
Signed-off-by: Stephane_Chamberland <[email protected]>
|
import sys
import ctypes as _ct
if sys.version_info < (3,):
integer_types = (int, long,)
range = xrange
else:
integer_types = (int,)
long = int
range = range
C_WCHAR2CHAR = lambda x: bytes(str(x).encode('ascii'))
C_WCHAR2CHAR.__doc__ = 'Convert str to bytes'
C_CHAR2WCHAR = lambda x: str(x.decode('ascii'))
C_CHAR2WCHAR.__doc__ = 'Convert bytes to str'
C_MKSTR = lambda x: _ct.create_string_buffer(C_WCHAR2CHAR(x))
C_MKSTR.__doc__ = 'alias to ctypes.create_string_buffer, make sure bytes are provided'
|
<commit_before>import sys
import ctypes as _ct
if sys.version_info < (3,):
integer_types = (int, long,)
range = xrange
else:
integer_types = (int,)
long = int
# xrange = range
C_WCHAR2CHAR = lambda x: bytes(str(x).encode('ascii'))
C_WCHAR2CHAR.__doc__ = 'Convert str to bytes'
C_CHAR2WCHAR = lambda x: str(x.decode('ascii'))
C_CHAR2WCHAR.__doc__ = 'Convert bytes to str'
C_MKSTR = lambda x: _ct.create_string_buffer(C_WCHAR2CHAR(x))
C_MKSTR.__doc__ = 'alias to ctypes.create_string_buffer, make sure bytes are provided'
<commit_msg>Add missing rpnpy.range reference for Python 3.
Signed-off-by: Stephane_Chamberland <[email protected]><commit_after>
|
import sys
import ctypes as _ct
if sys.version_info < (3,):
integer_types = (int, long,)
range = xrange
else:
integer_types = (int,)
long = int
range = range
C_WCHAR2CHAR = lambda x: bytes(str(x).encode('ascii'))
C_WCHAR2CHAR.__doc__ = 'Convert str to bytes'
C_CHAR2WCHAR = lambda x: str(x.decode('ascii'))
C_CHAR2WCHAR.__doc__ = 'Convert bytes to str'
C_MKSTR = lambda x: _ct.create_string_buffer(C_WCHAR2CHAR(x))
C_MKSTR.__doc__ = 'alias to ctypes.create_string_buffer, make sure bytes are provided'
|
import sys
import ctypes as _ct
if sys.version_info < (3,):
integer_types = (int, long,)
range = xrange
else:
integer_types = (int,)
long = int
# xrange = range
C_WCHAR2CHAR = lambda x: bytes(str(x).encode('ascii'))
C_WCHAR2CHAR.__doc__ = 'Convert str to bytes'
C_CHAR2WCHAR = lambda x: str(x.decode('ascii'))
C_CHAR2WCHAR.__doc__ = 'Convert bytes to str'
C_MKSTR = lambda x: _ct.create_string_buffer(C_WCHAR2CHAR(x))
C_MKSTR.__doc__ = 'alias to ctypes.create_string_buffer, make sure bytes are provided'
Add missing rpnpy.range reference for Python 3.
Signed-off-by: Stephane_Chamberland <[email protected]>import sys
import ctypes as _ct
if sys.version_info < (3,):
integer_types = (int, long,)
range = xrange
else:
integer_types = (int,)
long = int
range = range
C_WCHAR2CHAR = lambda x: bytes(str(x).encode('ascii'))
C_WCHAR2CHAR.__doc__ = 'Convert str to bytes'
C_CHAR2WCHAR = lambda x: str(x.decode('ascii'))
C_CHAR2WCHAR.__doc__ = 'Convert bytes to str'
C_MKSTR = lambda x: _ct.create_string_buffer(C_WCHAR2CHAR(x))
C_MKSTR.__doc__ = 'alias to ctypes.create_string_buffer, make sure bytes are provided'
|
<commit_before>import sys
import ctypes as _ct
if sys.version_info < (3,):
integer_types = (int, long,)
range = xrange
else:
integer_types = (int,)
long = int
# xrange = range
C_WCHAR2CHAR = lambda x: bytes(str(x).encode('ascii'))
C_WCHAR2CHAR.__doc__ = 'Convert str to bytes'
C_CHAR2WCHAR = lambda x: str(x.decode('ascii'))
C_CHAR2WCHAR.__doc__ = 'Convert bytes to str'
C_MKSTR = lambda x: _ct.create_string_buffer(C_WCHAR2CHAR(x))
C_MKSTR.__doc__ = 'alias to ctypes.create_string_buffer, make sure bytes are provided'
<commit_msg>Add missing rpnpy.range reference for Python 3.
Signed-off-by: Stephane_Chamberland <[email protected]><commit_after>import sys
import ctypes as _ct
if sys.version_info < (3,):
integer_types = (int, long,)
range = xrange
else:
integer_types = (int,)
long = int
range = range
C_WCHAR2CHAR = lambda x: bytes(str(x).encode('ascii'))
C_WCHAR2CHAR.__doc__ = 'Convert str to bytes'
C_CHAR2WCHAR = lambda x: str(x.decode('ascii'))
C_CHAR2WCHAR.__doc__ = 'Convert bytes to str'
C_MKSTR = lambda x: _ct.create_string_buffer(C_WCHAR2CHAR(x))
C_MKSTR.__doc__ = 'alias to ctypes.create_string_buffer, make sure bytes are provided'
|
e7c655bfdc860cd007e9c274c729f8a00d7fa0f5
|
dnzo/test/test_api.py
|
dnzo/test/test_api.py
|
import unittest
from os import path
from webtest import TestApp
from google.appengine.ext import webapp
from django.utils import simplejson as json
from api.main import API_URLS, API_PREFIX
from test.fixtures import setup_fixtures
from tasks_data.models import Task
class TaskAPITest(unittest.TestCase):
def setUp(self):
setup_fixtures()
self.application = webapp.WSGIApplication(API_URLS, debug=True)
def test_task(self):
app = TestApp(self.application)
for task in Task.all():
task_id = str(task.key().id())
response = app.get(path.join(API_PREFIX,'t',task_id))
self.assertEqual('200 OK', response.status)
self.assertTrue(json.dumps(task.body) in response,
"Response should include JSON-encoded task body.")
|
import unittest
from os import path
from webtest import TestApp
from google.appengine.ext import webapp
from django.utils import simplejson as json
from api.main import API_URLS, API_PREFIX
from test.fixtures import setup_fixtures
from tasks_data.models import Task
BOGUS_IDS = ('abc', '-1', '0.1234', '1.', '.1', ' 123 ', '99999')
class TaskAPITest(unittest.TestCase):
def setUp(self):
setup_fixtures()
self.application = webapp.WSGIApplication(API_URLS, debug=True)
def test_get_task(self):
app = TestApp(self.application)
all_tasks_response = app.get(path.join(API_PREFIX,'t'))
self.assertEqual('200 OK', all_tasks_response.status)
for task in Task.all():
task_id = str(task.key().id())
response = app.get(path.join(API_PREFIX,'t',task_id))
self.assertEqual('200 OK', response.status)
self.assertTrue(json.dumps(task.body) in response,
"Response should include JSON-encoded task body.")
self.assertTrue(json.dumps(task.project) in response,
"Response should include task's project.")
self.assertTrue(json.dumps(task.body) in all_tasks_response,
"/t/ response should include all tasks' bodies.")
self.assertTrue(json.dumps(task.project) in all_tasks_response,
"/t/ response should include all tasks' projects.")
for bogus_id in BOGUS_IDS:
response = app.get(path.join(API_PREFIX,'t',bogus_id), expect_errors=True)
self.assertTrue('404 Not Found' in response.status,
"Bogus ID task should be Not Found, but response was (%s)" % response.status)
|
Add some more basic tests for /t/, which should return all tasks for a user.
|
Add some more basic tests for /t/, which should return all tasks for a user.
git-svn-id: 062a66634e56759c7c3cc44955c32d2ce0012d25@307 c02d1e6f-6a35-45f2-ab14-3b6f79a691ff
|
Python
|
mit
|
taylorhughes/done-zo,taylorhughes/done-zo,taylorhughes/done-zo,taylorhughes/done-zo
|
import unittest
from os import path
from webtest import TestApp
from google.appengine.ext import webapp
from django.utils import simplejson as json
from api.main import API_URLS, API_PREFIX
from test.fixtures import setup_fixtures
from tasks_data.models import Task
class TaskAPITest(unittest.TestCase):
def setUp(self):
setup_fixtures()
self.application = webapp.WSGIApplication(API_URLS, debug=True)
def test_task(self):
app = TestApp(self.application)
for task in Task.all():
task_id = str(task.key().id())
response = app.get(path.join(API_PREFIX,'t',task_id))
self.assertEqual('200 OK', response.status)
self.assertTrue(json.dumps(task.body) in response,
"Response should include JSON-encoded task body.")Add some more basic tests for /t/, which should return all tasks for a user.
git-svn-id: 062a66634e56759c7c3cc44955c32d2ce0012d25@307 c02d1e6f-6a35-45f2-ab14-3b6f79a691ff
|
import unittest
from os import path
from webtest import TestApp
from google.appengine.ext import webapp
from django.utils import simplejson as json
from api.main import API_URLS, API_PREFIX
from test.fixtures import setup_fixtures
from tasks_data.models import Task
BOGUS_IDS = ('abc', '-1', '0.1234', '1.', '.1', ' 123 ', '99999')
class TaskAPITest(unittest.TestCase):
def setUp(self):
setup_fixtures()
self.application = webapp.WSGIApplication(API_URLS, debug=True)
def test_get_task(self):
app = TestApp(self.application)
all_tasks_response = app.get(path.join(API_PREFIX,'t'))
self.assertEqual('200 OK', all_tasks_response.status)
for task in Task.all():
task_id = str(task.key().id())
response = app.get(path.join(API_PREFIX,'t',task_id))
self.assertEqual('200 OK', response.status)
self.assertTrue(json.dumps(task.body) in response,
"Response should include JSON-encoded task body.")
self.assertTrue(json.dumps(task.project) in response,
"Response should include task's project.")
self.assertTrue(json.dumps(task.body) in all_tasks_response,
"/t/ response should include all tasks' bodies.")
self.assertTrue(json.dumps(task.project) in all_tasks_response,
"/t/ response should include all tasks' projects.")
for bogus_id in BOGUS_IDS:
response = app.get(path.join(API_PREFIX,'t',bogus_id), expect_errors=True)
self.assertTrue('404 Not Found' in response.status,
"Bogus ID task should be Not Found, but response was (%s)" % response.status)
|
<commit_before>import unittest
from os import path
from webtest import TestApp
from google.appengine.ext import webapp
from django.utils import simplejson as json
from api.main import API_URLS, API_PREFIX
from test.fixtures import setup_fixtures
from tasks_data.models import Task
class TaskAPITest(unittest.TestCase):
def setUp(self):
setup_fixtures()
self.application = webapp.WSGIApplication(API_URLS, debug=True)
def test_task(self):
app = TestApp(self.application)
for task in Task.all():
task_id = str(task.key().id())
response = app.get(path.join(API_PREFIX,'t',task_id))
self.assertEqual('200 OK', response.status)
self.assertTrue(json.dumps(task.body) in response,
"Response should include JSON-encoded task body.")<commit_msg>Add some more basic tests for /t/, which should return all tasks for a user.
git-svn-id: 062a66634e56759c7c3cc44955c32d2ce0012d25@307 c02d1e6f-6a35-45f2-ab14-3b6f79a691ff<commit_after>
|
import unittest
from os import path
from webtest import TestApp
from google.appengine.ext import webapp
from django.utils import simplejson as json
from api.main import API_URLS, API_PREFIX
from test.fixtures import setup_fixtures
from tasks_data.models import Task
BOGUS_IDS = ('abc', '-1', '0.1234', '1.', '.1', ' 123 ', '99999')
class TaskAPITest(unittest.TestCase):
def setUp(self):
setup_fixtures()
self.application = webapp.WSGIApplication(API_URLS, debug=True)
def test_get_task(self):
app = TestApp(self.application)
all_tasks_response = app.get(path.join(API_PREFIX,'t'))
self.assertEqual('200 OK', all_tasks_response.status)
for task in Task.all():
task_id = str(task.key().id())
response = app.get(path.join(API_PREFIX,'t',task_id))
self.assertEqual('200 OK', response.status)
self.assertTrue(json.dumps(task.body) in response,
"Response should include JSON-encoded task body.")
self.assertTrue(json.dumps(task.project) in response,
"Response should include task's project.")
self.assertTrue(json.dumps(task.body) in all_tasks_response,
"/t/ response should include all tasks' bodies.")
self.assertTrue(json.dumps(task.project) in all_tasks_response,
"/t/ response should include all tasks' projects.")
for bogus_id in BOGUS_IDS:
response = app.get(path.join(API_PREFIX,'t',bogus_id), expect_errors=True)
self.assertTrue('404 Not Found' in response.status,
"Bogus ID task should be Not Found, but response was (%s)" % response.status)
|
import unittest
from os import path
from webtest import TestApp
from google.appengine.ext import webapp
from django.utils import simplejson as json
from api.main import API_URLS, API_PREFIX
from test.fixtures import setup_fixtures
from tasks_data.models import Task
class TaskAPITest(unittest.TestCase):
def setUp(self):
setup_fixtures()
self.application = webapp.WSGIApplication(API_URLS, debug=True)
def test_task(self):
app = TestApp(self.application)
for task in Task.all():
task_id = str(task.key().id())
response = app.get(path.join(API_PREFIX,'t',task_id))
self.assertEqual('200 OK', response.status)
self.assertTrue(json.dumps(task.body) in response,
"Response should include JSON-encoded task body.")Add some more basic tests for /t/, which should return all tasks for a user.
git-svn-id: 062a66634e56759c7c3cc44955c32d2ce0012d25@307 c02d1e6f-6a35-45f2-ab14-3b6f79a691ffimport unittest
from os import path
from webtest import TestApp
from google.appengine.ext import webapp
from django.utils import simplejson as json
from api.main import API_URLS, API_PREFIX
from test.fixtures import setup_fixtures
from tasks_data.models import Task
BOGUS_IDS = ('abc', '-1', '0.1234', '1.', '.1', ' 123 ', '99999')
class TaskAPITest(unittest.TestCase):
def setUp(self):
setup_fixtures()
self.application = webapp.WSGIApplication(API_URLS, debug=True)
def test_get_task(self):
app = TestApp(self.application)
all_tasks_response = app.get(path.join(API_PREFIX,'t'))
self.assertEqual('200 OK', all_tasks_response.status)
for task in Task.all():
task_id = str(task.key().id())
response = app.get(path.join(API_PREFIX,'t',task_id))
self.assertEqual('200 OK', response.status)
self.assertTrue(json.dumps(task.body) in response,
"Response should include JSON-encoded task body.")
self.assertTrue(json.dumps(task.project) in response,
"Response should include task's project.")
self.assertTrue(json.dumps(task.body) in all_tasks_response,
"/t/ response should include all tasks' bodies.")
self.assertTrue(json.dumps(task.project) in all_tasks_response,
"/t/ response should include all tasks' projects.")
for bogus_id in BOGUS_IDS:
response = app.get(path.join(API_PREFIX,'t',bogus_id), expect_errors=True)
self.assertTrue('404 Not Found' in response.status,
"Bogus ID task should be Not Found, but response was (%s)" % response.status)
|
<commit_before>import unittest
from os import path
from webtest import TestApp
from google.appengine.ext import webapp
from django.utils import simplejson as json
from api.main import API_URLS, API_PREFIX
from test.fixtures import setup_fixtures
from tasks_data.models import Task
class TaskAPITest(unittest.TestCase):
def setUp(self):
setup_fixtures()
self.application = webapp.WSGIApplication(API_URLS, debug=True)
def test_task(self):
app = TestApp(self.application)
for task in Task.all():
task_id = str(task.key().id())
response = app.get(path.join(API_PREFIX,'t',task_id))
self.assertEqual('200 OK', response.status)
self.assertTrue(json.dumps(task.body) in response,
"Response should include JSON-encoded task body.")<commit_msg>Add some more basic tests for /t/, which should return all tasks for a user.
git-svn-id: 062a66634e56759c7c3cc44955c32d2ce0012d25@307 c02d1e6f-6a35-45f2-ab14-3b6f79a691ff<commit_after>import unittest
from os import path
from webtest import TestApp
from google.appengine.ext import webapp
from django.utils import simplejson as json
from api.main import API_URLS, API_PREFIX
from test.fixtures import setup_fixtures
from tasks_data.models import Task
BOGUS_IDS = ('abc', '-1', '0.1234', '1.', '.1', ' 123 ', '99999')
class TaskAPITest(unittest.TestCase):
def setUp(self):
setup_fixtures()
self.application = webapp.WSGIApplication(API_URLS, debug=True)
def test_get_task(self):
app = TestApp(self.application)
all_tasks_response = app.get(path.join(API_PREFIX,'t'))
self.assertEqual('200 OK', all_tasks_response.status)
for task in Task.all():
task_id = str(task.key().id())
response = app.get(path.join(API_PREFIX,'t',task_id))
self.assertEqual('200 OK', response.status)
self.assertTrue(json.dumps(task.body) in response,
"Response should include JSON-encoded task body.")
self.assertTrue(json.dumps(task.project) in response,
"Response should include task's project.")
self.assertTrue(json.dumps(task.body) in all_tasks_response,
"/t/ response should include all tasks' bodies.")
self.assertTrue(json.dumps(task.project) in all_tasks_response,
"/t/ response should include all tasks' projects.")
for bogus_id in BOGUS_IDS:
response = app.get(path.join(API_PREFIX,'t',bogus_id), expect_errors=True)
self.assertTrue('404 Not Found' in response.status,
"Bogus ID task should be Not Found, but response was (%s)" % response.status)
|
ff5da3c3ccb378772e073a1020d3a7fcee72d7e4
|
scripts/install_devplatforms.py
|
scripts/install_devplatforms.py
|
# Copyright (c) 2014-present PlatformIO <[email 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.
import json
import subprocess
import sys
from platformio import util
def main():
platforms = json.loads(
subprocess.check_output(
["platformio", "platform", "search", "--json-output"]).decode())
for platform in platforms:
if platform['forDesktop']:
continue
# RISC-V GAP does not support Windows 86
if (util.get_systype() == "windows_x86"
and platform['name'] == "riscv_gap"):
continue
# unknown issue on Linux
if ("linux" in util.get_systype()
and platform['name'] == "aceinna_imu"):
continue
subprocess.check_call(
["platformio", "platform", "install", platform['repository']])
if __name__ == "__main__":
sys.exit(main())
|
# Copyright (c) 2014-present PlatformIO <[email 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.
import json
import subprocess
import sys
from platformio import util
def main():
platforms = json.loads(
subprocess.check_output(
["platformio", "platform", "search", "--json-output"]).decode())
for platform in platforms:
if platform['forDesktop']:
continue
# RISC-V GAP does not support Windows 86
if (util.get_systype() == "windows_x86"
and platform['name'] == "riscv_gap"):
continue
# unknown issue on Linux
if ("linux" in util.get_systype()
and platform['name'] == "aceinna_imu"):
continue
subprocess.check_call(
["platformio", "platform", "install", platform['name']])
if __name__ == "__main__":
sys.exit(main())
|
Use stable dev/platforms for CI
|
Use stable dev/platforms for CI
|
Python
|
apache-2.0
|
platformio/platformio-core,platformio/platformio-core,platformio/platformio
|
# Copyright (c) 2014-present PlatformIO <[email 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.
import json
import subprocess
import sys
from platformio import util
def main():
platforms = json.loads(
subprocess.check_output(
["platformio", "platform", "search", "--json-output"]).decode())
for platform in platforms:
if platform['forDesktop']:
continue
# RISC-V GAP does not support Windows 86
if (util.get_systype() == "windows_x86"
and platform['name'] == "riscv_gap"):
continue
# unknown issue on Linux
if ("linux" in util.get_systype()
and platform['name'] == "aceinna_imu"):
continue
subprocess.check_call(
["platformio", "platform", "install", platform['repository']])
if __name__ == "__main__":
sys.exit(main())
Use stable dev/platforms for CI
|
# Copyright (c) 2014-present PlatformIO <[email 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.
import json
import subprocess
import sys
from platformio import util
def main():
platforms = json.loads(
subprocess.check_output(
["platformio", "platform", "search", "--json-output"]).decode())
for platform in platforms:
if platform['forDesktop']:
continue
# RISC-V GAP does not support Windows 86
if (util.get_systype() == "windows_x86"
and platform['name'] == "riscv_gap"):
continue
# unknown issue on Linux
if ("linux" in util.get_systype()
and platform['name'] == "aceinna_imu"):
continue
subprocess.check_call(
["platformio", "platform", "install", platform['name']])
if __name__ == "__main__":
sys.exit(main())
|
<commit_before># Copyright (c) 2014-present PlatformIO <[email 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.
import json
import subprocess
import sys
from platformio import util
def main():
platforms = json.loads(
subprocess.check_output(
["platformio", "platform", "search", "--json-output"]).decode())
for platform in platforms:
if platform['forDesktop']:
continue
# RISC-V GAP does not support Windows 86
if (util.get_systype() == "windows_x86"
and platform['name'] == "riscv_gap"):
continue
# unknown issue on Linux
if ("linux" in util.get_systype()
and platform['name'] == "aceinna_imu"):
continue
subprocess.check_call(
["platformio", "platform", "install", platform['repository']])
if __name__ == "__main__":
sys.exit(main())
<commit_msg>Use stable dev/platforms for CI<commit_after>
|
# Copyright (c) 2014-present PlatformIO <[email 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.
import json
import subprocess
import sys
from platformio import util
def main():
platforms = json.loads(
subprocess.check_output(
["platformio", "platform", "search", "--json-output"]).decode())
for platform in platforms:
if platform['forDesktop']:
continue
# RISC-V GAP does not support Windows 86
if (util.get_systype() == "windows_x86"
and platform['name'] == "riscv_gap"):
continue
# unknown issue on Linux
if ("linux" in util.get_systype()
and platform['name'] == "aceinna_imu"):
continue
subprocess.check_call(
["platformio", "platform", "install", platform['name']])
if __name__ == "__main__":
sys.exit(main())
|
# Copyright (c) 2014-present PlatformIO <[email 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.
import json
import subprocess
import sys
from platformio import util
def main():
platforms = json.loads(
subprocess.check_output(
["platformio", "platform", "search", "--json-output"]).decode())
for platform in platforms:
if platform['forDesktop']:
continue
# RISC-V GAP does not support Windows 86
if (util.get_systype() == "windows_x86"
and platform['name'] == "riscv_gap"):
continue
# unknown issue on Linux
if ("linux" in util.get_systype()
and platform['name'] == "aceinna_imu"):
continue
subprocess.check_call(
["platformio", "platform", "install", platform['repository']])
if __name__ == "__main__":
sys.exit(main())
Use stable dev/platforms for CI# Copyright (c) 2014-present PlatformIO <[email 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.
import json
import subprocess
import sys
from platformio import util
def main():
platforms = json.loads(
subprocess.check_output(
["platformio", "platform", "search", "--json-output"]).decode())
for platform in platforms:
if platform['forDesktop']:
continue
# RISC-V GAP does not support Windows 86
if (util.get_systype() == "windows_x86"
and platform['name'] == "riscv_gap"):
continue
# unknown issue on Linux
if ("linux" in util.get_systype()
and platform['name'] == "aceinna_imu"):
continue
subprocess.check_call(
["platformio", "platform", "install", platform['name']])
if __name__ == "__main__":
sys.exit(main())
|
<commit_before># Copyright (c) 2014-present PlatformIO <[email 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.
import json
import subprocess
import sys
from platformio import util
def main():
platforms = json.loads(
subprocess.check_output(
["platformio", "platform", "search", "--json-output"]).decode())
for platform in platforms:
if platform['forDesktop']:
continue
# RISC-V GAP does not support Windows 86
if (util.get_systype() == "windows_x86"
and platform['name'] == "riscv_gap"):
continue
# unknown issue on Linux
if ("linux" in util.get_systype()
and platform['name'] == "aceinna_imu"):
continue
subprocess.check_call(
["platformio", "platform", "install", platform['repository']])
if __name__ == "__main__":
sys.exit(main())
<commit_msg>Use stable dev/platforms for CI<commit_after># Copyright (c) 2014-present PlatformIO <[email 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.
import json
import subprocess
import sys
from platformio import util
def main():
platforms = json.loads(
subprocess.check_output(
["platformio", "platform", "search", "--json-output"]).decode())
for platform in platforms:
if platform['forDesktop']:
continue
# RISC-V GAP does not support Windows 86
if (util.get_systype() == "windows_x86"
and platform['name'] == "riscv_gap"):
continue
# unknown issue on Linux
if ("linux" in util.get_systype()
and platform['name'] == "aceinna_imu"):
continue
subprocess.check_call(
["platformio", "platform", "install", platform['name']])
if __name__ == "__main__":
sys.exit(main())
|
59f5007787b87a37b5e5669a75d39d1d7e88e0e9
|
redfish/__init__.py
|
redfish/__init__.py
|
# -*- coding: utf-8 -*-
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import pbr.version
from redfish.main import *
#import redfish.types
__version__ = pbr.version.VersionInfo('redfish').version_string()
|
# -*- coding: utf-8 -*-
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import pbr.version
from redfish.main import *
#import redfish.types
try:
__version__ = pbr.version.VersionInfo('redfish').version_string()
except Exception, e:
if "Versioning for this project requires either an sdist tarball" in e.message:
pass
else:
raise
|
Fix pbr if running without git or sdist
|
Fix pbr if running without git or sdist
|
Python
|
apache-2.0
|
uggla/python-redfish,bcornec/python-redfish,bcornec/python-redfish,uggla/python-redfish,uggla/python-redfish,bcornec/python-redfish
|
# -*- coding: utf-8 -*-
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import pbr.version
from redfish.main import *
#import redfish.types
__version__ = pbr.version.VersionInfo('redfish').version_string()
Fix pbr if running without git or sdist
|
# -*- coding: utf-8 -*-
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import pbr.version
from redfish.main import *
#import redfish.types
try:
__version__ = pbr.version.VersionInfo('redfish').version_string()
except Exception, e:
if "Versioning for this project requires either an sdist tarball" in e.message:
pass
else:
raise
|
<commit_before># -*- coding: utf-8 -*-
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import pbr.version
from redfish.main import *
#import redfish.types
__version__ = pbr.version.VersionInfo('redfish').version_string()
<commit_msg>Fix pbr if running without git or sdist<commit_after>
|
# -*- coding: utf-8 -*-
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import pbr.version
from redfish.main import *
#import redfish.types
try:
__version__ = pbr.version.VersionInfo('redfish').version_string()
except Exception, e:
if "Versioning for this project requires either an sdist tarball" in e.message:
pass
else:
raise
|
# -*- coding: utf-8 -*-
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import pbr.version
from redfish.main import *
#import redfish.types
__version__ = pbr.version.VersionInfo('redfish').version_string()
Fix pbr if running without git or sdist# -*- coding: utf-8 -*-
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import pbr.version
from redfish.main import *
#import redfish.types
try:
__version__ = pbr.version.VersionInfo('redfish').version_string()
except Exception, e:
if "Versioning for this project requires either an sdist tarball" in e.message:
pass
else:
raise
|
<commit_before># -*- coding: utf-8 -*-
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import pbr.version
from redfish.main import *
#import redfish.types
__version__ = pbr.version.VersionInfo('redfish').version_string()
<commit_msg>Fix pbr if running without git or sdist<commit_after># -*- coding: utf-8 -*-
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import pbr.version
from redfish.main import *
#import redfish.types
try:
__version__ = pbr.version.VersionInfo('redfish').version_string()
except Exception, e:
if "Versioning for this project requires either an sdist tarball" in e.message:
pass
else:
raise
|
4c1993158bf44954bc10305f6f64e23dfd5d4618
|
floo/api.py
|
floo/api.py
|
from urllib.parse import urlencode
import urllib.error
import urllib.request
from . import shared as G
def create_room(room_name):
url = 'https://%s/api/room/' % G.DEFAULT_HOST
# TODO: let user specify permissions
post_data = {
'username': G.USERNAME,
'secret': G.SECRET,
'name': room_name
}
urllib.request.urlopen(url, data=urlencode(post_data), timeout=5)
|
from urllib.parse import urlencode
import urllib.error
import urllib.request
from . import shared as G
def create_room(room_name):
url = 'https://%s/api/room/' % G.DEFAULT_HOST
# TODO: let user specify permissions
post_data = {
'username': G.USERNAME,
'secret': G.SECRET,
'name': room_name
}
urllib.request.urlopen(url, data=urlencode(post_data).encode('ascii'), timeout=5)
|
Fix bug when creating rooms
|
Fix bug when creating rooms
|
Python
|
apache-2.0
|
Floobits/floobits-sublime,Floobits/floobits-sublime
|
from urllib.parse import urlencode
import urllib.error
import urllib.request
from . import shared as G
def create_room(room_name):
url = 'https://%s/api/room/' % G.DEFAULT_HOST
# TODO: let user specify permissions
post_data = {
'username': G.USERNAME,
'secret': G.SECRET,
'name': room_name
}
urllib.request.urlopen(url, data=urlencode(post_data), timeout=5)
Fix bug when creating rooms
|
from urllib.parse import urlencode
import urllib.error
import urllib.request
from . import shared as G
def create_room(room_name):
url = 'https://%s/api/room/' % G.DEFAULT_HOST
# TODO: let user specify permissions
post_data = {
'username': G.USERNAME,
'secret': G.SECRET,
'name': room_name
}
urllib.request.urlopen(url, data=urlencode(post_data).encode('ascii'), timeout=5)
|
<commit_before>from urllib.parse import urlencode
import urllib.error
import urllib.request
from . import shared as G
def create_room(room_name):
url = 'https://%s/api/room/' % G.DEFAULT_HOST
# TODO: let user specify permissions
post_data = {
'username': G.USERNAME,
'secret': G.SECRET,
'name': room_name
}
urllib.request.urlopen(url, data=urlencode(post_data), timeout=5)
<commit_msg>Fix bug when creating rooms<commit_after>
|
from urllib.parse import urlencode
import urllib.error
import urllib.request
from . import shared as G
def create_room(room_name):
url = 'https://%s/api/room/' % G.DEFAULT_HOST
# TODO: let user specify permissions
post_data = {
'username': G.USERNAME,
'secret': G.SECRET,
'name': room_name
}
urllib.request.urlopen(url, data=urlencode(post_data).encode('ascii'), timeout=5)
|
from urllib.parse import urlencode
import urllib.error
import urllib.request
from . import shared as G
def create_room(room_name):
url = 'https://%s/api/room/' % G.DEFAULT_HOST
# TODO: let user specify permissions
post_data = {
'username': G.USERNAME,
'secret': G.SECRET,
'name': room_name
}
urllib.request.urlopen(url, data=urlencode(post_data), timeout=5)
Fix bug when creating roomsfrom urllib.parse import urlencode
import urllib.error
import urllib.request
from . import shared as G
def create_room(room_name):
url = 'https://%s/api/room/' % G.DEFAULT_HOST
# TODO: let user specify permissions
post_data = {
'username': G.USERNAME,
'secret': G.SECRET,
'name': room_name
}
urllib.request.urlopen(url, data=urlencode(post_data).encode('ascii'), timeout=5)
|
<commit_before>from urllib.parse import urlencode
import urllib.error
import urllib.request
from . import shared as G
def create_room(room_name):
url = 'https://%s/api/room/' % G.DEFAULT_HOST
# TODO: let user specify permissions
post_data = {
'username': G.USERNAME,
'secret': G.SECRET,
'name': room_name
}
urllib.request.urlopen(url, data=urlencode(post_data), timeout=5)
<commit_msg>Fix bug when creating rooms<commit_after>from urllib.parse import urlencode
import urllib.error
import urllib.request
from . import shared as G
def create_room(room_name):
url = 'https://%s/api/room/' % G.DEFAULT_HOST
# TODO: let user specify permissions
post_data = {
'username': G.USERNAME,
'secret': G.SECRET,
'name': room_name
}
urllib.request.urlopen(url, data=urlencode(post_data).encode('ascii'), timeout=5)
|
91edea41858c1171168b8e2ed77f97ea19c8f684
|
public/sentry/env_remote_user_middleware.py
|
public/sentry/env_remote_user_middleware.py
|
import os
from django.contrib.auth.middleware import RemoteUserMiddleware
class EnvRemoteUserMiddleware(RemoteUserMiddleware):
header = os.environ.get('REMOTE_USER_HEADER', 'REMOTE_USER')
|
import os
from django.contrib.auth.middleware import RemoteUserMiddleware
class EnvRemoteUserMiddleware(RemoteUserMiddleware):
header = os.environ.get('REMOTE_USER_HEADER', 'REMOTE_USER')
def configure_user(user):
if 'REMOTE_USER_EMAIL_SUFFIX' in os.environ:
user.email = "{0}{1}".format(user.username, os.environ['REMOTE_USER_EMAIL_SUFFIX'])
user.save()
return user
|
Configure user's e-mail via REMOTE_USER_EMAIL_SUFFIX
|
sentry: Configure user's e-mail via REMOTE_USER_EMAIL_SUFFIX
|
Python
|
mit
|
3ofcoins/docker-images,3ofcoins/docker-images
|
import os
from django.contrib.auth.middleware import RemoteUserMiddleware
class EnvRemoteUserMiddleware(RemoteUserMiddleware):
header = os.environ.get('REMOTE_USER_HEADER', 'REMOTE_USER')
sentry: Configure user's e-mail via REMOTE_USER_EMAIL_SUFFIX
|
import os
from django.contrib.auth.middleware import RemoteUserMiddleware
class EnvRemoteUserMiddleware(RemoteUserMiddleware):
header = os.environ.get('REMOTE_USER_HEADER', 'REMOTE_USER')
def configure_user(user):
if 'REMOTE_USER_EMAIL_SUFFIX' in os.environ:
user.email = "{0}{1}".format(user.username, os.environ['REMOTE_USER_EMAIL_SUFFIX'])
user.save()
return user
|
<commit_before>import os
from django.contrib.auth.middleware import RemoteUserMiddleware
class EnvRemoteUserMiddleware(RemoteUserMiddleware):
header = os.environ.get('REMOTE_USER_HEADER', 'REMOTE_USER')
<commit_msg>sentry: Configure user's e-mail via REMOTE_USER_EMAIL_SUFFIX<commit_after>
|
import os
from django.contrib.auth.middleware import RemoteUserMiddleware
class EnvRemoteUserMiddleware(RemoteUserMiddleware):
header = os.environ.get('REMOTE_USER_HEADER', 'REMOTE_USER')
def configure_user(user):
if 'REMOTE_USER_EMAIL_SUFFIX' in os.environ:
user.email = "{0}{1}".format(user.username, os.environ['REMOTE_USER_EMAIL_SUFFIX'])
user.save()
return user
|
import os
from django.contrib.auth.middleware import RemoteUserMiddleware
class EnvRemoteUserMiddleware(RemoteUserMiddleware):
header = os.environ.get('REMOTE_USER_HEADER', 'REMOTE_USER')
sentry: Configure user's e-mail via REMOTE_USER_EMAIL_SUFFIXimport os
from django.contrib.auth.middleware import RemoteUserMiddleware
class EnvRemoteUserMiddleware(RemoteUserMiddleware):
header = os.environ.get('REMOTE_USER_HEADER', 'REMOTE_USER')
def configure_user(user):
if 'REMOTE_USER_EMAIL_SUFFIX' in os.environ:
user.email = "{0}{1}".format(user.username, os.environ['REMOTE_USER_EMAIL_SUFFIX'])
user.save()
return user
|
<commit_before>import os
from django.contrib.auth.middleware import RemoteUserMiddleware
class EnvRemoteUserMiddleware(RemoteUserMiddleware):
header = os.environ.get('REMOTE_USER_HEADER', 'REMOTE_USER')
<commit_msg>sentry: Configure user's e-mail via REMOTE_USER_EMAIL_SUFFIX<commit_after>import os
from django.contrib.auth.middleware import RemoteUserMiddleware
class EnvRemoteUserMiddleware(RemoteUserMiddleware):
header = os.environ.get('REMOTE_USER_HEADER', 'REMOTE_USER')
def configure_user(user):
if 'REMOTE_USER_EMAIL_SUFFIX' in os.environ:
user.email = "{0}{1}".format(user.username, os.environ['REMOTE_USER_EMAIL_SUFFIX'])
user.save()
return user
|
43d14f73055643a2e4921a58aa1bf5e14fdf8e74
|
linter.py
|
linter.py
|
import logging
import re
from SublimeLinter.lint import NodeLinter
logger = logging.getLogger('SublimeLinter.plugin.tslint')
class Tslint(NodeLinter):
cmd = 'tslint --format verbose ${file}'
regex = (
r'^(?:'
r'(ERROR:\s+\((?P<error>.*)\))|'
r'(WARNING:\s+\((?P<warning>.*)\))'
r')?'
r'.+?\[(?P<line>\d+), (?P<col>\d+)\]: '
r'(?P<message>.+)'
)
tempfile_suffix = '-'
defaults = {
'selector': 'source.ts, source.tsx'
}
def on_stderr(self, stderr):
# suppress warnings like "rule requires type information"
stderr = re.sub(
'Warning: .+\n', '', stderr)
if stderr:
self.notify_failure()
logger.error(stderr)
|
import logging
import re
from SublimeLinter.lint import NodeLinter
logger = logging.getLogger('SublimeLinter.plugin.tslint')
class Tslint(NodeLinter):
cmd = 'tslint --format verbose ${file}'
regex = (
r'^(?:'
r'(ERROR:\s+\((?P<error>.*)\))|'
r'(WARNING:\s+\((?P<warning>.*)\))'
r')?'
r'\s+(?P<filename>.+?)'
r'\[(?P<line>\d+), (?P<col>\d+)\]: '
r'(?P<message>.+)'
)
tempfile_suffix = '-'
defaults = {
'selector': 'source.ts, source.tsx'
}
def on_stderr(self, stderr):
# suppress warnings like "rule requires type information"
stderr = re.sub(
'Warning: .+\n', '', stderr)
if stderr:
self.notify_failure()
logger.error(stderr)
|
Update regex to include filename capture group.
|
Update regex to include filename capture group.
|
Python
|
mit
|
lavrton/SublimeLinter-contrib-tslint
|
import logging
import re
from SublimeLinter.lint import NodeLinter
logger = logging.getLogger('SublimeLinter.plugin.tslint')
class Tslint(NodeLinter):
cmd = 'tslint --format verbose ${file}'
regex = (
r'^(?:'
r'(ERROR:\s+\((?P<error>.*)\))|'
r'(WARNING:\s+\((?P<warning>.*)\))'
r')?'
r'.+?\[(?P<line>\d+), (?P<col>\d+)\]: '
r'(?P<message>.+)'
)
tempfile_suffix = '-'
defaults = {
'selector': 'source.ts, source.tsx'
}
def on_stderr(self, stderr):
# suppress warnings like "rule requires type information"
stderr = re.sub(
'Warning: .+\n', '', stderr)
if stderr:
self.notify_failure()
logger.error(stderr)
Update regex to include filename capture group.
|
import logging
import re
from SublimeLinter.lint import NodeLinter
logger = logging.getLogger('SublimeLinter.plugin.tslint')
class Tslint(NodeLinter):
cmd = 'tslint --format verbose ${file}'
regex = (
r'^(?:'
r'(ERROR:\s+\((?P<error>.*)\))|'
r'(WARNING:\s+\((?P<warning>.*)\))'
r')?'
r'\s+(?P<filename>.+?)'
r'\[(?P<line>\d+), (?P<col>\d+)\]: '
r'(?P<message>.+)'
)
tempfile_suffix = '-'
defaults = {
'selector': 'source.ts, source.tsx'
}
def on_stderr(self, stderr):
# suppress warnings like "rule requires type information"
stderr = re.sub(
'Warning: .+\n', '', stderr)
if stderr:
self.notify_failure()
logger.error(stderr)
|
<commit_before>import logging
import re
from SublimeLinter.lint import NodeLinter
logger = logging.getLogger('SublimeLinter.plugin.tslint')
class Tslint(NodeLinter):
cmd = 'tslint --format verbose ${file}'
regex = (
r'^(?:'
r'(ERROR:\s+\((?P<error>.*)\))|'
r'(WARNING:\s+\((?P<warning>.*)\))'
r')?'
r'.+?\[(?P<line>\d+), (?P<col>\d+)\]: '
r'(?P<message>.+)'
)
tempfile_suffix = '-'
defaults = {
'selector': 'source.ts, source.tsx'
}
def on_stderr(self, stderr):
# suppress warnings like "rule requires type information"
stderr = re.sub(
'Warning: .+\n', '', stderr)
if stderr:
self.notify_failure()
logger.error(stderr)
<commit_msg>Update regex to include filename capture group.<commit_after>
|
import logging
import re
from SublimeLinter.lint import NodeLinter
logger = logging.getLogger('SublimeLinter.plugin.tslint')
class Tslint(NodeLinter):
cmd = 'tslint --format verbose ${file}'
regex = (
r'^(?:'
r'(ERROR:\s+\((?P<error>.*)\))|'
r'(WARNING:\s+\((?P<warning>.*)\))'
r')?'
r'\s+(?P<filename>.+?)'
r'\[(?P<line>\d+), (?P<col>\d+)\]: '
r'(?P<message>.+)'
)
tempfile_suffix = '-'
defaults = {
'selector': 'source.ts, source.tsx'
}
def on_stderr(self, stderr):
# suppress warnings like "rule requires type information"
stderr = re.sub(
'Warning: .+\n', '', stderr)
if stderr:
self.notify_failure()
logger.error(stderr)
|
import logging
import re
from SublimeLinter.lint import NodeLinter
logger = logging.getLogger('SublimeLinter.plugin.tslint')
class Tslint(NodeLinter):
cmd = 'tslint --format verbose ${file}'
regex = (
r'^(?:'
r'(ERROR:\s+\((?P<error>.*)\))|'
r'(WARNING:\s+\((?P<warning>.*)\))'
r')?'
r'.+?\[(?P<line>\d+), (?P<col>\d+)\]: '
r'(?P<message>.+)'
)
tempfile_suffix = '-'
defaults = {
'selector': 'source.ts, source.tsx'
}
def on_stderr(self, stderr):
# suppress warnings like "rule requires type information"
stderr = re.sub(
'Warning: .+\n', '', stderr)
if stderr:
self.notify_failure()
logger.error(stderr)
Update regex to include filename capture group.import logging
import re
from SublimeLinter.lint import NodeLinter
logger = logging.getLogger('SublimeLinter.plugin.tslint')
class Tslint(NodeLinter):
cmd = 'tslint --format verbose ${file}'
regex = (
r'^(?:'
r'(ERROR:\s+\((?P<error>.*)\))|'
r'(WARNING:\s+\((?P<warning>.*)\))'
r')?'
r'\s+(?P<filename>.+?)'
r'\[(?P<line>\d+), (?P<col>\d+)\]: '
r'(?P<message>.+)'
)
tempfile_suffix = '-'
defaults = {
'selector': 'source.ts, source.tsx'
}
def on_stderr(self, stderr):
# suppress warnings like "rule requires type information"
stderr = re.sub(
'Warning: .+\n', '', stderr)
if stderr:
self.notify_failure()
logger.error(stderr)
|
<commit_before>import logging
import re
from SublimeLinter.lint import NodeLinter
logger = logging.getLogger('SublimeLinter.plugin.tslint')
class Tslint(NodeLinter):
cmd = 'tslint --format verbose ${file}'
regex = (
r'^(?:'
r'(ERROR:\s+\((?P<error>.*)\))|'
r'(WARNING:\s+\((?P<warning>.*)\))'
r')?'
r'.+?\[(?P<line>\d+), (?P<col>\d+)\]: '
r'(?P<message>.+)'
)
tempfile_suffix = '-'
defaults = {
'selector': 'source.ts, source.tsx'
}
def on_stderr(self, stderr):
# suppress warnings like "rule requires type information"
stderr = re.sub(
'Warning: .+\n', '', stderr)
if stderr:
self.notify_failure()
logger.error(stderr)
<commit_msg>Update regex to include filename capture group.<commit_after>import logging
import re
from SublimeLinter.lint import NodeLinter
logger = logging.getLogger('SublimeLinter.plugin.tslint')
class Tslint(NodeLinter):
cmd = 'tslint --format verbose ${file}'
regex = (
r'^(?:'
r'(ERROR:\s+\((?P<error>.*)\))|'
r'(WARNING:\s+\((?P<warning>.*)\))'
r')?'
r'\s+(?P<filename>.+?)'
r'\[(?P<line>\d+), (?P<col>\d+)\]: '
r'(?P<message>.+)'
)
tempfile_suffix = '-'
defaults = {
'selector': 'source.ts, source.tsx'
}
def on_stderr(self, stderr):
# suppress warnings like "rule requires type information"
stderr = re.sub(
'Warning: .+\n', '', stderr)
if stderr:
self.notify_failure()
logger.error(stderr)
|
3bf73c3a97762af08fafb36729e6e8ab024401e2
|
settings/heroku.py
|
settings/heroku.py
|
import dj_database_url
from .common import * # noqa
DATABASES = {
'default': dj_database_url.config(conn_max_age=500),
}
DEBUG = False
ALLOWED_HOSTS = ['.herokuapp.com']
|
import dj_database_url
from .common import * # noqa
DATABASES = {
'default': dj_database_url.config(conn_max_age=500),
}
DEBUG = False
ALLOWED_HOSTS = ['*']
|
Allow all hosts when on Heroku
|
Allow all hosts when on Heroku
|
Python
|
mit
|
smtchahal/url-shortener,smtchahal/url-shortener,smtchahal/url-shortener
|
import dj_database_url
from .common import * # noqa
DATABASES = {
'default': dj_database_url.config(conn_max_age=500),
}
DEBUG = False
ALLOWED_HOSTS = ['.herokuapp.com']
Allow all hosts when on Heroku
|
import dj_database_url
from .common import * # noqa
DATABASES = {
'default': dj_database_url.config(conn_max_age=500),
}
DEBUG = False
ALLOWED_HOSTS = ['*']
|
<commit_before>import dj_database_url
from .common import * # noqa
DATABASES = {
'default': dj_database_url.config(conn_max_age=500),
}
DEBUG = False
ALLOWED_HOSTS = ['.herokuapp.com']
<commit_msg>Allow all hosts when on Heroku<commit_after>
|
import dj_database_url
from .common import * # noqa
DATABASES = {
'default': dj_database_url.config(conn_max_age=500),
}
DEBUG = False
ALLOWED_HOSTS = ['*']
|
import dj_database_url
from .common import * # noqa
DATABASES = {
'default': dj_database_url.config(conn_max_age=500),
}
DEBUG = False
ALLOWED_HOSTS = ['.herokuapp.com']
Allow all hosts when on Herokuimport dj_database_url
from .common import * # noqa
DATABASES = {
'default': dj_database_url.config(conn_max_age=500),
}
DEBUG = False
ALLOWED_HOSTS = ['*']
|
<commit_before>import dj_database_url
from .common import * # noqa
DATABASES = {
'default': dj_database_url.config(conn_max_age=500),
}
DEBUG = False
ALLOWED_HOSTS = ['.herokuapp.com']
<commit_msg>Allow all hosts when on Heroku<commit_after>import dj_database_url
from .common import * # noqa
DATABASES = {
'default': dj_database_url.config(conn_max_age=500),
}
DEBUG = False
ALLOWED_HOSTS = ['*']
|
b7377196cdd05d9d6d481f7b93308189c4524c52
|
sfm/api/filters.py
|
sfm/api/filters.py
|
from django_filters import FilterSet, CharFilter, IsoDateTimeFilter
from ui.models import Warc, Seed, Harvest
from django_filters import Filter
from django_filters.fields import Lookup
class ListFilter(Filter):
def filter(self, qs, value):
return super(ListFilter, self).filter(qs, Lookup(value.split(u","), "in"))
class WarcFilter(FilterSet):
# Allows queries like /api/v1/warcs/?seedset=39c00280274a4db0b1cb5bfa4d527a1e
seedset = CharFilter(name="harvest__seed_set__seedset_id")
seed = ListFilter(name="harvest__seed_set__seeds__seed_id", distinct=True)
# TODO: This will need to be changed to use historical seeds once #54 is completed.
harvest_date_start = IsoDateTimeFilter(name="harvest__date_started", lookup_type='gte')
harvest_date_end = IsoDateTimeFilter(name="harvest__date_started", lookup_type='lte')
class Meta:
model = Warc
fields = ['seedset']
|
from django_filters import FilterSet, CharFilter, IsoDateTimeFilter
from ui.models import Warc, Seed, Harvest
from django_filters import Filter
from django_filters.fields import Lookup
class ListFilter(Filter):
def filter(self, qs, value):
return super(ListFilter, self).filter(qs, Lookup(value.split(u","), "in"))
class WarcFilter(FilterSet):
# Allows queries like /api/v1/warcs/?seedset=39c00280274a4db0b1cb5bfa4d527a1e
seedset = CharFilter(name="harvest__historical_seed_set__seedset_id")
seed = ListFilter(name="harvest__historical_seeds__seed_id", distinct=True)
harvest_date_start = IsoDateTimeFilter(name="harvest__date_started", lookup_type='gte')
harvest_date_end = IsoDateTimeFilter(name="harvest__date_started", lookup_type='lte')
class Meta:
model = Warc
fields = ['seedset']
|
Fix to take into account history in API queries.
|
Fix to take into account history in API queries.
|
Python
|
mit
|
gwu-libraries/sfm,gwu-libraries/sfm-ui,gwu-libraries/sfm,gwu-libraries/sfm,gwu-libraries/sfm-ui,gwu-libraries/sfm-ui,gwu-libraries/sfm-ui
|
from django_filters import FilterSet, CharFilter, IsoDateTimeFilter
from ui.models import Warc, Seed, Harvest
from django_filters import Filter
from django_filters.fields import Lookup
class ListFilter(Filter):
def filter(self, qs, value):
return super(ListFilter, self).filter(qs, Lookup(value.split(u","), "in"))
class WarcFilter(FilterSet):
# Allows queries like /api/v1/warcs/?seedset=39c00280274a4db0b1cb5bfa4d527a1e
seedset = CharFilter(name="harvest__seed_set__seedset_id")
seed = ListFilter(name="harvest__seed_set__seeds__seed_id", distinct=True)
# TODO: This will need to be changed to use historical seeds once #54 is completed.
harvest_date_start = IsoDateTimeFilter(name="harvest__date_started", lookup_type='gte')
harvest_date_end = IsoDateTimeFilter(name="harvest__date_started", lookup_type='lte')
class Meta:
model = Warc
fields = ['seedset']
Fix to take into account history in API queries.
|
from django_filters import FilterSet, CharFilter, IsoDateTimeFilter
from ui.models import Warc, Seed, Harvest
from django_filters import Filter
from django_filters.fields import Lookup
class ListFilter(Filter):
def filter(self, qs, value):
return super(ListFilter, self).filter(qs, Lookup(value.split(u","), "in"))
class WarcFilter(FilterSet):
# Allows queries like /api/v1/warcs/?seedset=39c00280274a4db0b1cb5bfa4d527a1e
seedset = CharFilter(name="harvest__historical_seed_set__seedset_id")
seed = ListFilter(name="harvest__historical_seeds__seed_id", distinct=True)
harvest_date_start = IsoDateTimeFilter(name="harvest__date_started", lookup_type='gte')
harvest_date_end = IsoDateTimeFilter(name="harvest__date_started", lookup_type='lte')
class Meta:
model = Warc
fields = ['seedset']
|
<commit_before>from django_filters import FilterSet, CharFilter, IsoDateTimeFilter
from ui.models import Warc, Seed, Harvest
from django_filters import Filter
from django_filters.fields import Lookup
class ListFilter(Filter):
def filter(self, qs, value):
return super(ListFilter, self).filter(qs, Lookup(value.split(u","), "in"))
class WarcFilter(FilterSet):
# Allows queries like /api/v1/warcs/?seedset=39c00280274a4db0b1cb5bfa4d527a1e
seedset = CharFilter(name="harvest__seed_set__seedset_id")
seed = ListFilter(name="harvest__seed_set__seeds__seed_id", distinct=True)
# TODO: This will need to be changed to use historical seeds once #54 is completed.
harvest_date_start = IsoDateTimeFilter(name="harvest__date_started", lookup_type='gte')
harvest_date_end = IsoDateTimeFilter(name="harvest__date_started", lookup_type='lte')
class Meta:
model = Warc
fields = ['seedset']
<commit_msg>Fix to take into account history in API queries.<commit_after>
|
from django_filters import FilterSet, CharFilter, IsoDateTimeFilter
from ui.models import Warc, Seed, Harvest
from django_filters import Filter
from django_filters.fields import Lookup
class ListFilter(Filter):
def filter(self, qs, value):
return super(ListFilter, self).filter(qs, Lookup(value.split(u","), "in"))
class WarcFilter(FilterSet):
# Allows queries like /api/v1/warcs/?seedset=39c00280274a4db0b1cb5bfa4d527a1e
seedset = CharFilter(name="harvest__historical_seed_set__seedset_id")
seed = ListFilter(name="harvest__historical_seeds__seed_id", distinct=True)
harvest_date_start = IsoDateTimeFilter(name="harvest__date_started", lookup_type='gte')
harvest_date_end = IsoDateTimeFilter(name="harvest__date_started", lookup_type='lte')
class Meta:
model = Warc
fields = ['seedset']
|
from django_filters import FilterSet, CharFilter, IsoDateTimeFilter
from ui.models import Warc, Seed, Harvest
from django_filters import Filter
from django_filters.fields import Lookup
class ListFilter(Filter):
def filter(self, qs, value):
return super(ListFilter, self).filter(qs, Lookup(value.split(u","), "in"))
class WarcFilter(FilterSet):
# Allows queries like /api/v1/warcs/?seedset=39c00280274a4db0b1cb5bfa4d527a1e
seedset = CharFilter(name="harvest__seed_set__seedset_id")
seed = ListFilter(name="harvest__seed_set__seeds__seed_id", distinct=True)
# TODO: This will need to be changed to use historical seeds once #54 is completed.
harvest_date_start = IsoDateTimeFilter(name="harvest__date_started", lookup_type='gte')
harvest_date_end = IsoDateTimeFilter(name="harvest__date_started", lookup_type='lte')
class Meta:
model = Warc
fields = ['seedset']
Fix to take into account history in API queries.from django_filters import FilterSet, CharFilter, IsoDateTimeFilter
from ui.models import Warc, Seed, Harvest
from django_filters import Filter
from django_filters.fields import Lookup
class ListFilter(Filter):
def filter(self, qs, value):
return super(ListFilter, self).filter(qs, Lookup(value.split(u","), "in"))
class WarcFilter(FilterSet):
# Allows queries like /api/v1/warcs/?seedset=39c00280274a4db0b1cb5bfa4d527a1e
seedset = CharFilter(name="harvest__historical_seed_set__seedset_id")
seed = ListFilter(name="harvest__historical_seeds__seed_id", distinct=True)
harvest_date_start = IsoDateTimeFilter(name="harvest__date_started", lookup_type='gte')
harvest_date_end = IsoDateTimeFilter(name="harvest__date_started", lookup_type='lte')
class Meta:
model = Warc
fields = ['seedset']
|
<commit_before>from django_filters import FilterSet, CharFilter, IsoDateTimeFilter
from ui.models import Warc, Seed, Harvest
from django_filters import Filter
from django_filters.fields import Lookup
class ListFilter(Filter):
def filter(self, qs, value):
return super(ListFilter, self).filter(qs, Lookup(value.split(u","), "in"))
class WarcFilter(FilterSet):
# Allows queries like /api/v1/warcs/?seedset=39c00280274a4db0b1cb5bfa4d527a1e
seedset = CharFilter(name="harvest__seed_set__seedset_id")
seed = ListFilter(name="harvest__seed_set__seeds__seed_id", distinct=True)
# TODO: This will need to be changed to use historical seeds once #54 is completed.
harvest_date_start = IsoDateTimeFilter(name="harvest__date_started", lookup_type='gte')
harvest_date_end = IsoDateTimeFilter(name="harvest__date_started", lookup_type='lte')
class Meta:
model = Warc
fields = ['seedset']
<commit_msg>Fix to take into account history in API queries.<commit_after>from django_filters import FilterSet, CharFilter, IsoDateTimeFilter
from ui.models import Warc, Seed, Harvest
from django_filters import Filter
from django_filters.fields import Lookup
class ListFilter(Filter):
def filter(self, qs, value):
return super(ListFilter, self).filter(qs, Lookup(value.split(u","), "in"))
class WarcFilter(FilterSet):
# Allows queries like /api/v1/warcs/?seedset=39c00280274a4db0b1cb5bfa4d527a1e
seedset = CharFilter(name="harvest__historical_seed_set__seedset_id")
seed = ListFilter(name="harvest__historical_seeds__seed_id", distinct=True)
harvest_date_start = IsoDateTimeFilter(name="harvest__date_started", lookup_type='gte')
harvest_date_end = IsoDateTimeFilter(name="harvest__date_started", lookup_type='lte')
class Meta:
model = Warc
fields = ['seedset']
|
b44345efada2a89423c89ec88a24f1dbe97ef562
|
viewer.py
|
viewer.py
|
# Nessus results viewing tools
#
# Developed by Felix Ingram, [email protected], @lllamaboy
# http://www.github.com/nccgroup/nessusviewer
#
# Released under AGPL. See LICENSE for more information
if __name__ == '__main__':
import wx
from controller import ViewerController
app = wx.App(0)
ViewerController()
app.MainLoop()
|
# Nessus results viewing tools
#
# Developed by Felix Ingram, [email protected], @lllamaboy
# http://www.github.com/nccgroup/nessusviewer
#
# Released under AGPL. See LICENSE for more information
if __name__ == '__main__':
import sys
try:
import wx
except ImportError:
print("""\
You need to install WXPython to use the viewer
http://wxpython.org/download.php
""")
sys.exit()
from controller import ViewerController
app = wx.App(0)
ViewerController()
app.MainLoop()
|
Add simple test for whether WX is installed. Display download link if not.
|
Add simple test for whether WX is installed. Display download link if not.
|
Python
|
agpl-3.0
|
nccgroup/lapith
|
# Nessus results viewing tools
#
# Developed by Felix Ingram, [email protected], @lllamaboy
# http://www.github.com/nccgroup/nessusviewer
#
# Released under AGPL. See LICENSE for more information
if __name__ == '__main__':
import wx
from controller import ViewerController
app = wx.App(0)
ViewerController()
app.MainLoop()
Add simple test for whether WX is installed. Display download link if not.
|
# Nessus results viewing tools
#
# Developed by Felix Ingram, [email protected], @lllamaboy
# http://www.github.com/nccgroup/nessusviewer
#
# Released under AGPL. See LICENSE for more information
if __name__ == '__main__':
import sys
try:
import wx
except ImportError:
print("""\
You need to install WXPython to use the viewer
http://wxpython.org/download.php
""")
sys.exit()
from controller import ViewerController
app = wx.App(0)
ViewerController()
app.MainLoop()
|
<commit_before># Nessus results viewing tools
#
# Developed by Felix Ingram, [email protected], @lllamaboy
# http://www.github.com/nccgroup/nessusviewer
#
# Released under AGPL. See LICENSE for more information
if __name__ == '__main__':
import wx
from controller import ViewerController
app = wx.App(0)
ViewerController()
app.MainLoop()
<commit_msg>Add simple test for whether WX is installed. Display download link if not.<commit_after>
|
# Nessus results viewing tools
#
# Developed by Felix Ingram, [email protected], @lllamaboy
# http://www.github.com/nccgroup/nessusviewer
#
# Released under AGPL. See LICENSE for more information
if __name__ == '__main__':
import sys
try:
import wx
except ImportError:
print("""\
You need to install WXPython to use the viewer
http://wxpython.org/download.php
""")
sys.exit()
from controller import ViewerController
app = wx.App(0)
ViewerController()
app.MainLoop()
|
# Nessus results viewing tools
#
# Developed by Felix Ingram, [email protected], @lllamaboy
# http://www.github.com/nccgroup/nessusviewer
#
# Released under AGPL. See LICENSE for more information
if __name__ == '__main__':
import wx
from controller import ViewerController
app = wx.App(0)
ViewerController()
app.MainLoop()
Add simple test for whether WX is installed. Display download link if not.# Nessus results viewing tools
#
# Developed by Felix Ingram, [email protected], @lllamaboy
# http://www.github.com/nccgroup/nessusviewer
#
# Released under AGPL. See LICENSE for more information
if __name__ == '__main__':
import sys
try:
import wx
except ImportError:
print("""\
You need to install WXPython to use the viewer
http://wxpython.org/download.php
""")
sys.exit()
from controller import ViewerController
app = wx.App(0)
ViewerController()
app.MainLoop()
|
<commit_before># Nessus results viewing tools
#
# Developed by Felix Ingram, [email protected], @lllamaboy
# http://www.github.com/nccgroup/nessusviewer
#
# Released under AGPL. See LICENSE for more information
if __name__ == '__main__':
import wx
from controller import ViewerController
app = wx.App(0)
ViewerController()
app.MainLoop()
<commit_msg>Add simple test for whether WX is installed. Display download link if not.<commit_after># Nessus results viewing tools
#
# Developed by Felix Ingram, [email protected], @lllamaboy
# http://www.github.com/nccgroup/nessusviewer
#
# Released under AGPL. See LICENSE for more information
if __name__ == '__main__':
import sys
try:
import wx
except ImportError:
print("""\
You need to install WXPython to use the viewer
http://wxpython.org/download.php
""")
sys.exit()
from controller import ViewerController
app = wx.App(0)
ViewerController()
app.MainLoop()
|
3046eaf265d015c2257efa8066a04c26ddd4448e
|
search.py
|
search.py
|
import io
import getopt
import sys
import pickle
def usage():
print("usage: " + sys.argv[0] + " -d dictionary-file -p postings-file -q file-of-queries -o output-file-of-results")
if __name__ == '__main__':
dict_file = postings_file = query_file = output_file = None
try:
opts, args = getopt.getopt(sys.argv[1:], 'd:p:q:o:')
except getopt.GetoptError as err:
usage()
sys.exit(2)
for o, a in opts:
if o == '-d':
dict_file = a
elif o == '-p':
postings_file = a
elif o == '-q':
query_file = a
elif o == '-o':
output_file = a
else:
assert False, "unhandled option"
if dict_file == None or postings_file == None or query_file == None or output_file == None:
usage()
sys.exit(2)
with io.open(dict_file, 'rb') as f:
dictionary = pickle.load(f)
with io.open(postings_file, 'rb') as f:
postings = pickle.load(f)
skip_pointers = pickle.load(f)
|
import io
import getopt
import sys
import pickle
def usage():
print("usage: " + sys.argv[0] + " -d dictionary-file -p postings-file -q file-of-queries -o output-file-of-results")
if __name__ == '__main__':
dict_file = postings_file = query_file = output_file = None
try:
opts, args = getopt.getopt(sys.argv[1:], 'd:p:q:o:')
except getopt.GetoptError as err:
usage()
sys.exit(2)
for o, a in opts:
if o == '-d':
dict_file = a
elif o == '-p':
postings_file = a
elif o == '-q':
query_file = a
elif o == '-o':
output_file = a
else:
assert False, "unhandled option"
if dict_file == None or postings_file == None or query_file == None or output_file == None:
usage()
sys.exit(2)
with io.open(dict_file, 'rb') as f:
dictionary = pickle.load(f)
# Implement seeking and reading don't read entirely
with io.open(postings_file, 'rb') as f:
postings = pickle.load(f)
skip_pointers = pickle.load(f)
|
Add todo for seeking and reading
|
Add todo for seeking and reading
|
Python
|
mit
|
ikaruswill/boolean-retrieval,ikaruswill/vector-space-model
|
import io
import getopt
import sys
import pickle
def usage():
print("usage: " + sys.argv[0] + " -d dictionary-file -p postings-file -q file-of-queries -o output-file-of-results")
if __name__ == '__main__':
dict_file = postings_file = query_file = output_file = None
try:
opts, args = getopt.getopt(sys.argv[1:], 'd:p:q:o:')
except getopt.GetoptError as err:
usage()
sys.exit(2)
for o, a in opts:
if o == '-d':
dict_file = a
elif o == '-p':
postings_file = a
elif o == '-q':
query_file = a
elif o == '-o':
output_file = a
else:
assert False, "unhandled option"
if dict_file == None or postings_file == None or query_file == None or output_file == None:
usage()
sys.exit(2)
with io.open(dict_file, 'rb') as f:
dictionary = pickle.load(f)
with io.open(postings_file, 'rb') as f:
postings = pickle.load(f)
skip_pointers = pickle.load(f)
Add todo for seeking and reading
|
import io
import getopt
import sys
import pickle
def usage():
print("usage: " + sys.argv[0] + " -d dictionary-file -p postings-file -q file-of-queries -o output-file-of-results")
if __name__ == '__main__':
dict_file = postings_file = query_file = output_file = None
try:
opts, args = getopt.getopt(sys.argv[1:], 'd:p:q:o:')
except getopt.GetoptError as err:
usage()
sys.exit(2)
for o, a in opts:
if o == '-d':
dict_file = a
elif o == '-p':
postings_file = a
elif o == '-q':
query_file = a
elif o == '-o':
output_file = a
else:
assert False, "unhandled option"
if dict_file == None or postings_file == None or query_file == None or output_file == None:
usage()
sys.exit(2)
with io.open(dict_file, 'rb') as f:
dictionary = pickle.load(f)
# Implement seeking and reading don't read entirely
with io.open(postings_file, 'rb') as f:
postings = pickle.load(f)
skip_pointers = pickle.load(f)
|
<commit_before>import io
import getopt
import sys
import pickle
def usage():
print("usage: " + sys.argv[0] + " -d dictionary-file -p postings-file -q file-of-queries -o output-file-of-results")
if __name__ == '__main__':
dict_file = postings_file = query_file = output_file = None
try:
opts, args = getopt.getopt(sys.argv[1:], 'd:p:q:o:')
except getopt.GetoptError as err:
usage()
sys.exit(2)
for o, a in opts:
if o == '-d':
dict_file = a
elif o == '-p':
postings_file = a
elif o == '-q':
query_file = a
elif o == '-o':
output_file = a
else:
assert False, "unhandled option"
if dict_file == None or postings_file == None or query_file == None or output_file == None:
usage()
sys.exit(2)
with io.open(dict_file, 'rb') as f:
dictionary = pickle.load(f)
with io.open(postings_file, 'rb') as f:
postings = pickle.load(f)
skip_pointers = pickle.load(f)
<commit_msg>Add todo for seeking and reading<commit_after>
|
import io
import getopt
import sys
import pickle
def usage():
print("usage: " + sys.argv[0] + " -d dictionary-file -p postings-file -q file-of-queries -o output-file-of-results")
if __name__ == '__main__':
dict_file = postings_file = query_file = output_file = None
try:
opts, args = getopt.getopt(sys.argv[1:], 'd:p:q:o:')
except getopt.GetoptError as err:
usage()
sys.exit(2)
for o, a in opts:
if o == '-d':
dict_file = a
elif o == '-p':
postings_file = a
elif o == '-q':
query_file = a
elif o == '-o':
output_file = a
else:
assert False, "unhandled option"
if dict_file == None or postings_file == None or query_file == None or output_file == None:
usage()
sys.exit(2)
with io.open(dict_file, 'rb') as f:
dictionary = pickle.load(f)
# Implement seeking and reading don't read entirely
with io.open(postings_file, 'rb') as f:
postings = pickle.load(f)
skip_pointers = pickle.load(f)
|
import io
import getopt
import sys
import pickle
def usage():
print("usage: " + sys.argv[0] + " -d dictionary-file -p postings-file -q file-of-queries -o output-file-of-results")
if __name__ == '__main__':
dict_file = postings_file = query_file = output_file = None
try:
opts, args = getopt.getopt(sys.argv[1:], 'd:p:q:o:')
except getopt.GetoptError as err:
usage()
sys.exit(2)
for o, a in opts:
if o == '-d':
dict_file = a
elif o == '-p':
postings_file = a
elif o == '-q':
query_file = a
elif o == '-o':
output_file = a
else:
assert False, "unhandled option"
if dict_file == None or postings_file == None or query_file == None or output_file == None:
usage()
sys.exit(2)
with io.open(dict_file, 'rb') as f:
dictionary = pickle.load(f)
with io.open(postings_file, 'rb') as f:
postings = pickle.load(f)
skip_pointers = pickle.load(f)
Add todo for seeking and readingimport io
import getopt
import sys
import pickle
def usage():
print("usage: " + sys.argv[0] + " -d dictionary-file -p postings-file -q file-of-queries -o output-file-of-results")
if __name__ == '__main__':
dict_file = postings_file = query_file = output_file = None
try:
opts, args = getopt.getopt(sys.argv[1:], 'd:p:q:o:')
except getopt.GetoptError as err:
usage()
sys.exit(2)
for o, a in opts:
if o == '-d':
dict_file = a
elif o == '-p':
postings_file = a
elif o == '-q':
query_file = a
elif o == '-o':
output_file = a
else:
assert False, "unhandled option"
if dict_file == None or postings_file == None or query_file == None or output_file == None:
usage()
sys.exit(2)
with io.open(dict_file, 'rb') as f:
dictionary = pickle.load(f)
# Implement seeking and reading don't read entirely
with io.open(postings_file, 'rb') as f:
postings = pickle.load(f)
skip_pointers = pickle.load(f)
|
<commit_before>import io
import getopt
import sys
import pickle
def usage():
print("usage: " + sys.argv[0] + " -d dictionary-file -p postings-file -q file-of-queries -o output-file-of-results")
if __name__ == '__main__':
dict_file = postings_file = query_file = output_file = None
try:
opts, args = getopt.getopt(sys.argv[1:], 'd:p:q:o:')
except getopt.GetoptError as err:
usage()
sys.exit(2)
for o, a in opts:
if o == '-d':
dict_file = a
elif o == '-p':
postings_file = a
elif o == '-q':
query_file = a
elif o == '-o':
output_file = a
else:
assert False, "unhandled option"
if dict_file == None or postings_file == None or query_file == None or output_file == None:
usage()
sys.exit(2)
with io.open(dict_file, 'rb') as f:
dictionary = pickle.load(f)
with io.open(postings_file, 'rb') as f:
postings = pickle.load(f)
skip_pointers = pickle.load(f)
<commit_msg>Add todo for seeking and reading<commit_after>import io
import getopt
import sys
import pickle
def usage():
print("usage: " + sys.argv[0] + " -d dictionary-file -p postings-file -q file-of-queries -o output-file-of-results")
if __name__ == '__main__':
dict_file = postings_file = query_file = output_file = None
try:
opts, args = getopt.getopt(sys.argv[1:], 'd:p:q:o:')
except getopt.GetoptError as err:
usage()
sys.exit(2)
for o, a in opts:
if o == '-d':
dict_file = a
elif o == '-p':
postings_file = a
elif o == '-q':
query_file = a
elif o == '-o':
output_file = a
else:
assert False, "unhandled option"
if dict_file == None or postings_file == None or query_file == None or output_file == None:
usage()
sys.exit(2)
with io.open(dict_file, 'rb') as f:
dictionary = pickle.load(f)
# Implement seeking and reading don't read entirely
with io.open(postings_file, 'rb') as f:
postings = pickle.load(f)
skip_pointers = pickle.load(f)
|
c259320c1108ed1012266f1bf8d49caf113af4e9
|
dsub/_dsub_version.py
|
dsub/_dsub_version.py
|
# Copyright 2017 Google Inc. All Rights Reserved.
#
# 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.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
The version should follow formatting requirements specified in PEP-440.
- https://www.python.org/dev/peps/pep-0440
A typical release sequence will be versioned as:
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
DSUB_VERSION = '0.4.1'
|
# Copyright 2017 Google Inc. All Rights Reserved.
#
# 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.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
The version should follow formatting requirements specified in PEP-440.
- https://www.python.org/dev/peps/pep-0440
A typical release sequence will be versioned as:
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
DSUB_VERSION = '0.4.2.dev0'
|
Update dsub version to 0.4.2.dev0
|
Update dsub version to 0.4.2.dev0
PiperOrigin-RevId: 328753098
|
Python
|
apache-2.0
|
DataBiosphere/dsub,DataBiosphere/dsub
|
# Copyright 2017 Google Inc. All Rights Reserved.
#
# 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.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
The version should follow formatting requirements specified in PEP-440.
- https://www.python.org/dev/peps/pep-0440
A typical release sequence will be versioned as:
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
DSUB_VERSION = '0.4.1'
Update dsub version to 0.4.2.dev0
PiperOrigin-RevId: 328753098
|
# Copyright 2017 Google Inc. All Rights Reserved.
#
# 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.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
The version should follow formatting requirements specified in PEP-440.
- https://www.python.org/dev/peps/pep-0440
A typical release sequence will be versioned as:
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
DSUB_VERSION = '0.4.2.dev0'
|
<commit_before># Copyright 2017 Google Inc. All Rights Reserved.
#
# 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.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
The version should follow formatting requirements specified in PEP-440.
- https://www.python.org/dev/peps/pep-0440
A typical release sequence will be versioned as:
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
DSUB_VERSION = '0.4.1'
<commit_msg>Update dsub version to 0.4.2.dev0
PiperOrigin-RevId: 328753098<commit_after>
|
# Copyright 2017 Google Inc. All Rights Reserved.
#
# 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.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
The version should follow formatting requirements specified in PEP-440.
- https://www.python.org/dev/peps/pep-0440
A typical release sequence will be versioned as:
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
DSUB_VERSION = '0.4.2.dev0'
|
# Copyright 2017 Google Inc. All Rights Reserved.
#
# 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.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
The version should follow formatting requirements specified in PEP-440.
- https://www.python.org/dev/peps/pep-0440
A typical release sequence will be versioned as:
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
DSUB_VERSION = '0.4.1'
Update dsub version to 0.4.2.dev0
PiperOrigin-RevId: 328753098# Copyright 2017 Google Inc. All Rights Reserved.
#
# 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.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
The version should follow formatting requirements specified in PEP-440.
- https://www.python.org/dev/peps/pep-0440
A typical release sequence will be versioned as:
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
DSUB_VERSION = '0.4.2.dev0'
|
<commit_before># Copyright 2017 Google Inc. All Rights Reserved.
#
# 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.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
The version should follow formatting requirements specified in PEP-440.
- https://www.python.org/dev/peps/pep-0440
A typical release sequence will be versioned as:
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
DSUB_VERSION = '0.4.1'
<commit_msg>Update dsub version to 0.4.2.dev0
PiperOrigin-RevId: 328753098<commit_after># Copyright 2017 Google Inc. All Rights Reserved.
#
# 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.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
The version should follow formatting requirements specified in PEP-440.
- https://www.python.org/dev/peps/pep-0440
A typical release sequence will be versioned as:
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
DSUB_VERSION = '0.4.2.dev0'
|
510ab1cd5c39168cb64c733b41f37d3745812782
|
src/integrate_tool.py
|
src/integrate_tool.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from bioblend import galaxy
from bioblend import toolshed
if __name__ == '__main__':
gi_url = "http://172.21.23.6:8080/"
ts_url = "http://172.21.23.6:9009/"
name = "qiime"
owner = "iuc"
tool_panel_section_id = "qiime_rRNA_taxonomic_assignation"
gi = galaxy.GalaxyInstance(url=gi_url, key='8a099e97b0a83c73ead9f5b0fe19f4be')
ts = toolshed.ToolShedInstance(url=ts_url)
changeset_revision = str(ts.repositories.get_ordered_installable_revisions(name,
owner)[-1])
gi.toolShed.install_repository_revision(ts_url, name, owner, changeset_revision,
install_tool_dependencies=True, install_repository_dependencies=False,
tool_panel_section_id=tool_panel_section_id)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from bioblend import galaxy
from bioblend import toolshed
if __name__ == '__main__':
gi_url = "http://172.21.23.6:8080/"
ts_url = "http://172.21.23.6:9009/"
name = "qiime"
owner = "iuc"
tool_panel_section_id = "qiime_rRNA_taxonomic_assignation"
gi = galaxy.GalaxyInstance(url=gi_url, key='8a099e97b0a83c73ead9f5b0fe19f4be')
ts = toolshed.ToolShedInstance(url=ts_url)
changeset_revision = str(ts.repositories.get_ordered_installable_revisions(name,
owner)[-1])
gi.toolShed.install_repository_revision(ts_url, name, owner, changeset_revision,
install_tool_dependencies=True, install_repository_dependencies=True,
tool_panel_section_id=tool_panel_section_id)
|
Add installation of repository dependencies for tools
|
Add installation of repository dependencies for tools
|
Python
|
apache-2.0
|
ASaiM/framework,ASaiM/framework
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from bioblend import galaxy
from bioblend import toolshed
if __name__ == '__main__':
gi_url = "http://172.21.23.6:8080/"
ts_url = "http://172.21.23.6:9009/"
name = "qiime"
owner = "iuc"
tool_panel_section_id = "qiime_rRNA_taxonomic_assignation"
gi = galaxy.GalaxyInstance(url=gi_url, key='8a099e97b0a83c73ead9f5b0fe19f4be')
ts = toolshed.ToolShedInstance(url=ts_url)
changeset_revision = str(ts.repositories.get_ordered_installable_revisions(name,
owner)[-1])
gi.toolShed.install_repository_revision(ts_url, name, owner, changeset_revision,
install_tool_dependencies=True, install_repository_dependencies=False,
tool_panel_section_id=tool_panel_section_id)
Add installation of repository dependencies for tools
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from bioblend import galaxy
from bioblend import toolshed
if __name__ == '__main__':
gi_url = "http://172.21.23.6:8080/"
ts_url = "http://172.21.23.6:9009/"
name = "qiime"
owner = "iuc"
tool_panel_section_id = "qiime_rRNA_taxonomic_assignation"
gi = galaxy.GalaxyInstance(url=gi_url, key='8a099e97b0a83c73ead9f5b0fe19f4be')
ts = toolshed.ToolShedInstance(url=ts_url)
changeset_revision = str(ts.repositories.get_ordered_installable_revisions(name,
owner)[-1])
gi.toolShed.install_repository_revision(ts_url, name, owner, changeset_revision,
install_tool_dependencies=True, install_repository_dependencies=True,
tool_panel_section_id=tool_panel_section_id)
|
<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from bioblend import galaxy
from bioblend import toolshed
if __name__ == '__main__':
gi_url = "http://172.21.23.6:8080/"
ts_url = "http://172.21.23.6:9009/"
name = "qiime"
owner = "iuc"
tool_panel_section_id = "qiime_rRNA_taxonomic_assignation"
gi = galaxy.GalaxyInstance(url=gi_url, key='8a099e97b0a83c73ead9f5b0fe19f4be')
ts = toolshed.ToolShedInstance(url=ts_url)
changeset_revision = str(ts.repositories.get_ordered_installable_revisions(name,
owner)[-1])
gi.toolShed.install_repository_revision(ts_url, name, owner, changeset_revision,
install_tool_dependencies=True, install_repository_dependencies=False,
tool_panel_section_id=tool_panel_section_id)
<commit_msg>Add installation of repository dependencies for tools<commit_after>
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from bioblend import galaxy
from bioblend import toolshed
if __name__ == '__main__':
gi_url = "http://172.21.23.6:8080/"
ts_url = "http://172.21.23.6:9009/"
name = "qiime"
owner = "iuc"
tool_panel_section_id = "qiime_rRNA_taxonomic_assignation"
gi = galaxy.GalaxyInstance(url=gi_url, key='8a099e97b0a83c73ead9f5b0fe19f4be')
ts = toolshed.ToolShedInstance(url=ts_url)
changeset_revision = str(ts.repositories.get_ordered_installable_revisions(name,
owner)[-1])
gi.toolShed.install_repository_revision(ts_url, name, owner, changeset_revision,
install_tool_dependencies=True, install_repository_dependencies=True,
tool_panel_section_id=tool_panel_section_id)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from bioblend import galaxy
from bioblend import toolshed
if __name__ == '__main__':
gi_url = "http://172.21.23.6:8080/"
ts_url = "http://172.21.23.6:9009/"
name = "qiime"
owner = "iuc"
tool_panel_section_id = "qiime_rRNA_taxonomic_assignation"
gi = galaxy.GalaxyInstance(url=gi_url, key='8a099e97b0a83c73ead9f5b0fe19f4be')
ts = toolshed.ToolShedInstance(url=ts_url)
changeset_revision = str(ts.repositories.get_ordered_installable_revisions(name,
owner)[-1])
gi.toolShed.install_repository_revision(ts_url, name, owner, changeset_revision,
install_tool_dependencies=True, install_repository_dependencies=False,
tool_panel_section_id=tool_panel_section_id)
Add installation of repository dependencies for tools#!/usr/bin/env python
# -*- coding: utf-8 -*-
from bioblend import galaxy
from bioblend import toolshed
if __name__ == '__main__':
gi_url = "http://172.21.23.6:8080/"
ts_url = "http://172.21.23.6:9009/"
name = "qiime"
owner = "iuc"
tool_panel_section_id = "qiime_rRNA_taxonomic_assignation"
gi = galaxy.GalaxyInstance(url=gi_url, key='8a099e97b0a83c73ead9f5b0fe19f4be')
ts = toolshed.ToolShedInstance(url=ts_url)
changeset_revision = str(ts.repositories.get_ordered_installable_revisions(name,
owner)[-1])
gi.toolShed.install_repository_revision(ts_url, name, owner, changeset_revision,
install_tool_dependencies=True, install_repository_dependencies=True,
tool_panel_section_id=tool_panel_section_id)
|
<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from bioblend import galaxy
from bioblend import toolshed
if __name__ == '__main__':
gi_url = "http://172.21.23.6:8080/"
ts_url = "http://172.21.23.6:9009/"
name = "qiime"
owner = "iuc"
tool_panel_section_id = "qiime_rRNA_taxonomic_assignation"
gi = galaxy.GalaxyInstance(url=gi_url, key='8a099e97b0a83c73ead9f5b0fe19f4be')
ts = toolshed.ToolShedInstance(url=ts_url)
changeset_revision = str(ts.repositories.get_ordered_installable_revisions(name,
owner)[-1])
gi.toolShed.install_repository_revision(ts_url, name, owner, changeset_revision,
install_tool_dependencies=True, install_repository_dependencies=False,
tool_panel_section_id=tool_panel_section_id)
<commit_msg>Add installation of repository dependencies for tools<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from bioblend import galaxy
from bioblend import toolshed
if __name__ == '__main__':
gi_url = "http://172.21.23.6:8080/"
ts_url = "http://172.21.23.6:9009/"
name = "qiime"
owner = "iuc"
tool_panel_section_id = "qiime_rRNA_taxonomic_assignation"
gi = galaxy.GalaxyInstance(url=gi_url, key='8a099e97b0a83c73ead9f5b0fe19f4be')
ts = toolshed.ToolShedInstance(url=ts_url)
changeset_revision = str(ts.repositories.get_ordered_installable_revisions(name,
owner)[-1])
gi.toolShed.install_repository_revision(ts_url, name, owner, changeset_revision,
install_tool_dependencies=True, install_repository_dependencies=True,
tool_panel_section_id=tool_panel_section_id)
|
36d79bd59282f9f1d2ba948cbaf0401f851b2d0a
|
rtwilio/outgoing.py
|
rtwilio/outgoing.py
|
import pprint
import logging
import datetime
from twilio.rest import TwilioRestClient
from rapidsms.backends.base import BackendBase
logger = logging.getLogger(__name__)
class TwilioBackend(BackendBase):
"""A RapidSMS backend for Twilio (http://www.twilio.com/)."""
def configure(self, config=None, **kwargs):
self.config = config
self.client = TwilioRestClient(self.config['account_sid'],
self.config['auth_token'])
def prepare_message(self, id_, text, identities, context):
encoding = self.config.get('encoding', 'ascii')
encoding_errors = self.config.get('encoding_errors', 'ignore')
data = {
'from_': self.config['number'],
'body': text.encode(encoding, encoding_errors),
}
if 'callback' in self.config:
data['status_callback'] = self.config['callback']
return data
def send(self, id_, text, identities, context={}):
logger.debug('Sending message: %s' % text)
data = self.prepare_message(id_, text, identities, context)
for identity in identities:
data['to'] = identity
self.debug('POST data: %s' % pprint.pformat(data))
try:
self.client.sms.messages.create(**data)
except Exception:
logger.exception("Failed to create Twilio message")
raise
|
import pprint
import logging
import datetime
from twilio.rest import TwilioRestClient
from rapidsms.backends.base import BackendBase
logger = logging.getLogger(__name__)
class TwilioBackend(BackendBase):
"""A RapidSMS backend for Twilio (http://www.twilio.com/)."""
def configure(self, config=None, **kwargs):
self.config = config
self.client = TwilioRestClient(self.config['account_sid'],
self.config['auth_token'])
def prepare_message(self, id_, text, identities, context):
encoding = self.config.get('encoding', 'ascii')
encoding_errors = self.config.get('encoding_errors', 'ignore')
data = {
'from_': self.config['number'],
'body': text.encode(encoding, encoding_errors),
}
if 'callback' in self.config:
data['status_callback'] = self.config['callback']
return data
def send(self, id_, text, identities, context={}):
logger.debug('Sending message: %s' % text)
data = self.prepare_message(id_, text, identities, context)
for identity in identities:
data['to'] = identity
logger.debug('POST data: %s' % pprint.pformat(data))
try:
self.client.sms.messages.create(**data)
except Exception:
logger.exception("Failed to create Twilio message")
raise
|
Remove self.debug as LoggerMixin was removed from new versions of rapidsms.
|
Remove self.debug as LoggerMixin was removed from new versions of rapidsms.
|
Python
|
bsd-3-clause
|
caktus/rapidsms-twilio
|
import pprint
import logging
import datetime
from twilio.rest import TwilioRestClient
from rapidsms.backends.base import BackendBase
logger = logging.getLogger(__name__)
class TwilioBackend(BackendBase):
"""A RapidSMS backend for Twilio (http://www.twilio.com/)."""
def configure(self, config=None, **kwargs):
self.config = config
self.client = TwilioRestClient(self.config['account_sid'],
self.config['auth_token'])
def prepare_message(self, id_, text, identities, context):
encoding = self.config.get('encoding', 'ascii')
encoding_errors = self.config.get('encoding_errors', 'ignore')
data = {
'from_': self.config['number'],
'body': text.encode(encoding, encoding_errors),
}
if 'callback' in self.config:
data['status_callback'] = self.config['callback']
return data
def send(self, id_, text, identities, context={}):
logger.debug('Sending message: %s' % text)
data = self.prepare_message(id_, text, identities, context)
for identity in identities:
data['to'] = identity
self.debug('POST data: %s' % pprint.pformat(data))
try:
self.client.sms.messages.create(**data)
except Exception:
logger.exception("Failed to create Twilio message")
raise
Remove self.debug as LoggerMixin was removed from new versions of rapidsms.
|
import pprint
import logging
import datetime
from twilio.rest import TwilioRestClient
from rapidsms.backends.base import BackendBase
logger = logging.getLogger(__name__)
class TwilioBackend(BackendBase):
"""A RapidSMS backend for Twilio (http://www.twilio.com/)."""
def configure(self, config=None, **kwargs):
self.config = config
self.client = TwilioRestClient(self.config['account_sid'],
self.config['auth_token'])
def prepare_message(self, id_, text, identities, context):
encoding = self.config.get('encoding', 'ascii')
encoding_errors = self.config.get('encoding_errors', 'ignore')
data = {
'from_': self.config['number'],
'body': text.encode(encoding, encoding_errors),
}
if 'callback' in self.config:
data['status_callback'] = self.config['callback']
return data
def send(self, id_, text, identities, context={}):
logger.debug('Sending message: %s' % text)
data = self.prepare_message(id_, text, identities, context)
for identity in identities:
data['to'] = identity
logger.debug('POST data: %s' % pprint.pformat(data))
try:
self.client.sms.messages.create(**data)
except Exception:
logger.exception("Failed to create Twilio message")
raise
|
<commit_before>import pprint
import logging
import datetime
from twilio.rest import TwilioRestClient
from rapidsms.backends.base import BackendBase
logger = logging.getLogger(__name__)
class TwilioBackend(BackendBase):
"""A RapidSMS backend for Twilio (http://www.twilio.com/)."""
def configure(self, config=None, **kwargs):
self.config = config
self.client = TwilioRestClient(self.config['account_sid'],
self.config['auth_token'])
def prepare_message(self, id_, text, identities, context):
encoding = self.config.get('encoding', 'ascii')
encoding_errors = self.config.get('encoding_errors', 'ignore')
data = {
'from_': self.config['number'],
'body': text.encode(encoding, encoding_errors),
}
if 'callback' in self.config:
data['status_callback'] = self.config['callback']
return data
def send(self, id_, text, identities, context={}):
logger.debug('Sending message: %s' % text)
data = self.prepare_message(id_, text, identities, context)
for identity in identities:
data['to'] = identity
self.debug('POST data: %s' % pprint.pformat(data))
try:
self.client.sms.messages.create(**data)
except Exception:
logger.exception("Failed to create Twilio message")
raise
<commit_msg>Remove self.debug as LoggerMixin was removed from new versions of rapidsms.<commit_after>
|
import pprint
import logging
import datetime
from twilio.rest import TwilioRestClient
from rapidsms.backends.base import BackendBase
logger = logging.getLogger(__name__)
class TwilioBackend(BackendBase):
"""A RapidSMS backend for Twilio (http://www.twilio.com/)."""
def configure(self, config=None, **kwargs):
self.config = config
self.client = TwilioRestClient(self.config['account_sid'],
self.config['auth_token'])
def prepare_message(self, id_, text, identities, context):
encoding = self.config.get('encoding', 'ascii')
encoding_errors = self.config.get('encoding_errors', 'ignore')
data = {
'from_': self.config['number'],
'body': text.encode(encoding, encoding_errors),
}
if 'callback' in self.config:
data['status_callback'] = self.config['callback']
return data
def send(self, id_, text, identities, context={}):
logger.debug('Sending message: %s' % text)
data = self.prepare_message(id_, text, identities, context)
for identity in identities:
data['to'] = identity
logger.debug('POST data: %s' % pprint.pformat(data))
try:
self.client.sms.messages.create(**data)
except Exception:
logger.exception("Failed to create Twilio message")
raise
|
import pprint
import logging
import datetime
from twilio.rest import TwilioRestClient
from rapidsms.backends.base import BackendBase
logger = logging.getLogger(__name__)
class TwilioBackend(BackendBase):
"""A RapidSMS backend for Twilio (http://www.twilio.com/)."""
def configure(self, config=None, **kwargs):
self.config = config
self.client = TwilioRestClient(self.config['account_sid'],
self.config['auth_token'])
def prepare_message(self, id_, text, identities, context):
encoding = self.config.get('encoding', 'ascii')
encoding_errors = self.config.get('encoding_errors', 'ignore')
data = {
'from_': self.config['number'],
'body': text.encode(encoding, encoding_errors),
}
if 'callback' in self.config:
data['status_callback'] = self.config['callback']
return data
def send(self, id_, text, identities, context={}):
logger.debug('Sending message: %s' % text)
data = self.prepare_message(id_, text, identities, context)
for identity in identities:
data['to'] = identity
self.debug('POST data: %s' % pprint.pformat(data))
try:
self.client.sms.messages.create(**data)
except Exception:
logger.exception("Failed to create Twilio message")
raise
Remove self.debug as LoggerMixin was removed from new versions of rapidsms.import pprint
import logging
import datetime
from twilio.rest import TwilioRestClient
from rapidsms.backends.base import BackendBase
logger = logging.getLogger(__name__)
class TwilioBackend(BackendBase):
"""A RapidSMS backend for Twilio (http://www.twilio.com/)."""
def configure(self, config=None, **kwargs):
self.config = config
self.client = TwilioRestClient(self.config['account_sid'],
self.config['auth_token'])
def prepare_message(self, id_, text, identities, context):
encoding = self.config.get('encoding', 'ascii')
encoding_errors = self.config.get('encoding_errors', 'ignore')
data = {
'from_': self.config['number'],
'body': text.encode(encoding, encoding_errors),
}
if 'callback' in self.config:
data['status_callback'] = self.config['callback']
return data
def send(self, id_, text, identities, context={}):
logger.debug('Sending message: %s' % text)
data = self.prepare_message(id_, text, identities, context)
for identity in identities:
data['to'] = identity
logger.debug('POST data: %s' % pprint.pformat(data))
try:
self.client.sms.messages.create(**data)
except Exception:
logger.exception("Failed to create Twilio message")
raise
|
<commit_before>import pprint
import logging
import datetime
from twilio.rest import TwilioRestClient
from rapidsms.backends.base import BackendBase
logger = logging.getLogger(__name__)
class TwilioBackend(BackendBase):
"""A RapidSMS backend for Twilio (http://www.twilio.com/)."""
def configure(self, config=None, **kwargs):
self.config = config
self.client = TwilioRestClient(self.config['account_sid'],
self.config['auth_token'])
def prepare_message(self, id_, text, identities, context):
encoding = self.config.get('encoding', 'ascii')
encoding_errors = self.config.get('encoding_errors', 'ignore')
data = {
'from_': self.config['number'],
'body': text.encode(encoding, encoding_errors),
}
if 'callback' in self.config:
data['status_callback'] = self.config['callback']
return data
def send(self, id_, text, identities, context={}):
logger.debug('Sending message: %s' % text)
data = self.prepare_message(id_, text, identities, context)
for identity in identities:
data['to'] = identity
self.debug('POST data: %s' % pprint.pformat(data))
try:
self.client.sms.messages.create(**data)
except Exception:
logger.exception("Failed to create Twilio message")
raise
<commit_msg>Remove self.debug as LoggerMixin was removed from new versions of rapidsms.<commit_after>import pprint
import logging
import datetime
from twilio.rest import TwilioRestClient
from rapidsms.backends.base import BackendBase
logger = logging.getLogger(__name__)
class TwilioBackend(BackendBase):
"""A RapidSMS backend for Twilio (http://www.twilio.com/)."""
def configure(self, config=None, **kwargs):
self.config = config
self.client = TwilioRestClient(self.config['account_sid'],
self.config['auth_token'])
def prepare_message(self, id_, text, identities, context):
encoding = self.config.get('encoding', 'ascii')
encoding_errors = self.config.get('encoding_errors', 'ignore')
data = {
'from_': self.config['number'],
'body': text.encode(encoding, encoding_errors),
}
if 'callback' in self.config:
data['status_callback'] = self.config['callback']
return data
def send(self, id_, text, identities, context={}):
logger.debug('Sending message: %s' % text)
data = self.prepare_message(id_, text, identities, context)
for identity in identities:
data['to'] = identity
logger.debug('POST data: %s' % pprint.pformat(data))
try:
self.client.sms.messages.create(**data)
except Exception:
logger.exception("Failed to create Twilio message")
raise
|
592a2c778bf7c87b7aad6f9ba14c1ba83da033e8
|
scoring_engine/web/views/services.py
|
scoring_engine/web/views/services.py
|
from flask import Blueprint, render_template, flash
from flask_login import login_required, current_user
mod = Blueprint('services', __name__)
@mod.route('/services')
@login_required
def home():
current_team = current_user.team
if not current_user.is_blue_team:
flash('Only blue teams can access services', 'error')
return render_template('overview.html')
return render_template('services.html', team=current_team)
@mod.route('/service/<id>')
@login_required
def service(id):
return render_template('service.html', service=id)
|
from flask import Blueprint, render_template, url_for, redirect
from flask_login import login_required, current_user
from scoring_engine.models.service import Service
mod = Blueprint('services', __name__)
@mod.route('/services')
@login_required
def home():
current_team = current_user.team
if not current_user.is_blue_team:
return redirect(url_for('auth.unauthorized'))
return render_template('services.html', team=current_team)
@mod.route('/service/<id>')
@login_required
def service(id):
service = Service.query.get(id)
if service is None or not current_user.team == service.team:
return redirect(url_for('auth.unauthorized'))
return render_template('service.html', service=service)
|
Add unauthorize to service template
|
Add unauthorize to service template
Signed-off-by: Brandon Myers <[email protected]>
|
Python
|
mit
|
pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine
|
from flask import Blueprint, render_template, flash
from flask_login import login_required, current_user
mod = Blueprint('services', __name__)
@mod.route('/services')
@login_required
def home():
current_team = current_user.team
if not current_user.is_blue_team:
flash('Only blue teams can access services', 'error')
return render_template('overview.html')
return render_template('services.html', team=current_team)
@mod.route('/service/<id>')
@login_required
def service(id):
return render_template('service.html', service=id)
Add unauthorize to service template
Signed-off-by: Brandon Myers <[email protected]>
|
from flask import Blueprint, render_template, url_for, redirect
from flask_login import login_required, current_user
from scoring_engine.models.service import Service
mod = Blueprint('services', __name__)
@mod.route('/services')
@login_required
def home():
current_team = current_user.team
if not current_user.is_blue_team:
return redirect(url_for('auth.unauthorized'))
return render_template('services.html', team=current_team)
@mod.route('/service/<id>')
@login_required
def service(id):
service = Service.query.get(id)
if service is None or not current_user.team == service.team:
return redirect(url_for('auth.unauthorized'))
return render_template('service.html', service=service)
|
<commit_before>from flask import Blueprint, render_template, flash
from flask_login import login_required, current_user
mod = Blueprint('services', __name__)
@mod.route('/services')
@login_required
def home():
current_team = current_user.team
if not current_user.is_blue_team:
flash('Only blue teams can access services', 'error')
return render_template('overview.html')
return render_template('services.html', team=current_team)
@mod.route('/service/<id>')
@login_required
def service(id):
return render_template('service.html', service=id)
<commit_msg>Add unauthorize to service template
Signed-off-by: Brandon Myers <[email protected]><commit_after>
|
from flask import Blueprint, render_template, url_for, redirect
from flask_login import login_required, current_user
from scoring_engine.models.service import Service
mod = Blueprint('services', __name__)
@mod.route('/services')
@login_required
def home():
current_team = current_user.team
if not current_user.is_blue_team:
return redirect(url_for('auth.unauthorized'))
return render_template('services.html', team=current_team)
@mod.route('/service/<id>')
@login_required
def service(id):
service = Service.query.get(id)
if service is None or not current_user.team == service.team:
return redirect(url_for('auth.unauthorized'))
return render_template('service.html', service=service)
|
from flask import Blueprint, render_template, flash
from flask_login import login_required, current_user
mod = Blueprint('services', __name__)
@mod.route('/services')
@login_required
def home():
current_team = current_user.team
if not current_user.is_blue_team:
flash('Only blue teams can access services', 'error')
return render_template('overview.html')
return render_template('services.html', team=current_team)
@mod.route('/service/<id>')
@login_required
def service(id):
return render_template('service.html', service=id)
Add unauthorize to service template
Signed-off-by: Brandon Myers <[email protected]>from flask import Blueprint, render_template, url_for, redirect
from flask_login import login_required, current_user
from scoring_engine.models.service import Service
mod = Blueprint('services', __name__)
@mod.route('/services')
@login_required
def home():
current_team = current_user.team
if not current_user.is_blue_team:
return redirect(url_for('auth.unauthorized'))
return render_template('services.html', team=current_team)
@mod.route('/service/<id>')
@login_required
def service(id):
service = Service.query.get(id)
if service is None or not current_user.team == service.team:
return redirect(url_for('auth.unauthorized'))
return render_template('service.html', service=service)
|
<commit_before>from flask import Blueprint, render_template, flash
from flask_login import login_required, current_user
mod = Blueprint('services', __name__)
@mod.route('/services')
@login_required
def home():
current_team = current_user.team
if not current_user.is_blue_team:
flash('Only blue teams can access services', 'error')
return render_template('overview.html')
return render_template('services.html', team=current_team)
@mod.route('/service/<id>')
@login_required
def service(id):
return render_template('service.html', service=id)
<commit_msg>Add unauthorize to service template
Signed-off-by: Brandon Myers <[email protected]><commit_after>from flask import Blueprint, render_template, url_for, redirect
from flask_login import login_required, current_user
from scoring_engine.models.service import Service
mod = Blueprint('services', __name__)
@mod.route('/services')
@login_required
def home():
current_team = current_user.team
if not current_user.is_blue_team:
return redirect(url_for('auth.unauthorized'))
return render_template('services.html', team=current_team)
@mod.route('/service/<id>')
@login_required
def service(id):
service = Service.query.get(id)
if service is None or not current_user.team == service.team:
return redirect(url_for('auth.unauthorized'))
return render_template('service.html', service=service)
|
7f2c1c46f9a9f1557b3754b26428d9d9862440c3
|
server.py
|
server.py
|
#!/usr/bin/env python
from recipyGui import recipyGui
import random, threading, webbrowser
port = 5000 + random.randint(0, 999)
url = "http://127.0.0.1:{0}".format(port)
# Give the application some time before it starts
threading.Timer(1.25, lambda: webbrowser.open(url) ).start()
recipyGui.run(debug = True, port=port)
|
#!/usr/bin/env python
from recipyGui import recipyGui
import threading, webbrowser, socket
def get_free_port():
s = socket.socket()
s.bind(('', 0))
port = s.getsockname()[1]
s.close()
return port
port = get_free_port()
url = "http://127.0.0.1:{0}".format(port)
# Give the application some time before it starts
threading.Timer(1.25, lambda: webbrowser.open(url) ).start()
recipyGui.run(debug = True, port=port)
|
Select random open port for gui
|
Select random open port for gui
Refs #6.
|
Python
|
apache-2.0
|
MBARIMike/recipy,musically-ut/recipy,github4ry/recipy,MichielCottaar/recipy,github4ry/recipy,recipy/recipy-gui,musically-ut/recipy,bsipocz/recipy,MBARIMike/recipy,recipy/recipy,recipy/recipy,recipy/recipy-gui,MichielCottaar/recipy,bsipocz/recipy
|
#!/usr/bin/env python
from recipyGui import recipyGui
import random, threading, webbrowser
port = 5000 + random.randint(0, 999)
url = "http://127.0.0.1:{0}".format(port)
# Give the application some time before it starts
threading.Timer(1.25, lambda: webbrowser.open(url) ).start()
recipyGui.run(debug = True, port=port)
Select random open port for gui
Refs #6.
|
#!/usr/bin/env python
from recipyGui import recipyGui
import threading, webbrowser, socket
def get_free_port():
s = socket.socket()
s.bind(('', 0))
port = s.getsockname()[1]
s.close()
return port
port = get_free_port()
url = "http://127.0.0.1:{0}".format(port)
# Give the application some time before it starts
threading.Timer(1.25, lambda: webbrowser.open(url) ).start()
recipyGui.run(debug = True, port=port)
|
<commit_before>#!/usr/bin/env python
from recipyGui import recipyGui
import random, threading, webbrowser
port = 5000 + random.randint(0, 999)
url = "http://127.0.0.1:{0}".format(port)
# Give the application some time before it starts
threading.Timer(1.25, lambda: webbrowser.open(url) ).start()
recipyGui.run(debug = True, port=port)
<commit_msg>Select random open port for gui
Refs #6.<commit_after>
|
#!/usr/bin/env python
from recipyGui import recipyGui
import threading, webbrowser, socket
def get_free_port():
s = socket.socket()
s.bind(('', 0))
port = s.getsockname()[1]
s.close()
return port
port = get_free_port()
url = "http://127.0.0.1:{0}".format(port)
# Give the application some time before it starts
threading.Timer(1.25, lambda: webbrowser.open(url) ).start()
recipyGui.run(debug = True, port=port)
|
#!/usr/bin/env python
from recipyGui import recipyGui
import random, threading, webbrowser
port = 5000 + random.randint(0, 999)
url = "http://127.0.0.1:{0}".format(port)
# Give the application some time before it starts
threading.Timer(1.25, lambda: webbrowser.open(url) ).start()
recipyGui.run(debug = True, port=port)
Select random open port for gui
Refs #6.#!/usr/bin/env python
from recipyGui import recipyGui
import threading, webbrowser, socket
def get_free_port():
s = socket.socket()
s.bind(('', 0))
port = s.getsockname()[1]
s.close()
return port
port = get_free_port()
url = "http://127.0.0.1:{0}".format(port)
# Give the application some time before it starts
threading.Timer(1.25, lambda: webbrowser.open(url) ).start()
recipyGui.run(debug = True, port=port)
|
<commit_before>#!/usr/bin/env python
from recipyGui import recipyGui
import random, threading, webbrowser
port = 5000 + random.randint(0, 999)
url = "http://127.0.0.1:{0}".format(port)
# Give the application some time before it starts
threading.Timer(1.25, lambda: webbrowser.open(url) ).start()
recipyGui.run(debug = True, port=port)
<commit_msg>Select random open port for gui
Refs #6.<commit_after>#!/usr/bin/env python
from recipyGui import recipyGui
import threading, webbrowser, socket
def get_free_port():
s = socket.socket()
s.bind(('', 0))
port = s.getsockname()[1]
s.close()
return port
port = get_free_port()
url = "http://127.0.0.1:{0}".format(port)
# Give the application some time before it starts
threading.Timer(1.25, lambda: webbrowser.open(url) ).start()
recipyGui.run(debug = True, port=port)
|
cdfbd5bab75de151e2e9f3f36eb18741ddb862c1
|
sifter.py
|
sifter.py
|
import os
import requests
import re
import json
NUM_REGEX = r'\#([0-9]+)'
API_KEY = os.environ['SIFTER']
def find_ticket(number):
headers = {
'X-Sifter-Token': API_KEY
}
url = 'https://unisubs.sifterapp.com/api/projects/12298/issues?q=%s'
api = url % number
r = requests.get(api, headers=headers)
data = json.loads(r.content)
for issue in data['issues']:
if str(issue['number']) == number:
return format_ticket(issue)
def format_ticket(issue):
url = "https://unisubs.sifterapp.com/issue/%s" % issue['number']
return "%s - %s - %s" % (issue['number'], issue['subject'], url)
def parse(text):
issues = re.findall(NUM_REGEX, text)
return map(find_ticket, issues)
|
import os
import requests
import re
import json
NUM_REGEX = r'\b\#?(\d\d\d\d?\d?)\b'
API_KEY = os.environ['SIFTER']
def find_ticket(number):
headers = {
'X-Sifter-Token': API_KEY
}
url = 'https://unisubs.sifterapp.com/api/projects/12298/issues?q=%s'
api = url % number
r = requests.get(api, headers=headers)
data = json.loads(r.content)
for issue in data['issues']:
if str(issue['number']) == number:
return format_ticket(issue)
def format_ticket(issue):
url = "https://unisubs.sifterapp.com/issue/%s" % issue['number']
return "%s - %s - %s" % (issue['number'], issue['subject'], url)
def parse(text):
issues = re.findall(NUM_REGEX, text)
return map(find_ticket, issues)
|
Change the Sifter issue number matching
|
Change the Sifter issue number matching
Now it's only 3-5 digits, optionally with the hash,
and only as a standalone word.
|
Python
|
bsd-2-clause
|
honza/nigel
|
import os
import requests
import re
import json
NUM_REGEX = r'\#([0-9]+)'
API_KEY = os.environ['SIFTER']
def find_ticket(number):
headers = {
'X-Sifter-Token': API_KEY
}
url = 'https://unisubs.sifterapp.com/api/projects/12298/issues?q=%s'
api = url % number
r = requests.get(api, headers=headers)
data = json.loads(r.content)
for issue in data['issues']:
if str(issue['number']) == number:
return format_ticket(issue)
def format_ticket(issue):
url = "https://unisubs.sifterapp.com/issue/%s" % issue['number']
return "%s - %s - %s" % (issue['number'], issue['subject'], url)
def parse(text):
issues = re.findall(NUM_REGEX, text)
return map(find_ticket, issues)
Change the Sifter issue number matching
Now it's only 3-5 digits, optionally with the hash,
and only as a standalone word.
|
import os
import requests
import re
import json
NUM_REGEX = r'\b\#?(\d\d\d\d?\d?)\b'
API_KEY = os.environ['SIFTER']
def find_ticket(number):
headers = {
'X-Sifter-Token': API_KEY
}
url = 'https://unisubs.sifterapp.com/api/projects/12298/issues?q=%s'
api = url % number
r = requests.get(api, headers=headers)
data = json.loads(r.content)
for issue in data['issues']:
if str(issue['number']) == number:
return format_ticket(issue)
def format_ticket(issue):
url = "https://unisubs.sifterapp.com/issue/%s" % issue['number']
return "%s - %s - %s" % (issue['number'], issue['subject'], url)
def parse(text):
issues = re.findall(NUM_REGEX, text)
return map(find_ticket, issues)
|
<commit_before>import os
import requests
import re
import json
NUM_REGEX = r'\#([0-9]+)'
API_KEY = os.environ['SIFTER']
def find_ticket(number):
headers = {
'X-Sifter-Token': API_KEY
}
url = 'https://unisubs.sifterapp.com/api/projects/12298/issues?q=%s'
api = url % number
r = requests.get(api, headers=headers)
data = json.loads(r.content)
for issue in data['issues']:
if str(issue['number']) == number:
return format_ticket(issue)
def format_ticket(issue):
url = "https://unisubs.sifterapp.com/issue/%s" % issue['number']
return "%s - %s - %s" % (issue['number'], issue['subject'], url)
def parse(text):
issues = re.findall(NUM_REGEX, text)
return map(find_ticket, issues)
<commit_msg>Change the Sifter issue number matching
Now it's only 3-5 digits, optionally with the hash,
and only as a standalone word.<commit_after>
|
import os
import requests
import re
import json
NUM_REGEX = r'\b\#?(\d\d\d\d?\d?)\b'
API_KEY = os.environ['SIFTER']
def find_ticket(number):
headers = {
'X-Sifter-Token': API_KEY
}
url = 'https://unisubs.sifterapp.com/api/projects/12298/issues?q=%s'
api = url % number
r = requests.get(api, headers=headers)
data = json.loads(r.content)
for issue in data['issues']:
if str(issue['number']) == number:
return format_ticket(issue)
def format_ticket(issue):
url = "https://unisubs.sifterapp.com/issue/%s" % issue['number']
return "%s - %s - %s" % (issue['number'], issue['subject'], url)
def parse(text):
issues = re.findall(NUM_REGEX, text)
return map(find_ticket, issues)
|
import os
import requests
import re
import json
NUM_REGEX = r'\#([0-9]+)'
API_KEY = os.environ['SIFTER']
def find_ticket(number):
headers = {
'X-Sifter-Token': API_KEY
}
url = 'https://unisubs.sifterapp.com/api/projects/12298/issues?q=%s'
api = url % number
r = requests.get(api, headers=headers)
data = json.loads(r.content)
for issue in data['issues']:
if str(issue['number']) == number:
return format_ticket(issue)
def format_ticket(issue):
url = "https://unisubs.sifterapp.com/issue/%s" % issue['number']
return "%s - %s - %s" % (issue['number'], issue['subject'], url)
def parse(text):
issues = re.findall(NUM_REGEX, text)
return map(find_ticket, issues)
Change the Sifter issue number matching
Now it's only 3-5 digits, optionally with the hash,
and only as a standalone word.import os
import requests
import re
import json
NUM_REGEX = r'\b\#?(\d\d\d\d?\d?)\b'
API_KEY = os.environ['SIFTER']
def find_ticket(number):
headers = {
'X-Sifter-Token': API_KEY
}
url = 'https://unisubs.sifterapp.com/api/projects/12298/issues?q=%s'
api = url % number
r = requests.get(api, headers=headers)
data = json.loads(r.content)
for issue in data['issues']:
if str(issue['number']) == number:
return format_ticket(issue)
def format_ticket(issue):
url = "https://unisubs.sifterapp.com/issue/%s" % issue['number']
return "%s - %s - %s" % (issue['number'], issue['subject'], url)
def parse(text):
issues = re.findall(NUM_REGEX, text)
return map(find_ticket, issues)
|
<commit_before>import os
import requests
import re
import json
NUM_REGEX = r'\#([0-9]+)'
API_KEY = os.environ['SIFTER']
def find_ticket(number):
headers = {
'X-Sifter-Token': API_KEY
}
url = 'https://unisubs.sifterapp.com/api/projects/12298/issues?q=%s'
api = url % number
r = requests.get(api, headers=headers)
data = json.loads(r.content)
for issue in data['issues']:
if str(issue['number']) == number:
return format_ticket(issue)
def format_ticket(issue):
url = "https://unisubs.sifterapp.com/issue/%s" % issue['number']
return "%s - %s - %s" % (issue['number'], issue['subject'], url)
def parse(text):
issues = re.findall(NUM_REGEX, text)
return map(find_ticket, issues)
<commit_msg>Change the Sifter issue number matching
Now it's only 3-5 digits, optionally with the hash,
and only as a standalone word.<commit_after>import os
import requests
import re
import json
NUM_REGEX = r'\b\#?(\d\d\d\d?\d?)\b'
API_KEY = os.environ['SIFTER']
def find_ticket(number):
headers = {
'X-Sifter-Token': API_KEY
}
url = 'https://unisubs.sifterapp.com/api/projects/12298/issues?q=%s'
api = url % number
r = requests.get(api, headers=headers)
data = json.loads(r.content)
for issue in data['issues']:
if str(issue['number']) == number:
return format_ticket(issue)
def format_ticket(issue):
url = "https://unisubs.sifterapp.com/issue/%s" % issue['number']
return "%s - %s - %s" % (issue['number'], issue['subject'], url)
def parse(text):
issues = re.findall(NUM_REGEX, text)
return map(find_ticket, issues)
|
74eb842870424a22334fee35881f1b6c877da8e6
|
scot/backend_mne.py
|
scot/backend_mne.py
|
# Released under The MIT License (MIT)
# http://opensource.org/licenses/MIT
# Copyright (c) 2013-2016 SCoT Development Team
"""Use mne-python routines as backend."""
from __future__ import absolute_import
import scipy as sp
from . import datatools
from . import backend
from . import backend_builtin as builtin
def generate():
from mne.preprocessing.infomax_ import infomax
def wrapper_infomax(data, random_state=None):
"""Call Infomax for ICA calculation."""
u = infomax(datatools.cat_trials(data).T, extended=True,
random_state=random_state).T
m = sp.linalg.pinv(u)
return m, u
def wrapper_csp(x, cl, reducedim):
"""Call MNE CSP algorithm."""
from mne.decoding import CSP
csp = CSP(n_components=reducedim, cov_est="epoch")
csp.fit(x, cl)
c, d = csp.filters_.T[:, :reducedim], csp.patterns_[:reducedim, :]
y = datatools.dot_special(c.T, x)
return c, d, y
backend = builtin.generate()
backend.update({'ica': wrapper_infomax, 'csp': wrapper_csp})
return backend
backend.register('mne', generate)
|
# Released under The MIT License (MIT)
# http://opensource.org/licenses/MIT
# Copyright (c) 2013-2016 SCoT Development Team
"""Use mne-python routines as backend."""
from __future__ import absolute_import
import scipy as sp
from . import datatools
from . import backend
from . import backend_builtin as builtin
def generate():
from mne.preprocessing.infomax_ import infomax
def wrapper_infomax(data, random_state=None):
"""Call Infomax for ICA calculation."""
u = infomax(datatools.cat_trials(data).T, extended=True,
random_state=random_state).T
m = sp.linalg.pinv(u)
return m, u
def wrapper_csp(x, cl, reducedim):
"""Call MNE CSP algorithm."""
from mne.decoding import CSP
csp = CSP(n_components=reducedim, cov_est="epoch", reg="ledoit_wolf")
csp.fit(x, cl)
c, d = csp.filters_.T[:, :reducedim], csp.patterns_[:reducedim, :]
y = datatools.dot_special(c.T, x)
return c, d, y
backend = builtin.generate()
backend.update({'ica': wrapper_infomax, 'csp': wrapper_csp})
return backend
backend.register('mne', generate)
|
Use regularized covariance in CSP by default
|
Use regularized covariance in CSP by default
|
Python
|
mit
|
scot-dev/scot,cbrnr/scot,mbillingr/SCoT,cbrnr/scot,scot-dev/scot,cle1109/scot,cle1109/scot,mbillingr/SCoT
|
# Released under The MIT License (MIT)
# http://opensource.org/licenses/MIT
# Copyright (c) 2013-2016 SCoT Development Team
"""Use mne-python routines as backend."""
from __future__ import absolute_import
import scipy as sp
from . import datatools
from . import backend
from . import backend_builtin as builtin
def generate():
from mne.preprocessing.infomax_ import infomax
def wrapper_infomax(data, random_state=None):
"""Call Infomax for ICA calculation."""
u = infomax(datatools.cat_trials(data).T, extended=True,
random_state=random_state).T
m = sp.linalg.pinv(u)
return m, u
def wrapper_csp(x, cl, reducedim):
"""Call MNE CSP algorithm."""
from mne.decoding import CSP
csp = CSP(n_components=reducedim, cov_est="epoch")
csp.fit(x, cl)
c, d = csp.filters_.T[:, :reducedim], csp.patterns_[:reducedim, :]
y = datatools.dot_special(c.T, x)
return c, d, y
backend = builtin.generate()
backend.update({'ica': wrapper_infomax, 'csp': wrapper_csp})
return backend
backend.register('mne', generate)
Use regularized covariance in CSP by default
|
# Released under The MIT License (MIT)
# http://opensource.org/licenses/MIT
# Copyright (c) 2013-2016 SCoT Development Team
"""Use mne-python routines as backend."""
from __future__ import absolute_import
import scipy as sp
from . import datatools
from . import backend
from . import backend_builtin as builtin
def generate():
from mne.preprocessing.infomax_ import infomax
def wrapper_infomax(data, random_state=None):
"""Call Infomax for ICA calculation."""
u = infomax(datatools.cat_trials(data).T, extended=True,
random_state=random_state).T
m = sp.linalg.pinv(u)
return m, u
def wrapper_csp(x, cl, reducedim):
"""Call MNE CSP algorithm."""
from mne.decoding import CSP
csp = CSP(n_components=reducedim, cov_est="epoch", reg="ledoit_wolf")
csp.fit(x, cl)
c, d = csp.filters_.T[:, :reducedim], csp.patterns_[:reducedim, :]
y = datatools.dot_special(c.T, x)
return c, d, y
backend = builtin.generate()
backend.update({'ica': wrapper_infomax, 'csp': wrapper_csp})
return backend
backend.register('mne', generate)
|
<commit_before># Released under The MIT License (MIT)
# http://opensource.org/licenses/MIT
# Copyright (c) 2013-2016 SCoT Development Team
"""Use mne-python routines as backend."""
from __future__ import absolute_import
import scipy as sp
from . import datatools
from . import backend
from . import backend_builtin as builtin
def generate():
from mne.preprocessing.infomax_ import infomax
def wrapper_infomax(data, random_state=None):
"""Call Infomax for ICA calculation."""
u = infomax(datatools.cat_trials(data).T, extended=True,
random_state=random_state).T
m = sp.linalg.pinv(u)
return m, u
def wrapper_csp(x, cl, reducedim):
"""Call MNE CSP algorithm."""
from mne.decoding import CSP
csp = CSP(n_components=reducedim, cov_est="epoch")
csp.fit(x, cl)
c, d = csp.filters_.T[:, :reducedim], csp.patterns_[:reducedim, :]
y = datatools.dot_special(c.T, x)
return c, d, y
backend = builtin.generate()
backend.update({'ica': wrapper_infomax, 'csp': wrapper_csp})
return backend
backend.register('mne', generate)
<commit_msg>Use regularized covariance in CSP by default<commit_after>
|
# Released under The MIT License (MIT)
# http://opensource.org/licenses/MIT
# Copyright (c) 2013-2016 SCoT Development Team
"""Use mne-python routines as backend."""
from __future__ import absolute_import
import scipy as sp
from . import datatools
from . import backend
from . import backend_builtin as builtin
def generate():
from mne.preprocessing.infomax_ import infomax
def wrapper_infomax(data, random_state=None):
"""Call Infomax for ICA calculation."""
u = infomax(datatools.cat_trials(data).T, extended=True,
random_state=random_state).T
m = sp.linalg.pinv(u)
return m, u
def wrapper_csp(x, cl, reducedim):
"""Call MNE CSP algorithm."""
from mne.decoding import CSP
csp = CSP(n_components=reducedim, cov_est="epoch", reg="ledoit_wolf")
csp.fit(x, cl)
c, d = csp.filters_.T[:, :reducedim], csp.patterns_[:reducedim, :]
y = datatools.dot_special(c.T, x)
return c, d, y
backend = builtin.generate()
backend.update({'ica': wrapper_infomax, 'csp': wrapper_csp})
return backend
backend.register('mne', generate)
|
# Released under The MIT License (MIT)
# http://opensource.org/licenses/MIT
# Copyright (c) 2013-2016 SCoT Development Team
"""Use mne-python routines as backend."""
from __future__ import absolute_import
import scipy as sp
from . import datatools
from . import backend
from . import backend_builtin as builtin
def generate():
from mne.preprocessing.infomax_ import infomax
def wrapper_infomax(data, random_state=None):
"""Call Infomax for ICA calculation."""
u = infomax(datatools.cat_trials(data).T, extended=True,
random_state=random_state).T
m = sp.linalg.pinv(u)
return m, u
def wrapper_csp(x, cl, reducedim):
"""Call MNE CSP algorithm."""
from mne.decoding import CSP
csp = CSP(n_components=reducedim, cov_est="epoch")
csp.fit(x, cl)
c, d = csp.filters_.T[:, :reducedim], csp.patterns_[:reducedim, :]
y = datatools.dot_special(c.T, x)
return c, d, y
backend = builtin.generate()
backend.update({'ica': wrapper_infomax, 'csp': wrapper_csp})
return backend
backend.register('mne', generate)
Use regularized covariance in CSP by default# Released under The MIT License (MIT)
# http://opensource.org/licenses/MIT
# Copyright (c) 2013-2016 SCoT Development Team
"""Use mne-python routines as backend."""
from __future__ import absolute_import
import scipy as sp
from . import datatools
from . import backend
from . import backend_builtin as builtin
def generate():
from mne.preprocessing.infomax_ import infomax
def wrapper_infomax(data, random_state=None):
"""Call Infomax for ICA calculation."""
u = infomax(datatools.cat_trials(data).T, extended=True,
random_state=random_state).T
m = sp.linalg.pinv(u)
return m, u
def wrapper_csp(x, cl, reducedim):
"""Call MNE CSP algorithm."""
from mne.decoding import CSP
csp = CSP(n_components=reducedim, cov_est="epoch", reg="ledoit_wolf")
csp.fit(x, cl)
c, d = csp.filters_.T[:, :reducedim], csp.patterns_[:reducedim, :]
y = datatools.dot_special(c.T, x)
return c, d, y
backend = builtin.generate()
backend.update({'ica': wrapper_infomax, 'csp': wrapper_csp})
return backend
backend.register('mne', generate)
|
<commit_before># Released under The MIT License (MIT)
# http://opensource.org/licenses/MIT
# Copyright (c) 2013-2016 SCoT Development Team
"""Use mne-python routines as backend."""
from __future__ import absolute_import
import scipy as sp
from . import datatools
from . import backend
from . import backend_builtin as builtin
def generate():
from mne.preprocessing.infomax_ import infomax
def wrapper_infomax(data, random_state=None):
"""Call Infomax for ICA calculation."""
u = infomax(datatools.cat_trials(data).T, extended=True,
random_state=random_state).T
m = sp.linalg.pinv(u)
return m, u
def wrapper_csp(x, cl, reducedim):
"""Call MNE CSP algorithm."""
from mne.decoding import CSP
csp = CSP(n_components=reducedim, cov_est="epoch")
csp.fit(x, cl)
c, d = csp.filters_.T[:, :reducedim], csp.patterns_[:reducedim, :]
y = datatools.dot_special(c.T, x)
return c, d, y
backend = builtin.generate()
backend.update({'ica': wrapper_infomax, 'csp': wrapper_csp})
return backend
backend.register('mne', generate)
<commit_msg>Use regularized covariance in CSP by default<commit_after># Released under The MIT License (MIT)
# http://opensource.org/licenses/MIT
# Copyright (c) 2013-2016 SCoT Development Team
"""Use mne-python routines as backend."""
from __future__ import absolute_import
import scipy as sp
from . import datatools
from . import backend
from . import backend_builtin as builtin
def generate():
from mne.preprocessing.infomax_ import infomax
def wrapper_infomax(data, random_state=None):
"""Call Infomax for ICA calculation."""
u = infomax(datatools.cat_trials(data).T, extended=True,
random_state=random_state).T
m = sp.linalg.pinv(u)
return m, u
def wrapper_csp(x, cl, reducedim):
"""Call MNE CSP algorithm."""
from mne.decoding import CSP
csp = CSP(n_components=reducedim, cov_est="epoch", reg="ledoit_wolf")
csp.fit(x, cl)
c, d = csp.filters_.T[:, :reducedim], csp.patterns_[:reducedim, :]
y = datatools.dot_special(c.T, x)
return c, d, y
backend = builtin.generate()
backend.update({'ica': wrapper_infomax, 'csp': wrapper_csp})
return backend
backend.register('mne', generate)
|
322ccf3bb4197a466ac5022ae2098a82bbeab6f1
|
sorting_algorithms/selection_sort.py
|
sorting_algorithms/selection_sort.py
|
def selection_sort(L):
"""
:param L: unsorted list
:return: this is a method, there is no return function. The method sorts a list using
selection sort algorithm
>>> L = [2, 7, 5, 3]
>>> selection_sort(L)
>>> L
[2, 3, 5, 7]
"""
end = len(L)
# Find the index of the smallest element in L[i:] and swap that item
# with the item at index i
for i in range(end):
index_of_smallest = get_index_of_smallest(L, i)
L[index_of_smallest], L[i] = L[i], L[index_of_smallest]
def get_index_of_smallest(L, i):
"""
(list, int) -> int
:param L: list we want to analyse
:param i: index from where we want to start
:return: index of smallest object in the list
"""
# The index of the smallest item so far
index_of_smallest = i
end = len(L)
for j in range(i + 1, end):
if L[j] < L[index_of_smallest]:
index_of_smallest = j
return index_of_smallest
if __name__ == '__main__':
import doctest
doctest.testmod()
|
def selection_sort(L):
"""
(list) -> NoneType
Sort list from smallest to largest using selection sort algorithm
:param L: unsorted list
>>> L = [2, 7, 5, 3]
>>> selection_sort(L)
>>> L
[2, 3, 5, 7]
"""
end = len(L)
# Find the index of the smallest element in L[i:] and swap that item
# with the item at index i
for i in range(end):
index_of_smallest = get_index_of_smallest(L, i)
L[index_of_smallest], L[i] = L[i], L[index_of_smallest]
def get_index_of_smallest(L, i):
"""
(list, int) -> int
:param L: list we want to analyse
:param i: index from where we want to start
:return: index of smallest object in the list
"""
# The index of the smallest item so far
index_of_smallest = i
end = len(L)
for j in range(i + 1, end):
if L[j] < L[index_of_smallest]:
index_of_smallest = j
return index_of_smallest
if __name__ == '__main__':
import doctest
doctest.testmod()
|
Improve selection sort algorithm's documentation
|
Improve selection sort algorithm's documentation
|
Python
|
mit
|
IamGianluca/algorithms_collection,IamGianluca/algorithms
|
def selection_sort(L):
"""
:param L: unsorted list
:return: this is a method, there is no return function. The method sorts a list using
selection sort algorithm
>>> L = [2, 7, 5, 3]
>>> selection_sort(L)
>>> L
[2, 3, 5, 7]
"""
end = len(L)
# Find the index of the smallest element in L[i:] and swap that item
# with the item at index i
for i in range(end):
index_of_smallest = get_index_of_smallest(L, i)
L[index_of_smallest], L[i] = L[i], L[index_of_smallest]
def get_index_of_smallest(L, i):
"""
(list, int) -> int
:param L: list we want to analyse
:param i: index from where we want to start
:return: index of smallest object in the list
"""
# The index of the smallest item so far
index_of_smallest = i
end = len(L)
for j in range(i + 1, end):
if L[j] < L[index_of_smallest]:
index_of_smallest = j
return index_of_smallest
if __name__ == '__main__':
import doctest
doctest.testmod()Improve selection sort algorithm's documentation
|
def selection_sort(L):
"""
(list) -> NoneType
Sort list from smallest to largest using selection sort algorithm
:param L: unsorted list
>>> L = [2, 7, 5, 3]
>>> selection_sort(L)
>>> L
[2, 3, 5, 7]
"""
end = len(L)
# Find the index of the smallest element in L[i:] and swap that item
# with the item at index i
for i in range(end):
index_of_smallest = get_index_of_smallest(L, i)
L[index_of_smallest], L[i] = L[i], L[index_of_smallest]
def get_index_of_smallest(L, i):
"""
(list, int) -> int
:param L: list we want to analyse
:param i: index from where we want to start
:return: index of smallest object in the list
"""
# The index of the smallest item so far
index_of_smallest = i
end = len(L)
for j in range(i + 1, end):
if L[j] < L[index_of_smallest]:
index_of_smallest = j
return index_of_smallest
if __name__ == '__main__':
import doctest
doctest.testmod()
|
<commit_before>def selection_sort(L):
"""
:param L: unsorted list
:return: this is a method, there is no return function. The method sorts a list using
selection sort algorithm
>>> L = [2, 7, 5, 3]
>>> selection_sort(L)
>>> L
[2, 3, 5, 7]
"""
end = len(L)
# Find the index of the smallest element in L[i:] and swap that item
# with the item at index i
for i in range(end):
index_of_smallest = get_index_of_smallest(L, i)
L[index_of_smallest], L[i] = L[i], L[index_of_smallest]
def get_index_of_smallest(L, i):
"""
(list, int) -> int
:param L: list we want to analyse
:param i: index from where we want to start
:return: index of smallest object in the list
"""
# The index of the smallest item so far
index_of_smallest = i
end = len(L)
for j in range(i + 1, end):
if L[j] < L[index_of_smallest]:
index_of_smallest = j
return index_of_smallest
if __name__ == '__main__':
import doctest
doctest.testmod()<commit_msg>Improve selection sort algorithm's documentation<commit_after>
|
def selection_sort(L):
"""
(list) -> NoneType
Sort list from smallest to largest using selection sort algorithm
:param L: unsorted list
>>> L = [2, 7, 5, 3]
>>> selection_sort(L)
>>> L
[2, 3, 5, 7]
"""
end = len(L)
# Find the index of the smallest element in L[i:] and swap that item
# with the item at index i
for i in range(end):
index_of_smallest = get_index_of_smallest(L, i)
L[index_of_smallest], L[i] = L[i], L[index_of_smallest]
def get_index_of_smallest(L, i):
"""
(list, int) -> int
:param L: list we want to analyse
:param i: index from where we want to start
:return: index of smallest object in the list
"""
# The index of the smallest item so far
index_of_smallest = i
end = len(L)
for j in range(i + 1, end):
if L[j] < L[index_of_smallest]:
index_of_smallest = j
return index_of_smallest
if __name__ == '__main__':
import doctest
doctest.testmod()
|
def selection_sort(L):
"""
:param L: unsorted list
:return: this is a method, there is no return function. The method sorts a list using
selection sort algorithm
>>> L = [2, 7, 5, 3]
>>> selection_sort(L)
>>> L
[2, 3, 5, 7]
"""
end = len(L)
# Find the index of the smallest element in L[i:] and swap that item
# with the item at index i
for i in range(end):
index_of_smallest = get_index_of_smallest(L, i)
L[index_of_smallest], L[i] = L[i], L[index_of_smallest]
def get_index_of_smallest(L, i):
"""
(list, int) -> int
:param L: list we want to analyse
:param i: index from where we want to start
:return: index of smallest object in the list
"""
# The index of the smallest item so far
index_of_smallest = i
end = len(L)
for j in range(i + 1, end):
if L[j] < L[index_of_smallest]:
index_of_smallest = j
return index_of_smallest
if __name__ == '__main__':
import doctest
doctest.testmod()Improve selection sort algorithm's documentationdef selection_sort(L):
"""
(list) -> NoneType
Sort list from smallest to largest using selection sort algorithm
:param L: unsorted list
>>> L = [2, 7, 5, 3]
>>> selection_sort(L)
>>> L
[2, 3, 5, 7]
"""
end = len(L)
# Find the index of the smallest element in L[i:] and swap that item
# with the item at index i
for i in range(end):
index_of_smallest = get_index_of_smallest(L, i)
L[index_of_smallest], L[i] = L[i], L[index_of_smallest]
def get_index_of_smallest(L, i):
"""
(list, int) -> int
:param L: list we want to analyse
:param i: index from where we want to start
:return: index of smallest object in the list
"""
# The index of the smallest item so far
index_of_smallest = i
end = len(L)
for j in range(i + 1, end):
if L[j] < L[index_of_smallest]:
index_of_smallest = j
return index_of_smallest
if __name__ == '__main__':
import doctest
doctest.testmod()
|
<commit_before>def selection_sort(L):
"""
:param L: unsorted list
:return: this is a method, there is no return function. The method sorts a list using
selection sort algorithm
>>> L = [2, 7, 5, 3]
>>> selection_sort(L)
>>> L
[2, 3, 5, 7]
"""
end = len(L)
# Find the index of the smallest element in L[i:] and swap that item
# with the item at index i
for i in range(end):
index_of_smallest = get_index_of_smallest(L, i)
L[index_of_smallest], L[i] = L[i], L[index_of_smallest]
def get_index_of_smallest(L, i):
"""
(list, int) -> int
:param L: list we want to analyse
:param i: index from where we want to start
:return: index of smallest object in the list
"""
# The index of the smallest item so far
index_of_smallest = i
end = len(L)
for j in range(i + 1, end):
if L[j] < L[index_of_smallest]:
index_of_smallest = j
return index_of_smallest
if __name__ == '__main__':
import doctest
doctest.testmod()<commit_msg>Improve selection sort algorithm's documentation<commit_after>def selection_sort(L):
"""
(list) -> NoneType
Sort list from smallest to largest using selection sort algorithm
:param L: unsorted list
>>> L = [2, 7, 5, 3]
>>> selection_sort(L)
>>> L
[2, 3, 5, 7]
"""
end = len(L)
# Find the index of the smallest element in L[i:] and swap that item
# with the item at index i
for i in range(end):
index_of_smallest = get_index_of_smallest(L, i)
L[index_of_smallest], L[i] = L[i], L[index_of_smallest]
def get_index_of_smallest(L, i):
"""
(list, int) -> int
:param L: list we want to analyse
:param i: index from where we want to start
:return: index of smallest object in the list
"""
# The index of the smallest item so far
index_of_smallest = i
end = len(L)
for j in range(i + 1, end):
if L[j] < L[index_of_smallest]:
index_of_smallest = j
return index_of_smallest
if __name__ == '__main__':
import doctest
doctest.testmod()
|
16d009a11fdb3022189146fbf97e68d5d71cd70a
|
girder/test_girder/test_web_client.py
|
girder/test_girder/test_web_client.py
|
import os
import pytest
from pytest_girder.utils import runWebClientTest
@pytest.mark.parametrize('spec', (
'annotationListSpec.js',
'annotationSpec.js',
'geojsAnnotationSpec.js',
'geojsSpec.js',
'imageViewerSpec.js',
'largeImageSpec.js'
))
def testWebClient(fsAssetstore, db, spec):
spec = os.path.join(os.path.dirname(__file__), 'web_client_specs', spec)
runWebClientTest(spec, plugins=['large_image', 'large_image_annotation'])
|
import os
import pytest
from pytest_girder.web_client import runWebClientTest
@pytest.mark.parametrize('spec', (
'annotationListSpec.js',
'annotationSpec.js',
'geojsAnnotationSpec.js',
'geojsSpec.js',
'imageViewerSpec.js',
'largeImageSpec.js'
))
def testWebClient(fsAssetstore, db, spec):
spec = os.path.join(os.path.dirname(__file__), 'web_client_specs', spec)
runWebClientTest(spec, plugins=['large_image', 'large_image_annotation'])
|
Use new location for web client test util
|
Use new location for web client test util
|
Python
|
apache-2.0
|
girder/large_image,DigitalSlideArchive/large_image,DigitalSlideArchive/large_image,girder/large_image,girder/large_image,DigitalSlideArchive/large_image
|
import os
import pytest
from pytest_girder.utils import runWebClientTest
@pytest.mark.parametrize('spec', (
'annotationListSpec.js',
'annotationSpec.js',
'geojsAnnotationSpec.js',
'geojsSpec.js',
'imageViewerSpec.js',
'largeImageSpec.js'
))
def testWebClient(fsAssetstore, db, spec):
spec = os.path.join(os.path.dirname(__file__), 'web_client_specs', spec)
runWebClientTest(spec, plugins=['large_image', 'large_image_annotation'])
Use new location for web client test util
|
import os
import pytest
from pytest_girder.web_client import runWebClientTest
@pytest.mark.parametrize('spec', (
'annotationListSpec.js',
'annotationSpec.js',
'geojsAnnotationSpec.js',
'geojsSpec.js',
'imageViewerSpec.js',
'largeImageSpec.js'
))
def testWebClient(fsAssetstore, db, spec):
spec = os.path.join(os.path.dirname(__file__), 'web_client_specs', spec)
runWebClientTest(spec, plugins=['large_image', 'large_image_annotation'])
|
<commit_before>import os
import pytest
from pytest_girder.utils import runWebClientTest
@pytest.mark.parametrize('spec', (
'annotationListSpec.js',
'annotationSpec.js',
'geojsAnnotationSpec.js',
'geojsSpec.js',
'imageViewerSpec.js',
'largeImageSpec.js'
))
def testWebClient(fsAssetstore, db, spec):
spec = os.path.join(os.path.dirname(__file__), 'web_client_specs', spec)
runWebClientTest(spec, plugins=['large_image', 'large_image_annotation'])
<commit_msg>Use new location for web client test util<commit_after>
|
import os
import pytest
from pytest_girder.web_client import runWebClientTest
@pytest.mark.parametrize('spec', (
'annotationListSpec.js',
'annotationSpec.js',
'geojsAnnotationSpec.js',
'geojsSpec.js',
'imageViewerSpec.js',
'largeImageSpec.js'
))
def testWebClient(fsAssetstore, db, spec):
spec = os.path.join(os.path.dirname(__file__), 'web_client_specs', spec)
runWebClientTest(spec, plugins=['large_image', 'large_image_annotation'])
|
import os
import pytest
from pytest_girder.utils import runWebClientTest
@pytest.mark.parametrize('spec', (
'annotationListSpec.js',
'annotationSpec.js',
'geojsAnnotationSpec.js',
'geojsSpec.js',
'imageViewerSpec.js',
'largeImageSpec.js'
))
def testWebClient(fsAssetstore, db, spec):
spec = os.path.join(os.path.dirname(__file__), 'web_client_specs', spec)
runWebClientTest(spec, plugins=['large_image', 'large_image_annotation'])
Use new location for web client test utilimport os
import pytest
from pytest_girder.web_client import runWebClientTest
@pytest.mark.parametrize('spec', (
'annotationListSpec.js',
'annotationSpec.js',
'geojsAnnotationSpec.js',
'geojsSpec.js',
'imageViewerSpec.js',
'largeImageSpec.js'
))
def testWebClient(fsAssetstore, db, spec):
spec = os.path.join(os.path.dirname(__file__), 'web_client_specs', spec)
runWebClientTest(spec, plugins=['large_image', 'large_image_annotation'])
|
<commit_before>import os
import pytest
from pytest_girder.utils import runWebClientTest
@pytest.mark.parametrize('spec', (
'annotationListSpec.js',
'annotationSpec.js',
'geojsAnnotationSpec.js',
'geojsSpec.js',
'imageViewerSpec.js',
'largeImageSpec.js'
))
def testWebClient(fsAssetstore, db, spec):
spec = os.path.join(os.path.dirname(__file__), 'web_client_specs', spec)
runWebClientTest(spec, plugins=['large_image', 'large_image_annotation'])
<commit_msg>Use new location for web client test util<commit_after>import os
import pytest
from pytest_girder.web_client import runWebClientTest
@pytest.mark.parametrize('spec', (
'annotationListSpec.js',
'annotationSpec.js',
'geojsAnnotationSpec.js',
'geojsSpec.js',
'imageViewerSpec.js',
'largeImageSpec.js'
))
def testWebClient(fsAssetstore, db, spec):
spec = os.path.join(os.path.dirname(__file__), 'web_client_specs', spec)
runWebClientTest(spec, plugins=['large_image', 'large_image_annotation'])
|
21af090f312c2381526050fb4c45eb14cfb91eeb
|
ureport/stats/migrations/0017_better_indexes.py
|
ureport/stats/migrations/0017_better_indexes.py
|
# Generated by Django 3.2.6 on 2021-09-27 17:49
from django.db import migrations
INDEX_POLLSTATS_ORG_RESULT_SQL = """
CREATE INDEX IF NOT EXISTS stats_pollstats_org_result on stats_pollstats (org_id, flow_result_id) WHERE flow_result_id IS NOT NULL;
"""
INDEX_POLLSTATS_ORG_QST_RST_CAT_SQL = """
CREATE INDEX IF NOT EXISTS stats_pollstats_org_qstn_rslt_cat_age_gndr_schm_date_not_null on stats_pollstats (org_id, question_id, flow_result_id, category_id, flow_result_category_id, age_segment_id, gender_segment_id, scheme_segment_id, location_id, date) WHERE date IS NOT NULL;
"""
class Migration(migrations.Migration):
dependencies = [
("stats", "0016_pollstats_scheme_segment"),
]
operations = [
migrations.RunSQL(INDEX_POLLSTATS_ORG_RESULT_SQL),
migrations.RunSQL(INDEX_POLLSTATS_ORG_QST_RST_CAT_SQL),
]
|
# Generated by Django 3.2.6 on 2021-09-27 17:49
from django.db import migrations
INDEX_POLLSTATS_ORG_RESULT_SQL = """
CREATE INDEX IF NOT EXISTS stats_pollstats_org_result on stats_pollstats (org_id, flow_result_id) WHERE flow_result_id IS NOT NULL;
"""
INDEX_POLLSTATS_ORG_QST_RST_CAT_SQL = """
CREATE INDEX IF NOT EXISTS stats_pollstats_org_qstn_rslt_cat_age_gndr_schm_date_not_null on stats_pollstats (org_id, question_id, flow_result_id, category_id, flow_result_category_id, age_segment_id, gender_segment_id, scheme_segment_id, location_id, date) WHERE date IS NOT NULL;
"""
class Migration(migrations.Migration):
dependencies = [
("stats", "0016_pollstats_scheme_segment"),
]
operations = [
migrations.RunSQL(INDEX_POLLSTATS_ORG_RESULT_SQL, ""),
migrations.RunSQL(INDEX_POLLSTATS_ORG_QST_RST_CAT_SQL, ""),
]
|
Add empty reverse migration to be able to unapply the migration in reverse
|
Add empty reverse migration to be able to unapply the migration in reverse
|
Python
|
agpl-3.0
|
Ilhasoft/ureport,rapidpro/ureport,rapidpro/ureport,Ilhasoft/ureport,Ilhasoft/ureport,rapidpro/ureport,Ilhasoft/ureport,rapidpro/ureport
|
# Generated by Django 3.2.6 on 2021-09-27 17:49
from django.db import migrations
INDEX_POLLSTATS_ORG_RESULT_SQL = """
CREATE INDEX IF NOT EXISTS stats_pollstats_org_result on stats_pollstats (org_id, flow_result_id) WHERE flow_result_id IS NOT NULL;
"""
INDEX_POLLSTATS_ORG_QST_RST_CAT_SQL = """
CREATE INDEX IF NOT EXISTS stats_pollstats_org_qstn_rslt_cat_age_gndr_schm_date_not_null on stats_pollstats (org_id, question_id, flow_result_id, category_id, flow_result_category_id, age_segment_id, gender_segment_id, scheme_segment_id, location_id, date) WHERE date IS NOT NULL;
"""
class Migration(migrations.Migration):
dependencies = [
("stats", "0016_pollstats_scheme_segment"),
]
operations = [
migrations.RunSQL(INDEX_POLLSTATS_ORG_RESULT_SQL),
migrations.RunSQL(INDEX_POLLSTATS_ORG_QST_RST_CAT_SQL),
]
Add empty reverse migration to be able to unapply the migration in reverse
|
# Generated by Django 3.2.6 on 2021-09-27 17:49
from django.db import migrations
INDEX_POLLSTATS_ORG_RESULT_SQL = """
CREATE INDEX IF NOT EXISTS stats_pollstats_org_result on stats_pollstats (org_id, flow_result_id) WHERE flow_result_id IS NOT NULL;
"""
INDEX_POLLSTATS_ORG_QST_RST_CAT_SQL = """
CREATE INDEX IF NOT EXISTS stats_pollstats_org_qstn_rslt_cat_age_gndr_schm_date_not_null on stats_pollstats (org_id, question_id, flow_result_id, category_id, flow_result_category_id, age_segment_id, gender_segment_id, scheme_segment_id, location_id, date) WHERE date IS NOT NULL;
"""
class Migration(migrations.Migration):
dependencies = [
("stats", "0016_pollstats_scheme_segment"),
]
operations = [
migrations.RunSQL(INDEX_POLLSTATS_ORG_RESULT_SQL, ""),
migrations.RunSQL(INDEX_POLLSTATS_ORG_QST_RST_CAT_SQL, ""),
]
|
<commit_before># Generated by Django 3.2.6 on 2021-09-27 17:49
from django.db import migrations
INDEX_POLLSTATS_ORG_RESULT_SQL = """
CREATE INDEX IF NOT EXISTS stats_pollstats_org_result on stats_pollstats (org_id, flow_result_id) WHERE flow_result_id IS NOT NULL;
"""
INDEX_POLLSTATS_ORG_QST_RST_CAT_SQL = """
CREATE INDEX IF NOT EXISTS stats_pollstats_org_qstn_rslt_cat_age_gndr_schm_date_not_null on stats_pollstats (org_id, question_id, flow_result_id, category_id, flow_result_category_id, age_segment_id, gender_segment_id, scheme_segment_id, location_id, date) WHERE date IS NOT NULL;
"""
class Migration(migrations.Migration):
dependencies = [
("stats", "0016_pollstats_scheme_segment"),
]
operations = [
migrations.RunSQL(INDEX_POLLSTATS_ORG_RESULT_SQL),
migrations.RunSQL(INDEX_POLLSTATS_ORG_QST_RST_CAT_SQL),
]
<commit_msg>Add empty reverse migration to be able to unapply the migration in reverse<commit_after>
|
# Generated by Django 3.2.6 on 2021-09-27 17:49
from django.db import migrations
INDEX_POLLSTATS_ORG_RESULT_SQL = """
CREATE INDEX IF NOT EXISTS stats_pollstats_org_result on stats_pollstats (org_id, flow_result_id) WHERE flow_result_id IS NOT NULL;
"""
INDEX_POLLSTATS_ORG_QST_RST_CAT_SQL = """
CREATE INDEX IF NOT EXISTS stats_pollstats_org_qstn_rslt_cat_age_gndr_schm_date_not_null on stats_pollstats (org_id, question_id, flow_result_id, category_id, flow_result_category_id, age_segment_id, gender_segment_id, scheme_segment_id, location_id, date) WHERE date IS NOT NULL;
"""
class Migration(migrations.Migration):
dependencies = [
("stats", "0016_pollstats_scheme_segment"),
]
operations = [
migrations.RunSQL(INDEX_POLLSTATS_ORG_RESULT_SQL, ""),
migrations.RunSQL(INDEX_POLLSTATS_ORG_QST_RST_CAT_SQL, ""),
]
|
# Generated by Django 3.2.6 on 2021-09-27 17:49
from django.db import migrations
INDEX_POLLSTATS_ORG_RESULT_SQL = """
CREATE INDEX IF NOT EXISTS stats_pollstats_org_result on stats_pollstats (org_id, flow_result_id) WHERE flow_result_id IS NOT NULL;
"""
INDEX_POLLSTATS_ORG_QST_RST_CAT_SQL = """
CREATE INDEX IF NOT EXISTS stats_pollstats_org_qstn_rslt_cat_age_gndr_schm_date_not_null on stats_pollstats (org_id, question_id, flow_result_id, category_id, flow_result_category_id, age_segment_id, gender_segment_id, scheme_segment_id, location_id, date) WHERE date IS NOT NULL;
"""
class Migration(migrations.Migration):
dependencies = [
("stats", "0016_pollstats_scheme_segment"),
]
operations = [
migrations.RunSQL(INDEX_POLLSTATS_ORG_RESULT_SQL),
migrations.RunSQL(INDEX_POLLSTATS_ORG_QST_RST_CAT_SQL),
]
Add empty reverse migration to be able to unapply the migration in reverse# Generated by Django 3.2.6 on 2021-09-27 17:49
from django.db import migrations
INDEX_POLLSTATS_ORG_RESULT_SQL = """
CREATE INDEX IF NOT EXISTS stats_pollstats_org_result on stats_pollstats (org_id, flow_result_id) WHERE flow_result_id IS NOT NULL;
"""
INDEX_POLLSTATS_ORG_QST_RST_CAT_SQL = """
CREATE INDEX IF NOT EXISTS stats_pollstats_org_qstn_rslt_cat_age_gndr_schm_date_not_null on stats_pollstats (org_id, question_id, flow_result_id, category_id, flow_result_category_id, age_segment_id, gender_segment_id, scheme_segment_id, location_id, date) WHERE date IS NOT NULL;
"""
class Migration(migrations.Migration):
dependencies = [
("stats", "0016_pollstats_scheme_segment"),
]
operations = [
migrations.RunSQL(INDEX_POLLSTATS_ORG_RESULT_SQL, ""),
migrations.RunSQL(INDEX_POLLSTATS_ORG_QST_RST_CAT_SQL, ""),
]
|
<commit_before># Generated by Django 3.2.6 on 2021-09-27 17:49
from django.db import migrations
INDEX_POLLSTATS_ORG_RESULT_SQL = """
CREATE INDEX IF NOT EXISTS stats_pollstats_org_result on stats_pollstats (org_id, flow_result_id) WHERE flow_result_id IS NOT NULL;
"""
INDEX_POLLSTATS_ORG_QST_RST_CAT_SQL = """
CREATE INDEX IF NOT EXISTS stats_pollstats_org_qstn_rslt_cat_age_gndr_schm_date_not_null on stats_pollstats (org_id, question_id, flow_result_id, category_id, flow_result_category_id, age_segment_id, gender_segment_id, scheme_segment_id, location_id, date) WHERE date IS NOT NULL;
"""
class Migration(migrations.Migration):
dependencies = [
("stats", "0016_pollstats_scheme_segment"),
]
operations = [
migrations.RunSQL(INDEX_POLLSTATS_ORG_RESULT_SQL),
migrations.RunSQL(INDEX_POLLSTATS_ORG_QST_RST_CAT_SQL),
]
<commit_msg>Add empty reverse migration to be able to unapply the migration in reverse<commit_after># Generated by Django 3.2.6 on 2021-09-27 17:49
from django.db import migrations
INDEX_POLLSTATS_ORG_RESULT_SQL = """
CREATE INDEX IF NOT EXISTS stats_pollstats_org_result on stats_pollstats (org_id, flow_result_id) WHERE flow_result_id IS NOT NULL;
"""
INDEX_POLLSTATS_ORG_QST_RST_CAT_SQL = """
CREATE INDEX IF NOT EXISTS stats_pollstats_org_qstn_rslt_cat_age_gndr_schm_date_not_null on stats_pollstats (org_id, question_id, flow_result_id, category_id, flow_result_category_id, age_segment_id, gender_segment_id, scheme_segment_id, location_id, date) WHERE date IS NOT NULL;
"""
class Migration(migrations.Migration):
dependencies = [
("stats", "0016_pollstats_scheme_segment"),
]
operations = [
migrations.RunSQL(INDEX_POLLSTATS_ORG_RESULT_SQL, ""),
migrations.RunSQL(INDEX_POLLSTATS_ORG_QST_RST_CAT_SQL, ""),
]
|
ac30f52aff51dce892e79ce773e84f2458635d1c
|
digestive/entropy.py
|
digestive/entropy.py
|
from collections import Counter
from math import log2
from digestive import Sink
# TODO: stash intermediate histograms in multiple Counters?
# TODO: output as a spark
# TODO: output as plot
class Entropy(Sink):
def __init__(self):
super().__init__('entropy')
self.length = 0
self.counter = Counter()
def update(self, data):
self.length += len(data)
self.counter.update(data)
def digest(self):
# calculate binary entropy as -Σ(1…n) p_i × log₂(p_i)
entropy = -sum(count / self.length * log2(count / self.length) for count in self.counter.values())
return '{:.8f}'.format(entropy)
|
from collections import Counter
from math import log2
from digestive import Sink
class Entropy(Sink):
def __init__(self):
super().__init__('entropy')
self.length = 0
self.counter = Counter()
def update(self, data):
self.length += len(data)
self.counter.update(data)
def digest(self):
# calculate binary entropy as -Σ(1…n) p_i × log₂(p_i)
entropy = -sum(count / self.length * log2(count / self.length) for count in self.counter.values())
return '{:.8f}'.format(entropy)
|
Remove TODO's converted to issues
|
Remove TODO's converted to issues
|
Python
|
isc
|
akaIDIOT/Digestive
|
from collections import Counter
from math import log2
from digestive import Sink
# TODO: stash intermediate histograms in multiple Counters?
# TODO: output as a spark
# TODO: output as plot
class Entropy(Sink):
def __init__(self):
super().__init__('entropy')
self.length = 0
self.counter = Counter()
def update(self, data):
self.length += len(data)
self.counter.update(data)
def digest(self):
# calculate binary entropy as -Σ(1…n) p_i × log₂(p_i)
entropy = -sum(count / self.length * log2(count / self.length) for count in self.counter.values())
return '{:.8f}'.format(entropy)
Remove TODO's converted to issues
|
from collections import Counter
from math import log2
from digestive import Sink
class Entropy(Sink):
def __init__(self):
super().__init__('entropy')
self.length = 0
self.counter = Counter()
def update(self, data):
self.length += len(data)
self.counter.update(data)
def digest(self):
# calculate binary entropy as -Σ(1…n) p_i × log₂(p_i)
entropy = -sum(count / self.length * log2(count / self.length) for count in self.counter.values())
return '{:.8f}'.format(entropy)
|
<commit_before>from collections import Counter
from math import log2
from digestive import Sink
# TODO: stash intermediate histograms in multiple Counters?
# TODO: output as a spark
# TODO: output as plot
class Entropy(Sink):
def __init__(self):
super().__init__('entropy')
self.length = 0
self.counter = Counter()
def update(self, data):
self.length += len(data)
self.counter.update(data)
def digest(self):
# calculate binary entropy as -Σ(1…n) p_i × log₂(p_i)
entropy = -sum(count / self.length * log2(count / self.length) for count in self.counter.values())
return '{:.8f}'.format(entropy)
<commit_msg>Remove TODO's converted to issues<commit_after>
|
from collections import Counter
from math import log2
from digestive import Sink
class Entropy(Sink):
def __init__(self):
super().__init__('entropy')
self.length = 0
self.counter = Counter()
def update(self, data):
self.length += len(data)
self.counter.update(data)
def digest(self):
# calculate binary entropy as -Σ(1…n) p_i × log₂(p_i)
entropy = -sum(count / self.length * log2(count / self.length) for count in self.counter.values())
return '{:.8f}'.format(entropy)
|
from collections import Counter
from math import log2
from digestive import Sink
# TODO: stash intermediate histograms in multiple Counters?
# TODO: output as a spark
# TODO: output as plot
class Entropy(Sink):
def __init__(self):
super().__init__('entropy')
self.length = 0
self.counter = Counter()
def update(self, data):
self.length += len(data)
self.counter.update(data)
def digest(self):
# calculate binary entropy as -Σ(1…n) p_i × log₂(p_i)
entropy = -sum(count / self.length * log2(count / self.length) for count in self.counter.values())
return '{:.8f}'.format(entropy)
Remove TODO's converted to issuesfrom collections import Counter
from math import log2
from digestive import Sink
class Entropy(Sink):
def __init__(self):
super().__init__('entropy')
self.length = 0
self.counter = Counter()
def update(self, data):
self.length += len(data)
self.counter.update(data)
def digest(self):
# calculate binary entropy as -Σ(1…n) p_i × log₂(p_i)
entropy = -sum(count / self.length * log2(count / self.length) for count in self.counter.values())
return '{:.8f}'.format(entropy)
|
<commit_before>from collections import Counter
from math import log2
from digestive import Sink
# TODO: stash intermediate histograms in multiple Counters?
# TODO: output as a spark
# TODO: output as plot
class Entropy(Sink):
def __init__(self):
super().__init__('entropy')
self.length = 0
self.counter = Counter()
def update(self, data):
self.length += len(data)
self.counter.update(data)
def digest(self):
# calculate binary entropy as -Σ(1…n) p_i × log₂(p_i)
entropy = -sum(count / self.length * log2(count / self.length) for count in self.counter.values())
return '{:.8f}'.format(entropy)
<commit_msg>Remove TODO's converted to issues<commit_after>from collections import Counter
from math import log2
from digestive import Sink
class Entropy(Sink):
def __init__(self):
super().__init__('entropy')
self.length = 0
self.counter = Counter()
def update(self, data):
self.length += len(data)
self.counter.update(data)
def digest(self):
# calculate binary entropy as -Σ(1…n) p_i × log₂(p_i)
entropy = -sum(count / self.length * log2(count / self.length) for count in self.counter.values())
return '{:.8f}'.format(entropy)
|
bada6787aa111feac1df32952a8732400632f81d
|
doc/examples/plot_pyramid.py
|
doc/examples/plot_pyramid.py
|
"""
====================
Build image pyramids
====================
The `build_gaussian_pyramid` function takes an image and yields successive
images shrunk by a constant scale factor. Image pyramids are often used, e.g.,
to implement algorithms for denoising, texture discrimination, and scale-
invariant detection.
"""
import numpy as np
import matplotlib.pyplot as plt
from skimage import data
from skimage.transform import pyramid_gaussian
image = data.lena()
rows, cols, dim = image.shape
pyramid = tuple(pyramid_gaussian(image, downscale=2))
composite_image = np.zeros((rows, cols + cols / 2, 3), dtype=np.double)
composite_image[:rows, :cols, :] = pyramid[0]
i_row = 0
for p in pyramid[1:]:
n_rows, n_cols = p.shape[:2]
composite_image[i_row:i_row + n_rows, cols:cols + n_cols] = p
i_row += n_rows
plt.imshow(composite_image)
plt.show()
|
"""
====================
Build image pyramids
====================
The `pyramid_gaussian` function takes an image and yields successive images
shrunk by a constant scale factor. Image pyramids are often used, e.g., to
implement algorithms for denoising, texture discrimination, and scale- invariant
detection.
"""
import numpy as np
import matplotlib.pyplot as plt
from skimage import data
from skimage.transform import pyramid_gaussian
image = data.lena()
rows, cols, dim = image.shape
pyramid = tuple(pyramid_gaussian(image, downscale=2))
composite_image = np.zeros((rows, cols + cols / 2, 3), dtype=np.double)
composite_image[:rows, :cols, :] = pyramid[0]
i_row = 0
for p in pyramid[1:]:
n_rows, n_cols = p.shape[:2]
composite_image[i_row:i_row + n_rows, cols:cols + n_cols] = p
i_row += n_rows
plt.imshow(composite_image)
plt.show()
|
Update name of pyramid function in pyramid example description
|
Update name of pyramid function in pyramid example description
|
Python
|
bsd-3-clause
|
blink1073/scikit-image,warmspringwinds/scikit-image,keflavich/scikit-image,almarklein/scikit-image,blink1073/scikit-image,chintak/scikit-image,robintw/scikit-image,ajaybhat/scikit-image,ClinicalGraphics/scikit-image,SamHames/scikit-image,ofgulban/scikit-image,newville/scikit-image,emon10005/scikit-image,michaelaye/scikit-image,vighneshbirodkar/scikit-image,youprofit/scikit-image,ajaybhat/scikit-image,ClinicalGraphics/scikit-image,chriscrosscutler/scikit-image,rjeli/scikit-image,chintak/scikit-image,youprofit/scikit-image,robintw/scikit-image,chintak/scikit-image,keflavich/scikit-image,michaelpacer/scikit-image,Britefury/scikit-image,almarklein/scikit-image,Midafi/scikit-image,pratapvardhan/scikit-image,chintak/scikit-image,Hiyorimi/scikit-image,Midafi/scikit-image,WarrenWeckesser/scikits-image,SamHames/scikit-image,almarklein/scikit-image,vighneshbirodkar/scikit-image,dpshelio/scikit-image,paalge/scikit-image,juliusbierk/scikit-image,Britefury/scikit-image,paalge/scikit-image,SamHames/scikit-image,warmspringwinds/scikit-image,chriscrosscutler/scikit-image,bsipocz/scikit-image,emon10005/scikit-image,bsipocz/scikit-image,bennlich/scikit-image,GaZ3ll3/scikit-image,juliusbierk/scikit-image,ofgulban/scikit-image,almarklein/scikit-image,pratapvardhan/scikit-image,vighneshbirodkar/scikit-image,oew1v07/scikit-image,dpshelio/scikit-image,jwiggins/scikit-image,SamHames/scikit-image,michaelaye/scikit-image,rjeli/scikit-image,jwiggins/scikit-image,michaelpacer/scikit-image,paalge/scikit-image,bennlich/scikit-image,newville/scikit-image,WarrenWeckesser/scikits-image,Hiyorimi/scikit-image,rjeli/scikit-image,GaZ3ll3/scikit-image,ofgulban/scikit-image,oew1v07/scikit-image
|
"""
====================
Build image pyramids
====================
The `build_gaussian_pyramid` function takes an image and yields successive
images shrunk by a constant scale factor. Image pyramids are often used, e.g.,
to implement algorithms for denoising, texture discrimination, and scale-
invariant detection.
"""
import numpy as np
import matplotlib.pyplot as plt
from skimage import data
from skimage.transform import pyramid_gaussian
image = data.lena()
rows, cols, dim = image.shape
pyramid = tuple(pyramid_gaussian(image, downscale=2))
composite_image = np.zeros((rows, cols + cols / 2, 3), dtype=np.double)
composite_image[:rows, :cols, :] = pyramid[0]
i_row = 0
for p in pyramid[1:]:
n_rows, n_cols = p.shape[:2]
composite_image[i_row:i_row + n_rows, cols:cols + n_cols] = p
i_row += n_rows
plt.imshow(composite_image)
plt.show()
Update name of pyramid function in pyramid example description
|
"""
====================
Build image pyramids
====================
The `pyramid_gaussian` function takes an image and yields successive images
shrunk by a constant scale factor. Image pyramids are often used, e.g., to
implement algorithms for denoising, texture discrimination, and scale- invariant
detection.
"""
import numpy as np
import matplotlib.pyplot as plt
from skimage import data
from skimage.transform import pyramid_gaussian
image = data.lena()
rows, cols, dim = image.shape
pyramid = tuple(pyramid_gaussian(image, downscale=2))
composite_image = np.zeros((rows, cols + cols / 2, 3), dtype=np.double)
composite_image[:rows, :cols, :] = pyramid[0]
i_row = 0
for p in pyramid[1:]:
n_rows, n_cols = p.shape[:2]
composite_image[i_row:i_row + n_rows, cols:cols + n_cols] = p
i_row += n_rows
plt.imshow(composite_image)
plt.show()
|
<commit_before>"""
====================
Build image pyramids
====================
The `build_gaussian_pyramid` function takes an image and yields successive
images shrunk by a constant scale factor. Image pyramids are often used, e.g.,
to implement algorithms for denoising, texture discrimination, and scale-
invariant detection.
"""
import numpy as np
import matplotlib.pyplot as plt
from skimage import data
from skimage.transform import pyramid_gaussian
image = data.lena()
rows, cols, dim = image.shape
pyramid = tuple(pyramid_gaussian(image, downscale=2))
composite_image = np.zeros((rows, cols + cols / 2, 3), dtype=np.double)
composite_image[:rows, :cols, :] = pyramid[0]
i_row = 0
for p in pyramid[1:]:
n_rows, n_cols = p.shape[:2]
composite_image[i_row:i_row + n_rows, cols:cols + n_cols] = p
i_row += n_rows
plt.imshow(composite_image)
plt.show()
<commit_msg>Update name of pyramid function in pyramid example description<commit_after>
|
"""
====================
Build image pyramids
====================
The `pyramid_gaussian` function takes an image and yields successive images
shrunk by a constant scale factor. Image pyramids are often used, e.g., to
implement algorithms for denoising, texture discrimination, and scale- invariant
detection.
"""
import numpy as np
import matplotlib.pyplot as plt
from skimage import data
from skimage.transform import pyramid_gaussian
image = data.lena()
rows, cols, dim = image.shape
pyramid = tuple(pyramid_gaussian(image, downscale=2))
composite_image = np.zeros((rows, cols + cols / 2, 3), dtype=np.double)
composite_image[:rows, :cols, :] = pyramid[0]
i_row = 0
for p in pyramid[1:]:
n_rows, n_cols = p.shape[:2]
composite_image[i_row:i_row + n_rows, cols:cols + n_cols] = p
i_row += n_rows
plt.imshow(composite_image)
plt.show()
|
"""
====================
Build image pyramids
====================
The `build_gaussian_pyramid` function takes an image and yields successive
images shrunk by a constant scale factor. Image pyramids are often used, e.g.,
to implement algorithms for denoising, texture discrimination, and scale-
invariant detection.
"""
import numpy as np
import matplotlib.pyplot as plt
from skimage import data
from skimage.transform import pyramid_gaussian
image = data.lena()
rows, cols, dim = image.shape
pyramid = tuple(pyramid_gaussian(image, downscale=2))
composite_image = np.zeros((rows, cols + cols / 2, 3), dtype=np.double)
composite_image[:rows, :cols, :] = pyramid[0]
i_row = 0
for p in pyramid[1:]:
n_rows, n_cols = p.shape[:2]
composite_image[i_row:i_row + n_rows, cols:cols + n_cols] = p
i_row += n_rows
plt.imshow(composite_image)
plt.show()
Update name of pyramid function in pyramid example description"""
====================
Build image pyramids
====================
The `pyramid_gaussian` function takes an image and yields successive images
shrunk by a constant scale factor. Image pyramids are often used, e.g., to
implement algorithms for denoising, texture discrimination, and scale- invariant
detection.
"""
import numpy as np
import matplotlib.pyplot as plt
from skimage import data
from skimage.transform import pyramid_gaussian
image = data.lena()
rows, cols, dim = image.shape
pyramid = tuple(pyramid_gaussian(image, downscale=2))
composite_image = np.zeros((rows, cols + cols / 2, 3), dtype=np.double)
composite_image[:rows, :cols, :] = pyramid[0]
i_row = 0
for p in pyramid[1:]:
n_rows, n_cols = p.shape[:2]
composite_image[i_row:i_row + n_rows, cols:cols + n_cols] = p
i_row += n_rows
plt.imshow(composite_image)
plt.show()
|
<commit_before>"""
====================
Build image pyramids
====================
The `build_gaussian_pyramid` function takes an image and yields successive
images shrunk by a constant scale factor. Image pyramids are often used, e.g.,
to implement algorithms for denoising, texture discrimination, and scale-
invariant detection.
"""
import numpy as np
import matplotlib.pyplot as plt
from skimage import data
from skimage.transform import pyramid_gaussian
image = data.lena()
rows, cols, dim = image.shape
pyramid = tuple(pyramid_gaussian(image, downscale=2))
composite_image = np.zeros((rows, cols + cols / 2, 3), dtype=np.double)
composite_image[:rows, :cols, :] = pyramid[0]
i_row = 0
for p in pyramid[1:]:
n_rows, n_cols = p.shape[:2]
composite_image[i_row:i_row + n_rows, cols:cols + n_cols] = p
i_row += n_rows
plt.imshow(composite_image)
plt.show()
<commit_msg>Update name of pyramid function in pyramid example description<commit_after>"""
====================
Build image pyramids
====================
The `pyramid_gaussian` function takes an image and yields successive images
shrunk by a constant scale factor. Image pyramids are often used, e.g., to
implement algorithms for denoising, texture discrimination, and scale- invariant
detection.
"""
import numpy as np
import matplotlib.pyplot as plt
from skimage import data
from skimage.transform import pyramid_gaussian
image = data.lena()
rows, cols, dim = image.shape
pyramid = tuple(pyramid_gaussian(image, downscale=2))
composite_image = np.zeros((rows, cols + cols / 2, 3), dtype=np.double)
composite_image[:rows, :cols, :] = pyramid[0]
i_row = 0
for p in pyramid[1:]:
n_rows, n_cols = p.shape[:2]
composite_image[i_row:i_row + n_rows, cols:cols + n_cols] = p
i_row += n_rows
plt.imshow(composite_image)
plt.show()
|
8f1b473e2dab982e989e9a041aa14e31050d2f4b
|
scripts/promote_orga.py
|
scripts/promote_orga.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Promote a user to organizer status.
:Copyright: 2006-2016 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
import click
from byceps.database import db
from bootstrap.helpers import promote_orga
from bootstrap.util import app_context, get_config_name_from_env
from bootstrap.validators import validate_brand, validate_user_screen_name
@click.command()
@click.argument('brand', callback=validate_brand)
@click.argument('user', callback=validate_user_screen_name)
def execute(brand, user):
click.echo('Promoting user "{}" to orga for brand "{}" ... '
.format(user.screen_name, brand.title), nl=False)
promote_orga(brand, user)
db.session.commit()
click.secho('done.', fg='green')
if __name__ == '__main__':
config_name = get_config_name_from_env()
with app_context(config_name):
execute()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Promote a user to organizer status.
:Copyright: 2006-2016 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
import click
from byceps.services.orga import service as orga_service
from bootstrap.util import app_context, get_config_name_from_env
from bootstrap.validators import validate_brand, validate_user_screen_name
@click.command()
@click.argument('brand', callback=validate_brand)
@click.argument('user', callback=validate_user_screen_name)
def execute(brand, user):
click.echo('Promoting user "{}" to orga for brand "{}" ... '
.format(user.screen_name, brand.title), nl=False)
orga_service.create_orga_flag(brand.id, user.id)
click.secho('done.', fg='green')
if __name__ == '__main__':
config_name = get_config_name_from_env()
with app_context(config_name):
execute()
|
Use service in script to promote a user to organizer
|
Use service in script to promote a user to organizer
|
Python
|
bsd-3-clause
|
m-ober/byceps,m-ober/byceps,homeworkprod/byceps,m-ober/byceps,homeworkprod/byceps,homeworkprod/byceps
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Promote a user to organizer status.
:Copyright: 2006-2016 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
import click
from byceps.database import db
from bootstrap.helpers import promote_orga
from bootstrap.util import app_context, get_config_name_from_env
from bootstrap.validators import validate_brand, validate_user_screen_name
@click.command()
@click.argument('brand', callback=validate_brand)
@click.argument('user', callback=validate_user_screen_name)
def execute(brand, user):
click.echo('Promoting user "{}" to orga for brand "{}" ... '
.format(user.screen_name, brand.title), nl=False)
promote_orga(brand, user)
db.session.commit()
click.secho('done.', fg='green')
if __name__ == '__main__':
config_name = get_config_name_from_env()
with app_context(config_name):
execute()
Use service in script to promote a user to organizer
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Promote a user to organizer status.
:Copyright: 2006-2016 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
import click
from byceps.services.orga import service as orga_service
from bootstrap.util import app_context, get_config_name_from_env
from bootstrap.validators import validate_brand, validate_user_screen_name
@click.command()
@click.argument('brand', callback=validate_brand)
@click.argument('user', callback=validate_user_screen_name)
def execute(brand, user):
click.echo('Promoting user "{}" to orga for brand "{}" ... '
.format(user.screen_name, brand.title), nl=False)
orga_service.create_orga_flag(brand.id, user.id)
click.secho('done.', fg='green')
if __name__ == '__main__':
config_name = get_config_name_from_env()
with app_context(config_name):
execute()
|
<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Promote a user to organizer status.
:Copyright: 2006-2016 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
import click
from byceps.database import db
from bootstrap.helpers import promote_orga
from bootstrap.util import app_context, get_config_name_from_env
from bootstrap.validators import validate_brand, validate_user_screen_name
@click.command()
@click.argument('brand', callback=validate_brand)
@click.argument('user', callback=validate_user_screen_name)
def execute(brand, user):
click.echo('Promoting user "{}" to orga for brand "{}" ... '
.format(user.screen_name, brand.title), nl=False)
promote_orga(brand, user)
db.session.commit()
click.secho('done.', fg='green')
if __name__ == '__main__':
config_name = get_config_name_from_env()
with app_context(config_name):
execute()
<commit_msg>Use service in script to promote a user to organizer<commit_after>
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Promote a user to organizer status.
:Copyright: 2006-2016 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
import click
from byceps.services.orga import service as orga_service
from bootstrap.util import app_context, get_config_name_from_env
from bootstrap.validators import validate_brand, validate_user_screen_name
@click.command()
@click.argument('brand', callback=validate_brand)
@click.argument('user', callback=validate_user_screen_name)
def execute(brand, user):
click.echo('Promoting user "{}" to orga for brand "{}" ... '
.format(user.screen_name, brand.title), nl=False)
orga_service.create_orga_flag(brand.id, user.id)
click.secho('done.', fg='green')
if __name__ == '__main__':
config_name = get_config_name_from_env()
with app_context(config_name):
execute()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Promote a user to organizer status.
:Copyright: 2006-2016 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
import click
from byceps.database import db
from bootstrap.helpers import promote_orga
from bootstrap.util import app_context, get_config_name_from_env
from bootstrap.validators import validate_brand, validate_user_screen_name
@click.command()
@click.argument('brand', callback=validate_brand)
@click.argument('user', callback=validate_user_screen_name)
def execute(brand, user):
click.echo('Promoting user "{}" to orga for brand "{}" ... '
.format(user.screen_name, brand.title), nl=False)
promote_orga(brand, user)
db.session.commit()
click.secho('done.', fg='green')
if __name__ == '__main__':
config_name = get_config_name_from_env()
with app_context(config_name):
execute()
Use service in script to promote a user to organizer#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Promote a user to organizer status.
:Copyright: 2006-2016 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
import click
from byceps.services.orga import service as orga_service
from bootstrap.util import app_context, get_config_name_from_env
from bootstrap.validators import validate_brand, validate_user_screen_name
@click.command()
@click.argument('brand', callback=validate_brand)
@click.argument('user', callback=validate_user_screen_name)
def execute(brand, user):
click.echo('Promoting user "{}" to orga for brand "{}" ... '
.format(user.screen_name, brand.title), nl=False)
orga_service.create_orga_flag(brand.id, user.id)
click.secho('done.', fg='green')
if __name__ == '__main__':
config_name = get_config_name_from_env()
with app_context(config_name):
execute()
|
<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Promote a user to organizer status.
:Copyright: 2006-2016 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
import click
from byceps.database import db
from bootstrap.helpers import promote_orga
from bootstrap.util import app_context, get_config_name_from_env
from bootstrap.validators import validate_brand, validate_user_screen_name
@click.command()
@click.argument('brand', callback=validate_brand)
@click.argument('user', callback=validate_user_screen_name)
def execute(brand, user):
click.echo('Promoting user "{}" to orga for brand "{}" ... '
.format(user.screen_name, brand.title), nl=False)
promote_orga(brand, user)
db.session.commit()
click.secho('done.', fg='green')
if __name__ == '__main__':
config_name = get_config_name_from_env()
with app_context(config_name):
execute()
<commit_msg>Use service in script to promote a user to organizer<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Promote a user to organizer status.
:Copyright: 2006-2016 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
import click
from byceps.services.orga import service as orga_service
from bootstrap.util import app_context, get_config_name_from_env
from bootstrap.validators import validate_brand, validate_user_screen_name
@click.command()
@click.argument('brand', callback=validate_brand)
@click.argument('user', callback=validate_user_screen_name)
def execute(brand, user):
click.echo('Promoting user "{}" to orga for brand "{}" ... '
.format(user.screen_name, brand.title), nl=False)
orga_service.create_orga_flag(brand.id, user.id)
click.secho('done.', fg='green')
if __name__ == '__main__':
config_name = get_config_name_from_env()
with app_context(config_name):
execute()
|
499ad0cb7147f705ebf83604b9e0873b5b0edb61
|
api/rest/scrollingpaginator.py
|
api/rest/scrollingpaginator.py
|
from rest_framework import pagination
from amcat.tools import amcates
from rest_framework.response import Response
from django.core.urlresolvers import reverse
from rest_framework.utils.urls import replace_query_param
class ScrollingPaginator(pagination.BasePagination):
def paginate_queryset(self, queryset, request, view=None):
self.request = request
es = amcates.ES()
scroll_id = request.query_params.get("scroll_id")
if scroll_id:
res = es.es.scroll(scroll_id, scroll="1m")
else:
res = es.search(scroll="1m", **queryset)
self.total = res['hits']['total']
self.scroll_id = res['_scroll_id']
self.done = not res['hits']['hits']
for hit in res['hits']['hits']:
item = {'id': hit['_id']}
if '_source' in hit:
item.update({k: v for (k, v) in hit['_source'].items()})
yield item
def get_paginated_response(self, data):
return Response({
'next': self.get_next_link(),
'results': data,
'total': self.total,
})
def get_next_link(self):
if not self.done:
url = self.request.build_absolute_uri()
return replace_query_param(url, "scroll_id", self.scroll_id)
|
from rest_framework import pagination
from amcat.tools import amcates
from rest_framework.response import Response
from django.core.urlresolvers import reverse
from rest_framework.utils.urls import replace_query_param
class ScrollingPaginator(pagination.BasePagination):
def paginate_queryset(self, queryset, request, view=None):
self.request = request
es = amcates.ES()
scroll_id = request.query_params.get("scroll_id")
scroll = request.query_params.get("scroll", "1m")
if scroll_id:
res = es.es.scroll(scroll_id, scroll=scroll)
else:
res = es.search(scroll=scroll, **queryset)
self.total = res['hits']['total']
self.scroll_id = res['_scroll_id']
self.done = not res['hits']['hits']
for hit in res['hits']['hits']:
item = {'id': hit['_id']}
if '_source' in hit:
item.update({k: v for (k, v) in hit['_source'].items()})
yield item
def get_paginated_response(self, data):
return Response({
'next': self.get_next_link(),
'results': data,
'total': self.total,
})
def get_next_link(self):
if not self.done:
url = self.request.build_absolute_uri()
return replace_query_param(url, "scroll_id", self.scroll_id)
|
Allow set scroll timeout param
|
Allow set scroll timeout param
|
Python
|
agpl-3.0
|
amcat/amcat,amcat/amcat,amcat/amcat,amcat/amcat,amcat/amcat,amcat/amcat
|
from rest_framework import pagination
from amcat.tools import amcates
from rest_framework.response import Response
from django.core.urlresolvers import reverse
from rest_framework.utils.urls import replace_query_param
class ScrollingPaginator(pagination.BasePagination):
def paginate_queryset(self, queryset, request, view=None):
self.request = request
es = amcates.ES()
scroll_id = request.query_params.get("scroll_id")
if scroll_id:
res = es.es.scroll(scroll_id, scroll="1m")
else:
res = es.search(scroll="1m", **queryset)
self.total = res['hits']['total']
self.scroll_id = res['_scroll_id']
self.done = not res['hits']['hits']
for hit in res['hits']['hits']:
item = {'id': hit['_id']}
if '_source' in hit:
item.update({k: v for (k, v) in hit['_source'].items()})
yield item
def get_paginated_response(self, data):
return Response({
'next': self.get_next_link(),
'results': data,
'total': self.total,
})
def get_next_link(self):
if not self.done:
url = self.request.build_absolute_uri()
return replace_query_param(url, "scroll_id", self.scroll_id)
Allow set scroll timeout param
|
from rest_framework import pagination
from amcat.tools import amcates
from rest_framework.response import Response
from django.core.urlresolvers import reverse
from rest_framework.utils.urls import replace_query_param
class ScrollingPaginator(pagination.BasePagination):
def paginate_queryset(self, queryset, request, view=None):
self.request = request
es = amcates.ES()
scroll_id = request.query_params.get("scroll_id")
scroll = request.query_params.get("scroll", "1m")
if scroll_id:
res = es.es.scroll(scroll_id, scroll=scroll)
else:
res = es.search(scroll=scroll, **queryset)
self.total = res['hits']['total']
self.scroll_id = res['_scroll_id']
self.done = not res['hits']['hits']
for hit in res['hits']['hits']:
item = {'id': hit['_id']}
if '_source' in hit:
item.update({k: v for (k, v) in hit['_source'].items()})
yield item
def get_paginated_response(self, data):
return Response({
'next': self.get_next_link(),
'results': data,
'total': self.total,
})
def get_next_link(self):
if not self.done:
url = self.request.build_absolute_uri()
return replace_query_param(url, "scroll_id", self.scroll_id)
|
<commit_before>from rest_framework import pagination
from amcat.tools import amcates
from rest_framework.response import Response
from django.core.urlresolvers import reverse
from rest_framework.utils.urls import replace_query_param
class ScrollingPaginator(pagination.BasePagination):
def paginate_queryset(self, queryset, request, view=None):
self.request = request
es = amcates.ES()
scroll_id = request.query_params.get("scroll_id")
if scroll_id:
res = es.es.scroll(scroll_id, scroll="1m")
else:
res = es.search(scroll="1m", **queryset)
self.total = res['hits']['total']
self.scroll_id = res['_scroll_id']
self.done = not res['hits']['hits']
for hit in res['hits']['hits']:
item = {'id': hit['_id']}
if '_source' in hit:
item.update({k: v for (k, v) in hit['_source'].items()})
yield item
def get_paginated_response(self, data):
return Response({
'next': self.get_next_link(),
'results': data,
'total': self.total,
})
def get_next_link(self):
if not self.done:
url = self.request.build_absolute_uri()
return replace_query_param(url, "scroll_id", self.scroll_id)
<commit_msg>Allow set scroll timeout param<commit_after>
|
from rest_framework import pagination
from amcat.tools import amcates
from rest_framework.response import Response
from django.core.urlresolvers import reverse
from rest_framework.utils.urls import replace_query_param
class ScrollingPaginator(pagination.BasePagination):
def paginate_queryset(self, queryset, request, view=None):
self.request = request
es = amcates.ES()
scroll_id = request.query_params.get("scroll_id")
scroll = request.query_params.get("scroll", "1m")
if scroll_id:
res = es.es.scroll(scroll_id, scroll=scroll)
else:
res = es.search(scroll=scroll, **queryset)
self.total = res['hits']['total']
self.scroll_id = res['_scroll_id']
self.done = not res['hits']['hits']
for hit in res['hits']['hits']:
item = {'id': hit['_id']}
if '_source' in hit:
item.update({k: v for (k, v) in hit['_source'].items()})
yield item
def get_paginated_response(self, data):
return Response({
'next': self.get_next_link(),
'results': data,
'total': self.total,
})
def get_next_link(self):
if not self.done:
url = self.request.build_absolute_uri()
return replace_query_param(url, "scroll_id", self.scroll_id)
|
from rest_framework import pagination
from amcat.tools import amcates
from rest_framework.response import Response
from django.core.urlresolvers import reverse
from rest_framework.utils.urls import replace_query_param
class ScrollingPaginator(pagination.BasePagination):
def paginate_queryset(self, queryset, request, view=None):
self.request = request
es = amcates.ES()
scroll_id = request.query_params.get("scroll_id")
if scroll_id:
res = es.es.scroll(scroll_id, scroll="1m")
else:
res = es.search(scroll="1m", **queryset)
self.total = res['hits']['total']
self.scroll_id = res['_scroll_id']
self.done = not res['hits']['hits']
for hit in res['hits']['hits']:
item = {'id': hit['_id']}
if '_source' in hit:
item.update({k: v for (k, v) in hit['_source'].items()})
yield item
def get_paginated_response(self, data):
return Response({
'next': self.get_next_link(),
'results': data,
'total': self.total,
})
def get_next_link(self):
if not self.done:
url = self.request.build_absolute_uri()
return replace_query_param(url, "scroll_id", self.scroll_id)
Allow set scroll timeout paramfrom rest_framework import pagination
from amcat.tools import amcates
from rest_framework.response import Response
from django.core.urlresolvers import reverse
from rest_framework.utils.urls import replace_query_param
class ScrollingPaginator(pagination.BasePagination):
def paginate_queryset(self, queryset, request, view=None):
self.request = request
es = amcates.ES()
scroll_id = request.query_params.get("scroll_id")
scroll = request.query_params.get("scroll", "1m")
if scroll_id:
res = es.es.scroll(scroll_id, scroll=scroll)
else:
res = es.search(scroll=scroll, **queryset)
self.total = res['hits']['total']
self.scroll_id = res['_scroll_id']
self.done = not res['hits']['hits']
for hit in res['hits']['hits']:
item = {'id': hit['_id']}
if '_source' in hit:
item.update({k: v for (k, v) in hit['_source'].items()})
yield item
def get_paginated_response(self, data):
return Response({
'next': self.get_next_link(),
'results': data,
'total': self.total,
})
def get_next_link(self):
if not self.done:
url = self.request.build_absolute_uri()
return replace_query_param(url, "scroll_id", self.scroll_id)
|
<commit_before>from rest_framework import pagination
from amcat.tools import amcates
from rest_framework.response import Response
from django.core.urlresolvers import reverse
from rest_framework.utils.urls import replace_query_param
class ScrollingPaginator(pagination.BasePagination):
def paginate_queryset(self, queryset, request, view=None):
self.request = request
es = amcates.ES()
scroll_id = request.query_params.get("scroll_id")
if scroll_id:
res = es.es.scroll(scroll_id, scroll="1m")
else:
res = es.search(scroll="1m", **queryset)
self.total = res['hits']['total']
self.scroll_id = res['_scroll_id']
self.done = not res['hits']['hits']
for hit in res['hits']['hits']:
item = {'id': hit['_id']}
if '_source' in hit:
item.update({k: v for (k, v) in hit['_source'].items()})
yield item
def get_paginated_response(self, data):
return Response({
'next': self.get_next_link(),
'results': data,
'total': self.total,
})
def get_next_link(self):
if not self.done:
url = self.request.build_absolute_uri()
return replace_query_param(url, "scroll_id", self.scroll_id)
<commit_msg>Allow set scroll timeout param<commit_after>from rest_framework import pagination
from amcat.tools import amcates
from rest_framework.response import Response
from django.core.urlresolvers import reverse
from rest_framework.utils.urls import replace_query_param
class ScrollingPaginator(pagination.BasePagination):
def paginate_queryset(self, queryset, request, view=None):
self.request = request
es = amcates.ES()
scroll_id = request.query_params.get("scroll_id")
scroll = request.query_params.get("scroll", "1m")
if scroll_id:
res = es.es.scroll(scroll_id, scroll=scroll)
else:
res = es.search(scroll=scroll, **queryset)
self.total = res['hits']['total']
self.scroll_id = res['_scroll_id']
self.done = not res['hits']['hits']
for hit in res['hits']['hits']:
item = {'id': hit['_id']}
if '_source' in hit:
item.update({k: v for (k, v) in hit['_source'].items()})
yield item
def get_paginated_response(self, data):
return Response({
'next': self.get_next_link(),
'results': data,
'total': self.total,
})
def get_next_link(self):
if not self.done:
url = self.request.build_absolute_uri()
return replace_query_param(url, "scroll_id", self.scroll_id)
|
99c00b309e89ceb32528c217e308b91f94a56e2b
|
cogs/command_log.py
|
cogs/command_log.py
|
import logging
class CommandLog:
"""A simple cog to log commands executed."""
def __init__(self):
self.log = logging.getLogger('liara.command_log')
async def on_command(self, ctx):
self.log.info('{0.author} ({0.author.id}) executed command "{0.command}" in {0.guild}'.format(ctx))
def setup(liara):
liara.add_cog(CommandLog())
|
import logging
class CommandLog:
"""A simple cog to log commands executed."""
def __init__(self):
self.log = logging.getLogger('liara.command_log')
async def on_command(self, ctx):
kwargs = ', '.join(['{}={}'.format(k, repr(v)) for k, v in ctx.kwargs.items()])
args = 'with arguments {} '.format(kwargs) if kwargs else ''
self.log.info('{0.author} ({0.author.id}) executed command "{0.command}" {1}in {0.guild} ({0.guild.id})'
.format(ctx, args))
def setup(liara):
liara.add_cog(CommandLog())
|
Make the command log more detailed
|
Make the command log more detailed
|
Python
|
mit
|
Thessia/Liara
|
import logging
class CommandLog:
"""A simple cog to log commands executed."""
def __init__(self):
self.log = logging.getLogger('liara.command_log')
async def on_command(self, ctx):
self.log.info('{0.author} ({0.author.id}) executed command "{0.command}" in {0.guild}'.format(ctx))
def setup(liara):
liara.add_cog(CommandLog())
Make the command log more detailed
|
import logging
class CommandLog:
"""A simple cog to log commands executed."""
def __init__(self):
self.log = logging.getLogger('liara.command_log')
async def on_command(self, ctx):
kwargs = ', '.join(['{}={}'.format(k, repr(v)) for k, v in ctx.kwargs.items()])
args = 'with arguments {} '.format(kwargs) if kwargs else ''
self.log.info('{0.author} ({0.author.id}) executed command "{0.command}" {1}in {0.guild} ({0.guild.id})'
.format(ctx, args))
def setup(liara):
liara.add_cog(CommandLog())
|
<commit_before>import logging
class CommandLog:
"""A simple cog to log commands executed."""
def __init__(self):
self.log = logging.getLogger('liara.command_log')
async def on_command(self, ctx):
self.log.info('{0.author} ({0.author.id}) executed command "{0.command}" in {0.guild}'.format(ctx))
def setup(liara):
liara.add_cog(CommandLog())
<commit_msg>Make the command log more detailed<commit_after>
|
import logging
class CommandLog:
"""A simple cog to log commands executed."""
def __init__(self):
self.log = logging.getLogger('liara.command_log')
async def on_command(self, ctx):
kwargs = ', '.join(['{}={}'.format(k, repr(v)) for k, v in ctx.kwargs.items()])
args = 'with arguments {} '.format(kwargs) if kwargs else ''
self.log.info('{0.author} ({0.author.id}) executed command "{0.command}" {1}in {0.guild} ({0.guild.id})'
.format(ctx, args))
def setup(liara):
liara.add_cog(CommandLog())
|
import logging
class CommandLog:
"""A simple cog to log commands executed."""
def __init__(self):
self.log = logging.getLogger('liara.command_log')
async def on_command(self, ctx):
self.log.info('{0.author} ({0.author.id}) executed command "{0.command}" in {0.guild}'.format(ctx))
def setup(liara):
liara.add_cog(CommandLog())
Make the command log more detailedimport logging
class CommandLog:
"""A simple cog to log commands executed."""
def __init__(self):
self.log = logging.getLogger('liara.command_log')
async def on_command(self, ctx):
kwargs = ', '.join(['{}={}'.format(k, repr(v)) for k, v in ctx.kwargs.items()])
args = 'with arguments {} '.format(kwargs) if kwargs else ''
self.log.info('{0.author} ({0.author.id}) executed command "{0.command}" {1}in {0.guild} ({0.guild.id})'
.format(ctx, args))
def setup(liara):
liara.add_cog(CommandLog())
|
<commit_before>import logging
class CommandLog:
"""A simple cog to log commands executed."""
def __init__(self):
self.log = logging.getLogger('liara.command_log')
async def on_command(self, ctx):
self.log.info('{0.author} ({0.author.id}) executed command "{0.command}" in {0.guild}'.format(ctx))
def setup(liara):
liara.add_cog(CommandLog())
<commit_msg>Make the command log more detailed<commit_after>import logging
class CommandLog:
"""A simple cog to log commands executed."""
def __init__(self):
self.log = logging.getLogger('liara.command_log')
async def on_command(self, ctx):
kwargs = ', '.join(['{}={}'.format(k, repr(v)) for k, v in ctx.kwargs.items()])
args = 'with arguments {} '.format(kwargs) if kwargs else ''
self.log.info('{0.author} ({0.author.id}) executed command "{0.command}" {1}in {0.guild} ({0.guild.id})'
.format(ctx, args))
def setup(liara):
liara.add_cog(CommandLog())
|
5a319a118868336cdbca72808b1bf4f6929ce8de
|
tests/test_tools.py
|
tests/test_tools.py
|
# -*- coding: utf-8 -*-
import unittest
from pythainlp.tools import (
get_full_data_path,
get_pythainlp_data_path,
get_pythainlp_path,
)
class TestToolsPackage(unittest.TestCase):
def test_path(self):
data_filename = "ttc_freq.txt"
self.assertTrue(
get_full_data_path(data_filename).endswith(data_filename)
)
self.assertTrue(isinstance(get_pythainlp_data_path(), str))
self.assertTrue(isinstance(get_pythainlp_path, str))
|
# -*- coding: utf-8 -*-
import unittest
from pythainlp.tools import (
get_full_data_path,
get_pythainlp_data_path,
get_pythainlp_path,
)
class TestToolsPackage(unittest.TestCase):
def test_path(self):
data_filename = "ttc_freq.txt"
self.assertTrue(
get_full_data_path(data_filename).endswith(data_filename)
)
self.assertTrue(isinstance(get_pythainlp_data_path(), str))
self.assertTrue(isinstance(get_pythainlp_path(), str))
|
Fix test case for tools.path
|
Fix test case for tools.path
|
Python
|
apache-2.0
|
PyThaiNLP/pythainlp
|
# -*- coding: utf-8 -*-
import unittest
from pythainlp.tools import (
get_full_data_path,
get_pythainlp_data_path,
get_pythainlp_path,
)
class TestToolsPackage(unittest.TestCase):
def test_path(self):
data_filename = "ttc_freq.txt"
self.assertTrue(
get_full_data_path(data_filename).endswith(data_filename)
)
self.assertTrue(isinstance(get_pythainlp_data_path(), str))
self.assertTrue(isinstance(get_pythainlp_path, str))
Fix test case for tools.path
|
# -*- coding: utf-8 -*-
import unittest
from pythainlp.tools import (
get_full_data_path,
get_pythainlp_data_path,
get_pythainlp_path,
)
class TestToolsPackage(unittest.TestCase):
def test_path(self):
data_filename = "ttc_freq.txt"
self.assertTrue(
get_full_data_path(data_filename).endswith(data_filename)
)
self.assertTrue(isinstance(get_pythainlp_data_path(), str))
self.assertTrue(isinstance(get_pythainlp_path(), str))
|
<commit_before># -*- coding: utf-8 -*-
import unittest
from pythainlp.tools import (
get_full_data_path,
get_pythainlp_data_path,
get_pythainlp_path,
)
class TestToolsPackage(unittest.TestCase):
def test_path(self):
data_filename = "ttc_freq.txt"
self.assertTrue(
get_full_data_path(data_filename).endswith(data_filename)
)
self.assertTrue(isinstance(get_pythainlp_data_path(), str))
self.assertTrue(isinstance(get_pythainlp_path, str))
<commit_msg>Fix test case for tools.path<commit_after>
|
# -*- coding: utf-8 -*-
import unittest
from pythainlp.tools import (
get_full_data_path,
get_pythainlp_data_path,
get_pythainlp_path,
)
class TestToolsPackage(unittest.TestCase):
def test_path(self):
data_filename = "ttc_freq.txt"
self.assertTrue(
get_full_data_path(data_filename).endswith(data_filename)
)
self.assertTrue(isinstance(get_pythainlp_data_path(), str))
self.assertTrue(isinstance(get_pythainlp_path(), str))
|
# -*- coding: utf-8 -*-
import unittest
from pythainlp.tools import (
get_full_data_path,
get_pythainlp_data_path,
get_pythainlp_path,
)
class TestToolsPackage(unittest.TestCase):
def test_path(self):
data_filename = "ttc_freq.txt"
self.assertTrue(
get_full_data_path(data_filename).endswith(data_filename)
)
self.assertTrue(isinstance(get_pythainlp_data_path(), str))
self.assertTrue(isinstance(get_pythainlp_path, str))
Fix test case for tools.path# -*- coding: utf-8 -*-
import unittest
from pythainlp.tools import (
get_full_data_path,
get_pythainlp_data_path,
get_pythainlp_path,
)
class TestToolsPackage(unittest.TestCase):
def test_path(self):
data_filename = "ttc_freq.txt"
self.assertTrue(
get_full_data_path(data_filename).endswith(data_filename)
)
self.assertTrue(isinstance(get_pythainlp_data_path(), str))
self.assertTrue(isinstance(get_pythainlp_path(), str))
|
<commit_before># -*- coding: utf-8 -*-
import unittest
from pythainlp.tools import (
get_full_data_path,
get_pythainlp_data_path,
get_pythainlp_path,
)
class TestToolsPackage(unittest.TestCase):
def test_path(self):
data_filename = "ttc_freq.txt"
self.assertTrue(
get_full_data_path(data_filename).endswith(data_filename)
)
self.assertTrue(isinstance(get_pythainlp_data_path(), str))
self.assertTrue(isinstance(get_pythainlp_path, str))
<commit_msg>Fix test case for tools.path<commit_after># -*- coding: utf-8 -*-
import unittest
from pythainlp.tools import (
get_full_data_path,
get_pythainlp_data_path,
get_pythainlp_path,
)
class TestToolsPackage(unittest.TestCase):
def test_path(self):
data_filename = "ttc_freq.txt"
self.assertTrue(
get_full_data_path(data_filename).endswith(data_filename)
)
self.assertTrue(isinstance(get_pythainlp_data_path(), str))
self.assertTrue(isinstance(get_pythainlp_path(), str))
|
ebaca4f2572d7db9d9bc912f209cd9027750b3a7
|
tingbot/__init__.py
|
tingbot/__init__.py
|
try:
import pygame
except ImportError:
print 'Failed to import pygame'
print '-----------------------'
print ''
print 'tingbot-python requires pygame. Please download and install pygame 1.9.1'
print 'or later from http://www.pygame.org/download.shtml'
print ''
print "If you're using a virtualenv, you should make the virtualenv with the "
print "--system-site-packages flag so the system-wide installation is still "
print "accessible."
print ''
print '-----------------------'
print ''
raise
from . import platform_specific, input
from .graphics import screen, Surface, Image
from .run_loop import main_run_loop, every, once
from .input import touch
from .button import press
from .web import webhook
from .settings import config
platform_specific.fixup_env()
def run(loop=None):
if loop is not None:
every(seconds=1.0/30)(loop)
main_run_loop.add_after_action_callback(screen.update_if_needed)
main_run_loop.add_wait_callback(input.poll)
# in case screen updates happen in input.poll...
main_run_loop.add_wait_callback(screen.update_if_needed)
main_run_loop.run()
__all__ = ['run', 'screen', 'Surface', 'Image', 'every', 'touch', 'press', 'button', 'webhook']
__author__ = 'Joe Rickerby'
__email__ = '[email protected]'
__version__ = '0.3'
|
try:
import pygame
except ImportError:
print 'Failed to import pygame'
print '-----------------------'
print ''
print 'tingbot-python requires pygame. Please download and install pygame 1.9.1'
print 'or later from http://www.pygame.org/download.shtml'
print ''
print "If you're using a virtualenv, you should make the virtualenv with the "
print "--system-site-packages flag so the system-wide installation is still "
print "accessible."
print ''
print '-----------------------'
print ''
raise
from . import platform_specific, input
from .graphics import screen, Surface, Image
from .run_loop import main_run_loop, every, once
from .input import touch
from .button import press
from .web import webhook
from .tingapp import app
platform_specific.fixup_env()
def run(loop=None):
if loop is not None:
every(seconds=1.0/30)(loop)
main_run_loop.add_after_action_callback(screen.update_if_needed)
main_run_loop.add_wait_callback(input.poll)
# in case screen updates happen in input.poll...
main_run_loop.add_wait_callback(screen.update_if_needed)
main_run_loop.run()
__all__ = ['run', 'screen', 'Surface', 'Image', 'every', 'touch', 'press', 'button', 'webhook']
__author__ = 'Joe Rickerby'
__email__ = '[email protected]'
__version__ = '0.3'
|
Create reference to app in module
|
Create reference to app in module
|
Python
|
bsd-2-clause
|
furbrain/tingbot-python
|
try:
import pygame
except ImportError:
print 'Failed to import pygame'
print '-----------------------'
print ''
print 'tingbot-python requires pygame. Please download and install pygame 1.9.1'
print 'or later from http://www.pygame.org/download.shtml'
print ''
print "If you're using a virtualenv, you should make the virtualenv with the "
print "--system-site-packages flag so the system-wide installation is still "
print "accessible."
print ''
print '-----------------------'
print ''
raise
from . import platform_specific, input
from .graphics import screen, Surface, Image
from .run_loop import main_run_loop, every, once
from .input import touch
from .button import press
from .web import webhook
from .settings import config
platform_specific.fixup_env()
def run(loop=None):
if loop is not None:
every(seconds=1.0/30)(loop)
main_run_loop.add_after_action_callback(screen.update_if_needed)
main_run_loop.add_wait_callback(input.poll)
# in case screen updates happen in input.poll...
main_run_loop.add_wait_callback(screen.update_if_needed)
main_run_loop.run()
__all__ = ['run', 'screen', 'Surface', 'Image', 'every', 'touch', 'press', 'button', 'webhook']
__author__ = 'Joe Rickerby'
__email__ = '[email protected]'
__version__ = '0.3'
Create reference to app in module
|
try:
import pygame
except ImportError:
print 'Failed to import pygame'
print '-----------------------'
print ''
print 'tingbot-python requires pygame. Please download and install pygame 1.9.1'
print 'or later from http://www.pygame.org/download.shtml'
print ''
print "If you're using a virtualenv, you should make the virtualenv with the "
print "--system-site-packages flag so the system-wide installation is still "
print "accessible."
print ''
print '-----------------------'
print ''
raise
from . import platform_specific, input
from .graphics import screen, Surface, Image
from .run_loop import main_run_loop, every, once
from .input import touch
from .button import press
from .web import webhook
from .tingapp import app
platform_specific.fixup_env()
def run(loop=None):
if loop is not None:
every(seconds=1.0/30)(loop)
main_run_loop.add_after_action_callback(screen.update_if_needed)
main_run_loop.add_wait_callback(input.poll)
# in case screen updates happen in input.poll...
main_run_loop.add_wait_callback(screen.update_if_needed)
main_run_loop.run()
__all__ = ['run', 'screen', 'Surface', 'Image', 'every', 'touch', 'press', 'button', 'webhook']
__author__ = 'Joe Rickerby'
__email__ = '[email protected]'
__version__ = '0.3'
|
<commit_before>try:
import pygame
except ImportError:
print 'Failed to import pygame'
print '-----------------------'
print ''
print 'tingbot-python requires pygame. Please download and install pygame 1.9.1'
print 'or later from http://www.pygame.org/download.shtml'
print ''
print "If you're using a virtualenv, you should make the virtualenv with the "
print "--system-site-packages flag so the system-wide installation is still "
print "accessible."
print ''
print '-----------------------'
print ''
raise
from . import platform_specific, input
from .graphics import screen, Surface, Image
from .run_loop import main_run_loop, every, once
from .input import touch
from .button import press
from .web import webhook
from .settings import config
platform_specific.fixup_env()
def run(loop=None):
if loop is not None:
every(seconds=1.0/30)(loop)
main_run_loop.add_after_action_callback(screen.update_if_needed)
main_run_loop.add_wait_callback(input.poll)
# in case screen updates happen in input.poll...
main_run_loop.add_wait_callback(screen.update_if_needed)
main_run_loop.run()
__all__ = ['run', 'screen', 'Surface', 'Image', 'every', 'touch', 'press', 'button', 'webhook']
__author__ = 'Joe Rickerby'
__email__ = '[email protected]'
__version__ = '0.3'
<commit_msg>Create reference to app in module<commit_after>
|
try:
import pygame
except ImportError:
print 'Failed to import pygame'
print '-----------------------'
print ''
print 'tingbot-python requires pygame. Please download and install pygame 1.9.1'
print 'or later from http://www.pygame.org/download.shtml'
print ''
print "If you're using a virtualenv, you should make the virtualenv with the "
print "--system-site-packages flag so the system-wide installation is still "
print "accessible."
print ''
print '-----------------------'
print ''
raise
from . import platform_specific, input
from .graphics import screen, Surface, Image
from .run_loop import main_run_loop, every, once
from .input import touch
from .button import press
from .web import webhook
from .tingapp import app
platform_specific.fixup_env()
def run(loop=None):
if loop is not None:
every(seconds=1.0/30)(loop)
main_run_loop.add_after_action_callback(screen.update_if_needed)
main_run_loop.add_wait_callback(input.poll)
# in case screen updates happen in input.poll...
main_run_loop.add_wait_callback(screen.update_if_needed)
main_run_loop.run()
__all__ = ['run', 'screen', 'Surface', 'Image', 'every', 'touch', 'press', 'button', 'webhook']
__author__ = 'Joe Rickerby'
__email__ = '[email protected]'
__version__ = '0.3'
|
try:
import pygame
except ImportError:
print 'Failed to import pygame'
print '-----------------------'
print ''
print 'tingbot-python requires pygame. Please download and install pygame 1.9.1'
print 'or later from http://www.pygame.org/download.shtml'
print ''
print "If you're using a virtualenv, you should make the virtualenv with the "
print "--system-site-packages flag so the system-wide installation is still "
print "accessible."
print ''
print '-----------------------'
print ''
raise
from . import platform_specific, input
from .graphics import screen, Surface, Image
from .run_loop import main_run_loop, every, once
from .input import touch
from .button import press
from .web import webhook
from .settings import config
platform_specific.fixup_env()
def run(loop=None):
if loop is not None:
every(seconds=1.0/30)(loop)
main_run_loop.add_after_action_callback(screen.update_if_needed)
main_run_loop.add_wait_callback(input.poll)
# in case screen updates happen in input.poll...
main_run_loop.add_wait_callback(screen.update_if_needed)
main_run_loop.run()
__all__ = ['run', 'screen', 'Surface', 'Image', 'every', 'touch', 'press', 'button', 'webhook']
__author__ = 'Joe Rickerby'
__email__ = '[email protected]'
__version__ = '0.3'
Create reference to app in moduletry:
import pygame
except ImportError:
print 'Failed to import pygame'
print '-----------------------'
print ''
print 'tingbot-python requires pygame. Please download and install pygame 1.9.1'
print 'or later from http://www.pygame.org/download.shtml'
print ''
print "If you're using a virtualenv, you should make the virtualenv with the "
print "--system-site-packages flag so the system-wide installation is still "
print "accessible."
print ''
print '-----------------------'
print ''
raise
from . import platform_specific, input
from .graphics import screen, Surface, Image
from .run_loop import main_run_loop, every, once
from .input import touch
from .button import press
from .web import webhook
from .tingapp import app
platform_specific.fixup_env()
def run(loop=None):
if loop is not None:
every(seconds=1.0/30)(loop)
main_run_loop.add_after_action_callback(screen.update_if_needed)
main_run_loop.add_wait_callback(input.poll)
# in case screen updates happen in input.poll...
main_run_loop.add_wait_callback(screen.update_if_needed)
main_run_loop.run()
__all__ = ['run', 'screen', 'Surface', 'Image', 'every', 'touch', 'press', 'button', 'webhook']
__author__ = 'Joe Rickerby'
__email__ = '[email protected]'
__version__ = '0.3'
|
<commit_before>try:
import pygame
except ImportError:
print 'Failed to import pygame'
print '-----------------------'
print ''
print 'tingbot-python requires pygame. Please download and install pygame 1.9.1'
print 'or later from http://www.pygame.org/download.shtml'
print ''
print "If you're using a virtualenv, you should make the virtualenv with the "
print "--system-site-packages flag so the system-wide installation is still "
print "accessible."
print ''
print '-----------------------'
print ''
raise
from . import platform_specific, input
from .graphics import screen, Surface, Image
from .run_loop import main_run_loop, every, once
from .input import touch
from .button import press
from .web import webhook
from .settings import config
platform_specific.fixup_env()
def run(loop=None):
if loop is not None:
every(seconds=1.0/30)(loop)
main_run_loop.add_after_action_callback(screen.update_if_needed)
main_run_loop.add_wait_callback(input.poll)
# in case screen updates happen in input.poll...
main_run_loop.add_wait_callback(screen.update_if_needed)
main_run_loop.run()
__all__ = ['run', 'screen', 'Surface', 'Image', 'every', 'touch', 'press', 'button', 'webhook']
__author__ = 'Joe Rickerby'
__email__ = '[email protected]'
__version__ = '0.3'
<commit_msg>Create reference to app in module<commit_after>try:
import pygame
except ImportError:
print 'Failed to import pygame'
print '-----------------------'
print ''
print 'tingbot-python requires pygame. Please download and install pygame 1.9.1'
print 'or later from http://www.pygame.org/download.shtml'
print ''
print "If you're using a virtualenv, you should make the virtualenv with the "
print "--system-site-packages flag so the system-wide installation is still "
print "accessible."
print ''
print '-----------------------'
print ''
raise
from . import platform_specific, input
from .graphics import screen, Surface, Image
from .run_loop import main_run_loop, every, once
from .input import touch
from .button import press
from .web import webhook
from .tingapp import app
platform_specific.fixup_env()
def run(loop=None):
if loop is not None:
every(seconds=1.0/30)(loop)
main_run_loop.add_after_action_callback(screen.update_if_needed)
main_run_loop.add_wait_callback(input.poll)
# in case screen updates happen in input.poll...
main_run_loop.add_wait_callback(screen.update_if_needed)
main_run_loop.run()
__all__ = ['run', 'screen', 'Surface', 'Image', 'every', 'touch', 'press', 'button', 'webhook']
__author__ = 'Joe Rickerby'
__email__ = '[email protected]'
__version__ = '0.3'
|
a7d010d591761a459320e904045140ec21670439
|
src/oscar/templatetags/currency_filters.py
|
src/oscar/templatetags/currency_filters.py
|
from decimal import Decimal as D
from decimal import InvalidOperation
from babel.numbers import format_currency
from django import template
from django.conf import settings
from django.utils.translation import get_language, to_locale
register = template.Library()
@register.filter(name='currency')
def currency(value, currency=None):
"""
Format decimal value as currency
"""
try:
value = D(value)
except (TypeError, InvalidOperation):
return u""
# Using Babel's currency formatting
# http://babel.pocoo.org/en/latest/api/numbers.html#babel.numbers.format_currency
kwargs = {
'currency': currency if currency else settings.OSCAR_DEFAULT_CURRENCY,
'format': getattr(settings, 'OSCAR_CURRENCY_FORMAT', None),
'locale': to_locale(get_language() or settings.LANGUAGE_CODE),
}
return format_currency(value, **kwargs)
|
from decimal import Decimal as D
from decimal import InvalidOperation
from babel.numbers import format_currency
from django import template
from django.conf import settings
from django.utils.translation import get_language, to_locale
register = template.Library()
@register.filter(name='currency')
def currency(value, currency=None):
"""
Format decimal value as currency
"""
try:
value = D(value)
except (TypeError, InvalidOperation):
return u""
# Using Babel's currency formatting
# http://babel.pocoo.org/en/latest/api/numbers.html#babel.numbers.format_currency
kwargs = {
'currency': currency if currency else settings.OSCAR_DEFAULT_CURRENCY,
'format': getattr(settings, 'OSCAR_CURRENCY_FORMAT', None),
'locale': to_locale(get_language() or settings.LANGUAGE_CODE),
'currency_digits': getattr(settings, 'OSCAR_CURRENCY_DIGITS', 2),
}
return format_currency(value, **kwargs) + getattr(settings, 'OSCAR_CURRENCY_SUFFIX', '')
|
Support currency digits and currency suffix.
|
Support currency digits and currency suffix.
|
Python
|
bsd-3-clause
|
michaelkuty/django-oscar,michaelkuty/django-oscar,michaelkuty/django-oscar,michaelkuty/django-oscar
|
from decimal import Decimal as D
from decimal import InvalidOperation
from babel.numbers import format_currency
from django import template
from django.conf import settings
from django.utils.translation import get_language, to_locale
register = template.Library()
@register.filter(name='currency')
def currency(value, currency=None):
"""
Format decimal value as currency
"""
try:
value = D(value)
except (TypeError, InvalidOperation):
return u""
# Using Babel's currency formatting
# http://babel.pocoo.org/en/latest/api/numbers.html#babel.numbers.format_currency
kwargs = {
'currency': currency if currency else settings.OSCAR_DEFAULT_CURRENCY,
'format': getattr(settings, 'OSCAR_CURRENCY_FORMAT', None),
'locale': to_locale(get_language() or settings.LANGUAGE_CODE),
}
return format_currency(value, **kwargs)
Support currency digits and currency suffix.
|
from decimal import Decimal as D
from decimal import InvalidOperation
from babel.numbers import format_currency
from django import template
from django.conf import settings
from django.utils.translation import get_language, to_locale
register = template.Library()
@register.filter(name='currency')
def currency(value, currency=None):
"""
Format decimal value as currency
"""
try:
value = D(value)
except (TypeError, InvalidOperation):
return u""
# Using Babel's currency formatting
# http://babel.pocoo.org/en/latest/api/numbers.html#babel.numbers.format_currency
kwargs = {
'currency': currency if currency else settings.OSCAR_DEFAULT_CURRENCY,
'format': getattr(settings, 'OSCAR_CURRENCY_FORMAT', None),
'locale': to_locale(get_language() or settings.LANGUAGE_CODE),
'currency_digits': getattr(settings, 'OSCAR_CURRENCY_DIGITS', 2),
}
return format_currency(value, **kwargs) + getattr(settings, 'OSCAR_CURRENCY_SUFFIX', '')
|
<commit_before>from decimal import Decimal as D
from decimal import InvalidOperation
from babel.numbers import format_currency
from django import template
from django.conf import settings
from django.utils.translation import get_language, to_locale
register = template.Library()
@register.filter(name='currency')
def currency(value, currency=None):
"""
Format decimal value as currency
"""
try:
value = D(value)
except (TypeError, InvalidOperation):
return u""
# Using Babel's currency formatting
# http://babel.pocoo.org/en/latest/api/numbers.html#babel.numbers.format_currency
kwargs = {
'currency': currency if currency else settings.OSCAR_DEFAULT_CURRENCY,
'format': getattr(settings, 'OSCAR_CURRENCY_FORMAT', None),
'locale': to_locale(get_language() or settings.LANGUAGE_CODE),
}
return format_currency(value, **kwargs)
<commit_msg>Support currency digits and currency suffix.<commit_after>
|
from decimal import Decimal as D
from decimal import InvalidOperation
from babel.numbers import format_currency
from django import template
from django.conf import settings
from django.utils.translation import get_language, to_locale
register = template.Library()
@register.filter(name='currency')
def currency(value, currency=None):
"""
Format decimal value as currency
"""
try:
value = D(value)
except (TypeError, InvalidOperation):
return u""
# Using Babel's currency formatting
# http://babel.pocoo.org/en/latest/api/numbers.html#babel.numbers.format_currency
kwargs = {
'currency': currency if currency else settings.OSCAR_DEFAULT_CURRENCY,
'format': getattr(settings, 'OSCAR_CURRENCY_FORMAT', None),
'locale': to_locale(get_language() or settings.LANGUAGE_CODE),
'currency_digits': getattr(settings, 'OSCAR_CURRENCY_DIGITS', 2),
}
return format_currency(value, **kwargs) + getattr(settings, 'OSCAR_CURRENCY_SUFFIX', '')
|
from decimal import Decimal as D
from decimal import InvalidOperation
from babel.numbers import format_currency
from django import template
from django.conf import settings
from django.utils.translation import get_language, to_locale
register = template.Library()
@register.filter(name='currency')
def currency(value, currency=None):
"""
Format decimal value as currency
"""
try:
value = D(value)
except (TypeError, InvalidOperation):
return u""
# Using Babel's currency formatting
# http://babel.pocoo.org/en/latest/api/numbers.html#babel.numbers.format_currency
kwargs = {
'currency': currency if currency else settings.OSCAR_DEFAULT_CURRENCY,
'format': getattr(settings, 'OSCAR_CURRENCY_FORMAT', None),
'locale': to_locale(get_language() or settings.LANGUAGE_CODE),
}
return format_currency(value, **kwargs)
Support currency digits and currency suffix.from decimal import Decimal as D
from decimal import InvalidOperation
from babel.numbers import format_currency
from django import template
from django.conf import settings
from django.utils.translation import get_language, to_locale
register = template.Library()
@register.filter(name='currency')
def currency(value, currency=None):
"""
Format decimal value as currency
"""
try:
value = D(value)
except (TypeError, InvalidOperation):
return u""
# Using Babel's currency formatting
# http://babel.pocoo.org/en/latest/api/numbers.html#babel.numbers.format_currency
kwargs = {
'currency': currency if currency else settings.OSCAR_DEFAULT_CURRENCY,
'format': getattr(settings, 'OSCAR_CURRENCY_FORMAT', None),
'locale': to_locale(get_language() or settings.LANGUAGE_CODE),
'currency_digits': getattr(settings, 'OSCAR_CURRENCY_DIGITS', 2),
}
return format_currency(value, **kwargs) + getattr(settings, 'OSCAR_CURRENCY_SUFFIX', '')
|
<commit_before>from decimal import Decimal as D
from decimal import InvalidOperation
from babel.numbers import format_currency
from django import template
from django.conf import settings
from django.utils.translation import get_language, to_locale
register = template.Library()
@register.filter(name='currency')
def currency(value, currency=None):
"""
Format decimal value as currency
"""
try:
value = D(value)
except (TypeError, InvalidOperation):
return u""
# Using Babel's currency formatting
# http://babel.pocoo.org/en/latest/api/numbers.html#babel.numbers.format_currency
kwargs = {
'currency': currency if currency else settings.OSCAR_DEFAULT_CURRENCY,
'format': getattr(settings, 'OSCAR_CURRENCY_FORMAT', None),
'locale': to_locale(get_language() or settings.LANGUAGE_CODE),
}
return format_currency(value, **kwargs)
<commit_msg>Support currency digits and currency suffix.<commit_after>from decimal import Decimal as D
from decimal import InvalidOperation
from babel.numbers import format_currency
from django import template
from django.conf import settings
from django.utils.translation import get_language, to_locale
register = template.Library()
@register.filter(name='currency')
def currency(value, currency=None):
"""
Format decimal value as currency
"""
try:
value = D(value)
except (TypeError, InvalidOperation):
return u""
# Using Babel's currency formatting
# http://babel.pocoo.org/en/latest/api/numbers.html#babel.numbers.format_currency
kwargs = {
'currency': currency if currency else settings.OSCAR_DEFAULT_CURRENCY,
'format': getattr(settings, 'OSCAR_CURRENCY_FORMAT', None),
'locale': to_locale(get_language() or settings.LANGUAGE_CODE),
'currency_digits': getattr(settings, 'OSCAR_CURRENCY_DIGITS', 2),
}
return format_currency(value, **kwargs) + getattr(settings, 'OSCAR_CURRENCY_SUFFIX', '')
|
6dbefe8a62ae375b487c7e21340aba5b81eaeb7f
|
django_git/management/commands/pull_oldest.py
|
django_git/management/commands/pull_oldest.py
|
import os
import traceback
from django.utils import timezone
from django_git.management.commands.git_pull_utils.git_folder_enum import enum_git_repo
from django_git.management.commands.git_pull_utils.git_synchronizer import GitSynchronizer
from djangoautoconf.cmd_handler_base.msg_process_cmd_base import DjangoCmdBase
from iconizer.gui_client.notification_service_client import NotificationServiceClient
class GitPullOnce(DjangoCmdBase):
git_tag_name = "git"
def msg_loop(self):
for repo in enum_git_repo():
if os.path.exists(repo.full_path):
p = GitSynchronizer(repo.full_path, NotificationServiceClient().notify)
success = False
try:
p.pull_all_branches()
print "pull and push done"
success = True
except:
traceback.print_exc()
print "Pull error for: %s" % repo.full_path
repo.last_checked = timezone.now()
repo.is_last_pull_success = success
repo.save()
Command = GitPullOnce
|
import os
import traceback
from django.utils import timezone
from django_git.management.commands.git_pull_utils.git_folder_enum import enum_git_repo
from django_git.management.commands.git_pull_utils.git_synchronizer import GitSynchronizer
from djangoautoconf.cmd_handler_base.msg_process_cmd_base import DjangoCmdBase
from iconizer.gui_client.notification_service_client import NotificationServiceClient
class GitPullOnce(DjangoCmdBase):
git_tag_name = "git"
def msg_loop(self):
for repo in enum_git_repo():
if os.path.exists(repo.full_path):
p = GitSynchronizer(repo.full_path, NotificationServiceClient().notify)
success = False
try:
p.pull_all_branches()
print "pull and push done", p.sync_msg
success = True
except:
traceback.print_exc()
print "Pull error for: %s" % repo.full_path
repo.last_checked = timezone.now()
repo.is_last_pull_success = success
repo.save()
Command = GitPullOnce
|
Print message for pull success.
|
Print message for pull success.
|
Python
|
bsd-3-clause
|
weijia/django-git,weijia/django-git
|
import os
import traceback
from django.utils import timezone
from django_git.management.commands.git_pull_utils.git_folder_enum import enum_git_repo
from django_git.management.commands.git_pull_utils.git_synchronizer import GitSynchronizer
from djangoautoconf.cmd_handler_base.msg_process_cmd_base import DjangoCmdBase
from iconizer.gui_client.notification_service_client import NotificationServiceClient
class GitPullOnce(DjangoCmdBase):
git_tag_name = "git"
def msg_loop(self):
for repo in enum_git_repo():
if os.path.exists(repo.full_path):
p = GitSynchronizer(repo.full_path, NotificationServiceClient().notify)
success = False
try:
p.pull_all_branches()
print "pull and push done"
success = True
except:
traceback.print_exc()
print "Pull error for: %s" % repo.full_path
repo.last_checked = timezone.now()
repo.is_last_pull_success = success
repo.save()
Command = GitPullOnce
Print message for pull success.
|
import os
import traceback
from django.utils import timezone
from django_git.management.commands.git_pull_utils.git_folder_enum import enum_git_repo
from django_git.management.commands.git_pull_utils.git_synchronizer import GitSynchronizer
from djangoautoconf.cmd_handler_base.msg_process_cmd_base import DjangoCmdBase
from iconizer.gui_client.notification_service_client import NotificationServiceClient
class GitPullOnce(DjangoCmdBase):
git_tag_name = "git"
def msg_loop(self):
for repo in enum_git_repo():
if os.path.exists(repo.full_path):
p = GitSynchronizer(repo.full_path, NotificationServiceClient().notify)
success = False
try:
p.pull_all_branches()
print "pull and push done", p.sync_msg
success = True
except:
traceback.print_exc()
print "Pull error for: %s" % repo.full_path
repo.last_checked = timezone.now()
repo.is_last_pull_success = success
repo.save()
Command = GitPullOnce
|
<commit_before>import os
import traceback
from django.utils import timezone
from django_git.management.commands.git_pull_utils.git_folder_enum import enum_git_repo
from django_git.management.commands.git_pull_utils.git_synchronizer import GitSynchronizer
from djangoautoconf.cmd_handler_base.msg_process_cmd_base import DjangoCmdBase
from iconizer.gui_client.notification_service_client import NotificationServiceClient
class GitPullOnce(DjangoCmdBase):
git_tag_name = "git"
def msg_loop(self):
for repo in enum_git_repo():
if os.path.exists(repo.full_path):
p = GitSynchronizer(repo.full_path, NotificationServiceClient().notify)
success = False
try:
p.pull_all_branches()
print "pull and push done"
success = True
except:
traceback.print_exc()
print "Pull error for: %s" % repo.full_path
repo.last_checked = timezone.now()
repo.is_last_pull_success = success
repo.save()
Command = GitPullOnce
<commit_msg>Print message for pull success.<commit_after>
|
import os
import traceback
from django.utils import timezone
from django_git.management.commands.git_pull_utils.git_folder_enum import enum_git_repo
from django_git.management.commands.git_pull_utils.git_synchronizer import GitSynchronizer
from djangoautoconf.cmd_handler_base.msg_process_cmd_base import DjangoCmdBase
from iconizer.gui_client.notification_service_client import NotificationServiceClient
class GitPullOnce(DjangoCmdBase):
git_tag_name = "git"
def msg_loop(self):
for repo in enum_git_repo():
if os.path.exists(repo.full_path):
p = GitSynchronizer(repo.full_path, NotificationServiceClient().notify)
success = False
try:
p.pull_all_branches()
print "pull and push done", p.sync_msg
success = True
except:
traceback.print_exc()
print "Pull error for: %s" % repo.full_path
repo.last_checked = timezone.now()
repo.is_last_pull_success = success
repo.save()
Command = GitPullOnce
|
import os
import traceback
from django.utils import timezone
from django_git.management.commands.git_pull_utils.git_folder_enum import enum_git_repo
from django_git.management.commands.git_pull_utils.git_synchronizer import GitSynchronizer
from djangoautoconf.cmd_handler_base.msg_process_cmd_base import DjangoCmdBase
from iconizer.gui_client.notification_service_client import NotificationServiceClient
class GitPullOnce(DjangoCmdBase):
git_tag_name = "git"
def msg_loop(self):
for repo in enum_git_repo():
if os.path.exists(repo.full_path):
p = GitSynchronizer(repo.full_path, NotificationServiceClient().notify)
success = False
try:
p.pull_all_branches()
print "pull and push done"
success = True
except:
traceback.print_exc()
print "Pull error for: %s" % repo.full_path
repo.last_checked = timezone.now()
repo.is_last_pull_success = success
repo.save()
Command = GitPullOnce
Print message for pull success.import os
import traceback
from django.utils import timezone
from django_git.management.commands.git_pull_utils.git_folder_enum import enum_git_repo
from django_git.management.commands.git_pull_utils.git_synchronizer import GitSynchronizer
from djangoautoconf.cmd_handler_base.msg_process_cmd_base import DjangoCmdBase
from iconizer.gui_client.notification_service_client import NotificationServiceClient
class GitPullOnce(DjangoCmdBase):
git_tag_name = "git"
def msg_loop(self):
for repo in enum_git_repo():
if os.path.exists(repo.full_path):
p = GitSynchronizer(repo.full_path, NotificationServiceClient().notify)
success = False
try:
p.pull_all_branches()
print "pull and push done", p.sync_msg
success = True
except:
traceback.print_exc()
print "Pull error for: %s" % repo.full_path
repo.last_checked = timezone.now()
repo.is_last_pull_success = success
repo.save()
Command = GitPullOnce
|
<commit_before>import os
import traceback
from django.utils import timezone
from django_git.management.commands.git_pull_utils.git_folder_enum import enum_git_repo
from django_git.management.commands.git_pull_utils.git_synchronizer import GitSynchronizer
from djangoautoconf.cmd_handler_base.msg_process_cmd_base import DjangoCmdBase
from iconizer.gui_client.notification_service_client import NotificationServiceClient
class GitPullOnce(DjangoCmdBase):
git_tag_name = "git"
def msg_loop(self):
for repo in enum_git_repo():
if os.path.exists(repo.full_path):
p = GitSynchronizer(repo.full_path, NotificationServiceClient().notify)
success = False
try:
p.pull_all_branches()
print "pull and push done"
success = True
except:
traceback.print_exc()
print "Pull error for: %s" % repo.full_path
repo.last_checked = timezone.now()
repo.is_last_pull_success = success
repo.save()
Command = GitPullOnce
<commit_msg>Print message for pull success.<commit_after>import os
import traceback
from django.utils import timezone
from django_git.management.commands.git_pull_utils.git_folder_enum import enum_git_repo
from django_git.management.commands.git_pull_utils.git_synchronizer import GitSynchronizer
from djangoautoconf.cmd_handler_base.msg_process_cmd_base import DjangoCmdBase
from iconizer.gui_client.notification_service_client import NotificationServiceClient
class GitPullOnce(DjangoCmdBase):
git_tag_name = "git"
def msg_loop(self):
for repo in enum_git_repo():
if os.path.exists(repo.full_path):
p = GitSynchronizer(repo.full_path, NotificationServiceClient().notify)
success = False
try:
p.pull_all_branches()
print "pull and push done", p.sync_msg
success = True
except:
traceback.print_exc()
print "Pull error for: %s" % repo.full_path
repo.last_checked = timezone.now()
repo.is_last_pull_success = success
repo.save()
Command = GitPullOnce
|
fcf52a1d427d2e89031480f747374860f64c45ff
|
constant_listener/pyspeechTest.py
|
constant_listener/pyspeechTest.py
|
from pyspeech import best_speech_result
import unittest
from pyaudio import PyAudio
import Queue
class PyspeechTest(unittest.TestCase):
def setUp(self):
self.p = PyAudio()
def test_google_stt(self):
good_morning = open('example_wavs/good_morning.wav', 'rb')
output = best_speech_result(self.p, good_morning.read(), {}, "google")
self.assertEqual(output, "good morning")
hello_world = open('example_wavs/hello_world.wav', 'rb')
output = best_speech_result(self.p, hello_world.read(), {}, "google")
self.assertEqual(output, "hello world")
if __name__ == "__main__":
unittest.main()
|
from pyspeech import best_speech_result
import unittest
from pyaudio import PyAudio
import Queue
class PyspeechTest(unittest.TestCase):
def setUp(self):
self.p = PyAudio()
def test_google_stt(self):
good_morning = open('example_wavs/good_morning.wav', 'rb')
output = best_speech_result(self.p, good_morning.read(), {}, "google")
self.assertEqual(output, "good morning")
hello_world = open('example_wavs/hello_world.wav', 'rb')
output = best_speech_result(self.p, hello_world.read(), {}, "google")
self.assertEqual(output, "hello world")
# This will fail without a valid wit_token in profile.yml
def test_wit_stt(self):
import yaml
profile = yaml.load(open("profile.yml").read())
good_morning = open('example_wavs/good_morning.wav', 'rb')
output = best_speech_result(self.p, good_morning.read(), profile, "wit")
self.assertEqual(output, "good morning")
hello_world = open('example_wavs/hello_world.wav', 'rb')
output = best_speech_result(self.p, hello_world.read(), profile, "wit")
self.assertEqual(output, "hello world")
if __name__ == "__main__":
unittest.main()
|
Add tests for Wit STT
|
Add tests for Wit STT
|
Python
|
mit
|
MattWis/constant_listener
|
from pyspeech import best_speech_result
import unittest
from pyaudio import PyAudio
import Queue
class PyspeechTest(unittest.TestCase):
def setUp(self):
self.p = PyAudio()
def test_google_stt(self):
good_morning = open('example_wavs/good_morning.wav', 'rb')
output = best_speech_result(self.p, good_morning.read(), {}, "google")
self.assertEqual(output, "good morning")
hello_world = open('example_wavs/hello_world.wav', 'rb')
output = best_speech_result(self.p, hello_world.read(), {}, "google")
self.assertEqual(output, "hello world")
if __name__ == "__main__":
unittest.main()
Add tests for Wit STT
|
from pyspeech import best_speech_result
import unittest
from pyaudio import PyAudio
import Queue
class PyspeechTest(unittest.TestCase):
def setUp(self):
self.p = PyAudio()
def test_google_stt(self):
good_morning = open('example_wavs/good_morning.wav', 'rb')
output = best_speech_result(self.p, good_morning.read(), {}, "google")
self.assertEqual(output, "good morning")
hello_world = open('example_wavs/hello_world.wav', 'rb')
output = best_speech_result(self.p, hello_world.read(), {}, "google")
self.assertEqual(output, "hello world")
# This will fail without a valid wit_token in profile.yml
def test_wit_stt(self):
import yaml
profile = yaml.load(open("profile.yml").read())
good_morning = open('example_wavs/good_morning.wav', 'rb')
output = best_speech_result(self.p, good_morning.read(), profile, "wit")
self.assertEqual(output, "good morning")
hello_world = open('example_wavs/hello_world.wav', 'rb')
output = best_speech_result(self.p, hello_world.read(), profile, "wit")
self.assertEqual(output, "hello world")
if __name__ == "__main__":
unittest.main()
|
<commit_before>from pyspeech import best_speech_result
import unittest
from pyaudio import PyAudio
import Queue
class PyspeechTest(unittest.TestCase):
def setUp(self):
self.p = PyAudio()
def test_google_stt(self):
good_morning = open('example_wavs/good_morning.wav', 'rb')
output = best_speech_result(self.p, good_morning.read(), {}, "google")
self.assertEqual(output, "good morning")
hello_world = open('example_wavs/hello_world.wav', 'rb')
output = best_speech_result(self.p, hello_world.read(), {}, "google")
self.assertEqual(output, "hello world")
if __name__ == "__main__":
unittest.main()
<commit_msg>Add tests for Wit STT<commit_after>
|
from pyspeech import best_speech_result
import unittest
from pyaudio import PyAudio
import Queue
class PyspeechTest(unittest.TestCase):
def setUp(self):
self.p = PyAudio()
def test_google_stt(self):
good_morning = open('example_wavs/good_morning.wav', 'rb')
output = best_speech_result(self.p, good_morning.read(), {}, "google")
self.assertEqual(output, "good morning")
hello_world = open('example_wavs/hello_world.wav', 'rb')
output = best_speech_result(self.p, hello_world.read(), {}, "google")
self.assertEqual(output, "hello world")
# This will fail without a valid wit_token in profile.yml
def test_wit_stt(self):
import yaml
profile = yaml.load(open("profile.yml").read())
good_morning = open('example_wavs/good_morning.wav', 'rb')
output = best_speech_result(self.p, good_morning.read(), profile, "wit")
self.assertEqual(output, "good morning")
hello_world = open('example_wavs/hello_world.wav', 'rb')
output = best_speech_result(self.p, hello_world.read(), profile, "wit")
self.assertEqual(output, "hello world")
if __name__ == "__main__":
unittest.main()
|
from pyspeech import best_speech_result
import unittest
from pyaudio import PyAudio
import Queue
class PyspeechTest(unittest.TestCase):
def setUp(self):
self.p = PyAudio()
def test_google_stt(self):
good_morning = open('example_wavs/good_morning.wav', 'rb')
output = best_speech_result(self.p, good_morning.read(), {}, "google")
self.assertEqual(output, "good morning")
hello_world = open('example_wavs/hello_world.wav', 'rb')
output = best_speech_result(self.p, hello_world.read(), {}, "google")
self.assertEqual(output, "hello world")
if __name__ == "__main__":
unittest.main()
Add tests for Wit STTfrom pyspeech import best_speech_result
import unittest
from pyaudio import PyAudio
import Queue
class PyspeechTest(unittest.TestCase):
def setUp(self):
self.p = PyAudio()
def test_google_stt(self):
good_morning = open('example_wavs/good_morning.wav', 'rb')
output = best_speech_result(self.p, good_morning.read(), {}, "google")
self.assertEqual(output, "good morning")
hello_world = open('example_wavs/hello_world.wav', 'rb')
output = best_speech_result(self.p, hello_world.read(), {}, "google")
self.assertEqual(output, "hello world")
# This will fail without a valid wit_token in profile.yml
def test_wit_stt(self):
import yaml
profile = yaml.load(open("profile.yml").read())
good_morning = open('example_wavs/good_morning.wav', 'rb')
output = best_speech_result(self.p, good_morning.read(), profile, "wit")
self.assertEqual(output, "good morning")
hello_world = open('example_wavs/hello_world.wav', 'rb')
output = best_speech_result(self.p, hello_world.read(), profile, "wit")
self.assertEqual(output, "hello world")
if __name__ == "__main__":
unittest.main()
|
<commit_before>from pyspeech import best_speech_result
import unittest
from pyaudio import PyAudio
import Queue
class PyspeechTest(unittest.TestCase):
def setUp(self):
self.p = PyAudio()
def test_google_stt(self):
good_morning = open('example_wavs/good_morning.wav', 'rb')
output = best_speech_result(self.p, good_morning.read(), {}, "google")
self.assertEqual(output, "good morning")
hello_world = open('example_wavs/hello_world.wav', 'rb')
output = best_speech_result(self.p, hello_world.read(), {}, "google")
self.assertEqual(output, "hello world")
if __name__ == "__main__":
unittest.main()
<commit_msg>Add tests for Wit STT<commit_after>from pyspeech import best_speech_result
import unittest
from pyaudio import PyAudio
import Queue
class PyspeechTest(unittest.TestCase):
def setUp(self):
self.p = PyAudio()
def test_google_stt(self):
good_morning = open('example_wavs/good_morning.wav', 'rb')
output = best_speech_result(self.p, good_morning.read(), {}, "google")
self.assertEqual(output, "good morning")
hello_world = open('example_wavs/hello_world.wav', 'rb')
output = best_speech_result(self.p, hello_world.read(), {}, "google")
self.assertEqual(output, "hello world")
# This will fail without a valid wit_token in profile.yml
def test_wit_stt(self):
import yaml
profile = yaml.load(open("profile.yml").read())
good_morning = open('example_wavs/good_morning.wav', 'rb')
output = best_speech_result(self.p, good_morning.read(), profile, "wit")
self.assertEqual(output, "good morning")
hello_world = open('example_wavs/hello_world.wav', 'rb')
output = best_speech_result(self.p, hello_world.read(), profile, "wit")
self.assertEqual(output, "hello world")
if __name__ == "__main__":
unittest.main()
|
5a1edb15cac470f392ccb4447b81cc99e8af2a68
|
robinette/server.py
|
robinette/server.py
|
#!/usr/bin/env python
from irc import irc
from xmlrpc.server import AsyncXMLRPCServer
if __name__ == '__main__':
server = AsyncXMLRPCServer(('localhost', 8000), allow_none=True)
server.add_handler(irc)
try:
server.serve_forever()
except KeyboardInterrupt:
print 'Exiting'
|
#!/usr/bin/env python
from irc import irc
from xmlrpc.server import AsyncXMLRPCServer
if __name__ == '__main__':
server = AsyncXMLRPCServer(('localhost', 8000), allow_none=True)
server.add_handler(irc)
print 'Running on %s:%s' % map(str, server.server_address)
try:
server.serve_forever()
except KeyboardInterrupt:
print 'Exiting'
|
Print where we're running at
|
Print where we're running at
|
Python
|
mit
|
mgracik/robinette
|
#!/usr/bin/env python
from irc import irc
from xmlrpc.server import AsyncXMLRPCServer
if __name__ == '__main__':
server = AsyncXMLRPCServer(('localhost', 8000), allow_none=True)
server.add_handler(irc)
try:
server.serve_forever()
except KeyboardInterrupt:
print 'Exiting'
Print where we're running at
|
#!/usr/bin/env python
from irc import irc
from xmlrpc.server import AsyncXMLRPCServer
if __name__ == '__main__':
server = AsyncXMLRPCServer(('localhost', 8000), allow_none=True)
server.add_handler(irc)
print 'Running on %s:%s' % map(str, server.server_address)
try:
server.serve_forever()
except KeyboardInterrupt:
print 'Exiting'
|
<commit_before>#!/usr/bin/env python
from irc import irc
from xmlrpc.server import AsyncXMLRPCServer
if __name__ == '__main__':
server = AsyncXMLRPCServer(('localhost', 8000), allow_none=True)
server.add_handler(irc)
try:
server.serve_forever()
except KeyboardInterrupt:
print 'Exiting'
<commit_msg>Print where we're running at<commit_after>
|
#!/usr/bin/env python
from irc import irc
from xmlrpc.server import AsyncXMLRPCServer
if __name__ == '__main__':
server = AsyncXMLRPCServer(('localhost', 8000), allow_none=True)
server.add_handler(irc)
print 'Running on %s:%s' % map(str, server.server_address)
try:
server.serve_forever()
except KeyboardInterrupt:
print 'Exiting'
|
#!/usr/bin/env python
from irc import irc
from xmlrpc.server import AsyncXMLRPCServer
if __name__ == '__main__':
server = AsyncXMLRPCServer(('localhost', 8000), allow_none=True)
server.add_handler(irc)
try:
server.serve_forever()
except KeyboardInterrupt:
print 'Exiting'
Print where we're running at#!/usr/bin/env python
from irc import irc
from xmlrpc.server import AsyncXMLRPCServer
if __name__ == '__main__':
server = AsyncXMLRPCServer(('localhost', 8000), allow_none=True)
server.add_handler(irc)
print 'Running on %s:%s' % map(str, server.server_address)
try:
server.serve_forever()
except KeyboardInterrupt:
print 'Exiting'
|
<commit_before>#!/usr/bin/env python
from irc import irc
from xmlrpc.server import AsyncXMLRPCServer
if __name__ == '__main__':
server = AsyncXMLRPCServer(('localhost', 8000), allow_none=True)
server.add_handler(irc)
try:
server.serve_forever()
except KeyboardInterrupt:
print 'Exiting'
<commit_msg>Print where we're running at<commit_after>#!/usr/bin/env python
from irc import irc
from xmlrpc.server import AsyncXMLRPCServer
if __name__ == '__main__':
server = AsyncXMLRPCServer(('localhost', 8000), allow_none=True)
server.add_handler(irc)
print 'Running on %s:%s' % map(str, server.server_address)
try:
server.serve_forever()
except KeyboardInterrupt:
print 'Exiting'
|
bd78472c14ce9ed487a563a958082b356e0b7c79
|
src/epiweb/apps/reminder/admin.py
|
src/epiweb/apps/reminder/admin.py
|
from django.contrib import admin
from epiweb.apps.reminder.models import Reminder
class ReminderAdmin(admin.ModelAdmin):
list_display = ('user', 'wday', 'active',
'last_reminder', 'next_reminder')
admin.site.register(Reminder, ReminderAdmin)
|
from django.contrib import admin
from epiweb.apps.reminder.models import Reminder
def make_active(modeladmin, request, queryset):
queryset.update(active=True)
make_active.short_description = 'Make selected reminders active'
def make_inactive(modeladmin, request, queryset):
queryset.update(active=False)
make_inactive.short_description = 'Make selected reminders inactive'
class ReminderAdmin(admin.ModelAdmin):
list_display = ('user', 'wday', 'active',
'last_reminder', 'next_reminder')
ordering = ('user__username',)
actions = (make_active, make_inactive,)
admin.site.register(Reminder, ReminderAdmin)
|
Add actions to make reminders active or inactive
|
Add actions to make reminders active or inactive
|
Python
|
agpl-3.0
|
ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website
|
from django.contrib import admin
from epiweb.apps.reminder.models import Reminder
class ReminderAdmin(admin.ModelAdmin):
list_display = ('user', 'wday', 'active',
'last_reminder', 'next_reminder')
admin.site.register(Reminder, ReminderAdmin)
Add actions to make reminders active or inactive
|
from django.contrib import admin
from epiweb.apps.reminder.models import Reminder
def make_active(modeladmin, request, queryset):
queryset.update(active=True)
make_active.short_description = 'Make selected reminders active'
def make_inactive(modeladmin, request, queryset):
queryset.update(active=False)
make_inactive.short_description = 'Make selected reminders inactive'
class ReminderAdmin(admin.ModelAdmin):
list_display = ('user', 'wday', 'active',
'last_reminder', 'next_reminder')
ordering = ('user__username',)
actions = (make_active, make_inactive,)
admin.site.register(Reminder, ReminderAdmin)
|
<commit_before>from django.contrib import admin
from epiweb.apps.reminder.models import Reminder
class ReminderAdmin(admin.ModelAdmin):
list_display = ('user', 'wday', 'active',
'last_reminder', 'next_reminder')
admin.site.register(Reminder, ReminderAdmin)
<commit_msg>Add actions to make reminders active or inactive<commit_after>
|
from django.contrib import admin
from epiweb.apps.reminder.models import Reminder
def make_active(modeladmin, request, queryset):
queryset.update(active=True)
make_active.short_description = 'Make selected reminders active'
def make_inactive(modeladmin, request, queryset):
queryset.update(active=False)
make_inactive.short_description = 'Make selected reminders inactive'
class ReminderAdmin(admin.ModelAdmin):
list_display = ('user', 'wday', 'active',
'last_reminder', 'next_reminder')
ordering = ('user__username',)
actions = (make_active, make_inactive,)
admin.site.register(Reminder, ReminderAdmin)
|
from django.contrib import admin
from epiweb.apps.reminder.models import Reminder
class ReminderAdmin(admin.ModelAdmin):
list_display = ('user', 'wday', 'active',
'last_reminder', 'next_reminder')
admin.site.register(Reminder, ReminderAdmin)
Add actions to make reminders active or inactivefrom django.contrib import admin
from epiweb.apps.reminder.models import Reminder
def make_active(modeladmin, request, queryset):
queryset.update(active=True)
make_active.short_description = 'Make selected reminders active'
def make_inactive(modeladmin, request, queryset):
queryset.update(active=False)
make_inactive.short_description = 'Make selected reminders inactive'
class ReminderAdmin(admin.ModelAdmin):
list_display = ('user', 'wday', 'active',
'last_reminder', 'next_reminder')
ordering = ('user__username',)
actions = (make_active, make_inactive,)
admin.site.register(Reminder, ReminderAdmin)
|
<commit_before>from django.contrib import admin
from epiweb.apps.reminder.models import Reminder
class ReminderAdmin(admin.ModelAdmin):
list_display = ('user', 'wday', 'active',
'last_reminder', 'next_reminder')
admin.site.register(Reminder, ReminderAdmin)
<commit_msg>Add actions to make reminders active or inactive<commit_after>from django.contrib import admin
from epiweb.apps.reminder.models import Reminder
def make_active(modeladmin, request, queryset):
queryset.update(active=True)
make_active.short_description = 'Make selected reminders active'
def make_inactive(modeladmin, request, queryset):
queryset.update(active=False)
make_inactive.short_description = 'Make selected reminders inactive'
class ReminderAdmin(admin.ModelAdmin):
list_display = ('user', 'wday', 'active',
'last_reminder', 'next_reminder')
ordering = ('user__username',)
actions = (make_active, make_inactive,)
admin.site.register(Reminder, ReminderAdmin)
|
65428583f066c887d99f885a4fc516f6a5f83f17
|
src/livestreamer/plugins/rtlxl.py
|
src/livestreamer/plugins/rtlxl.py
|
import re
from livestreamer.plugin import Plugin
from livestreamer.plugin.api import http, validate
from livestreamer.stream import HDSStream, HLSStream, RTMPStream
_url_re = re.compile("""http(?:s)?://(?:\w+\.)?rtlxl.nl/#!/(?:.*)/(?P<uuid>.*?)\Z""", re.IGNORECASE)
class rtlxl(Plugin):
@classmethod
def can_handle_url(cls, url):
return _url_re.match(url)
def _get_streams(self):
match = _url_re.match(self.url)
uuid = match.group("uuid")
html = http.get('http://www.rtl.nl/system/s4m/vfd/version=2/uuid={}/d=pc/fmt=adaptive/'.format(uuid)).text
playlist_url = "http://manifest.us.rtl.nl" + re.compile('videopath":"(?P<playlist_url>.*?)",', re.IGNORECASE).search(html).group("playlist_url")
print playlist_url
return HLSStream.parse_variant_playlist(self.session, playlist_url)
__plugin__ = rtlxl
|
import re
from livestreamer.plugin import Plugin
from livestreamer.plugin.api import http, validate
from livestreamer.stream import HDSStream, HLSStream, RTMPStream
_url_re = re.compile("""http(?:s)?://(?:\w+\.)?rtlxl.nl/#!/(?:.*)/(?P<uuid>.*?)\Z""", re.IGNORECASE)
class rtlxl(Plugin):
@classmethod
def can_handle_url(cls, url):
return _url_re.match(url)
def _get_streams(self):
match = _url_re.match(self.url)
uuid = match.group("uuid")
html = http.get('http://www.rtl.nl/system/s4m/vfd/version=2/uuid={}/d=pc/fmt=adaptive/'.format(uuid)).text
playlist_url = "http://manifest.us.rtl.nl" + re.compile('videopath":"(?P<playlist_url>.*?)",', re.IGNORECASE).search(html).group("playlist_url")
return HLSStream.parse_variant_playlist(self.session, playlist_url)
__plugin__ = rtlxl
|
Remove spurious print statement that made the plugin incompatible with python 3.
|
Remove spurious print statement that made the plugin incompatible with python 3.
|
Python
|
bsd-2-clause
|
sbstp/streamlink,mmetak/streamlink,wlerin/streamlink,sbstp/streamlink,bastimeyer/streamlink,chhe/streamlink,ethanhlc/streamlink,gravyboat/streamlink,back-to/streamlink,mmetak/streamlink,streamlink/streamlink,fishscene/streamlink,back-to/streamlink,melmorabity/streamlink,gravyboat/streamlink,fishscene/streamlink,chhe/streamlink,javiercantero/streamlink,ethanhlc/streamlink,javiercantero/streamlink,bastimeyer/streamlink,beardypig/streamlink,melmorabity/streamlink,beardypig/streamlink,wlerin/streamlink,streamlink/streamlink
|
import re
from livestreamer.plugin import Plugin
from livestreamer.plugin.api import http, validate
from livestreamer.stream import HDSStream, HLSStream, RTMPStream
_url_re = re.compile("""http(?:s)?://(?:\w+\.)?rtlxl.nl/#!/(?:.*)/(?P<uuid>.*?)\Z""", re.IGNORECASE)
class rtlxl(Plugin):
@classmethod
def can_handle_url(cls, url):
return _url_re.match(url)
def _get_streams(self):
match = _url_re.match(self.url)
uuid = match.group("uuid")
html = http.get('http://www.rtl.nl/system/s4m/vfd/version=2/uuid={}/d=pc/fmt=adaptive/'.format(uuid)).text
playlist_url = "http://manifest.us.rtl.nl" + re.compile('videopath":"(?P<playlist_url>.*?)",', re.IGNORECASE).search(html).group("playlist_url")
print playlist_url
return HLSStream.parse_variant_playlist(self.session, playlist_url)
__plugin__ = rtlxl
Remove spurious print statement that made the plugin incompatible with python 3.
|
import re
from livestreamer.plugin import Plugin
from livestreamer.plugin.api import http, validate
from livestreamer.stream import HDSStream, HLSStream, RTMPStream
_url_re = re.compile("""http(?:s)?://(?:\w+\.)?rtlxl.nl/#!/(?:.*)/(?P<uuid>.*?)\Z""", re.IGNORECASE)
class rtlxl(Plugin):
@classmethod
def can_handle_url(cls, url):
return _url_re.match(url)
def _get_streams(self):
match = _url_re.match(self.url)
uuid = match.group("uuid")
html = http.get('http://www.rtl.nl/system/s4m/vfd/version=2/uuid={}/d=pc/fmt=adaptive/'.format(uuid)).text
playlist_url = "http://manifest.us.rtl.nl" + re.compile('videopath":"(?P<playlist_url>.*?)",', re.IGNORECASE).search(html).group("playlist_url")
return HLSStream.parse_variant_playlist(self.session, playlist_url)
__plugin__ = rtlxl
|
<commit_before>import re
from livestreamer.plugin import Plugin
from livestreamer.plugin.api import http, validate
from livestreamer.stream import HDSStream, HLSStream, RTMPStream
_url_re = re.compile("""http(?:s)?://(?:\w+\.)?rtlxl.nl/#!/(?:.*)/(?P<uuid>.*?)\Z""", re.IGNORECASE)
class rtlxl(Plugin):
@classmethod
def can_handle_url(cls, url):
return _url_re.match(url)
def _get_streams(self):
match = _url_re.match(self.url)
uuid = match.group("uuid")
html = http.get('http://www.rtl.nl/system/s4m/vfd/version=2/uuid={}/d=pc/fmt=adaptive/'.format(uuid)).text
playlist_url = "http://manifest.us.rtl.nl" + re.compile('videopath":"(?P<playlist_url>.*?)",', re.IGNORECASE).search(html).group("playlist_url")
print playlist_url
return HLSStream.parse_variant_playlist(self.session, playlist_url)
__plugin__ = rtlxl
<commit_msg>Remove spurious print statement that made the plugin incompatible with python 3.<commit_after>
|
import re
from livestreamer.plugin import Plugin
from livestreamer.plugin.api import http, validate
from livestreamer.stream import HDSStream, HLSStream, RTMPStream
_url_re = re.compile("""http(?:s)?://(?:\w+\.)?rtlxl.nl/#!/(?:.*)/(?P<uuid>.*?)\Z""", re.IGNORECASE)
class rtlxl(Plugin):
@classmethod
def can_handle_url(cls, url):
return _url_re.match(url)
def _get_streams(self):
match = _url_re.match(self.url)
uuid = match.group("uuid")
html = http.get('http://www.rtl.nl/system/s4m/vfd/version=2/uuid={}/d=pc/fmt=adaptive/'.format(uuid)).text
playlist_url = "http://manifest.us.rtl.nl" + re.compile('videopath":"(?P<playlist_url>.*?)",', re.IGNORECASE).search(html).group("playlist_url")
return HLSStream.parse_variant_playlist(self.session, playlist_url)
__plugin__ = rtlxl
|
import re
from livestreamer.plugin import Plugin
from livestreamer.plugin.api import http, validate
from livestreamer.stream import HDSStream, HLSStream, RTMPStream
_url_re = re.compile("""http(?:s)?://(?:\w+\.)?rtlxl.nl/#!/(?:.*)/(?P<uuid>.*?)\Z""", re.IGNORECASE)
class rtlxl(Plugin):
@classmethod
def can_handle_url(cls, url):
return _url_re.match(url)
def _get_streams(self):
match = _url_re.match(self.url)
uuid = match.group("uuid")
html = http.get('http://www.rtl.nl/system/s4m/vfd/version=2/uuid={}/d=pc/fmt=adaptive/'.format(uuid)).text
playlist_url = "http://manifest.us.rtl.nl" + re.compile('videopath":"(?P<playlist_url>.*?)",', re.IGNORECASE).search(html).group("playlist_url")
print playlist_url
return HLSStream.parse_variant_playlist(self.session, playlist_url)
__plugin__ = rtlxl
Remove spurious print statement that made the plugin incompatible with python 3.import re
from livestreamer.plugin import Plugin
from livestreamer.plugin.api import http, validate
from livestreamer.stream import HDSStream, HLSStream, RTMPStream
_url_re = re.compile("""http(?:s)?://(?:\w+\.)?rtlxl.nl/#!/(?:.*)/(?P<uuid>.*?)\Z""", re.IGNORECASE)
class rtlxl(Plugin):
@classmethod
def can_handle_url(cls, url):
return _url_re.match(url)
def _get_streams(self):
match = _url_re.match(self.url)
uuid = match.group("uuid")
html = http.get('http://www.rtl.nl/system/s4m/vfd/version=2/uuid={}/d=pc/fmt=adaptive/'.format(uuid)).text
playlist_url = "http://manifest.us.rtl.nl" + re.compile('videopath":"(?P<playlist_url>.*?)",', re.IGNORECASE).search(html).group("playlist_url")
return HLSStream.parse_variant_playlist(self.session, playlist_url)
__plugin__ = rtlxl
|
<commit_before>import re
from livestreamer.plugin import Plugin
from livestreamer.plugin.api import http, validate
from livestreamer.stream import HDSStream, HLSStream, RTMPStream
_url_re = re.compile("""http(?:s)?://(?:\w+\.)?rtlxl.nl/#!/(?:.*)/(?P<uuid>.*?)\Z""", re.IGNORECASE)
class rtlxl(Plugin):
@classmethod
def can_handle_url(cls, url):
return _url_re.match(url)
def _get_streams(self):
match = _url_re.match(self.url)
uuid = match.group("uuid")
html = http.get('http://www.rtl.nl/system/s4m/vfd/version=2/uuid={}/d=pc/fmt=adaptive/'.format(uuid)).text
playlist_url = "http://manifest.us.rtl.nl" + re.compile('videopath":"(?P<playlist_url>.*?)",', re.IGNORECASE).search(html).group("playlist_url")
print playlist_url
return HLSStream.parse_variant_playlist(self.session, playlist_url)
__plugin__ = rtlxl
<commit_msg>Remove spurious print statement that made the plugin incompatible with python 3.<commit_after>import re
from livestreamer.plugin import Plugin
from livestreamer.plugin.api import http, validate
from livestreamer.stream import HDSStream, HLSStream, RTMPStream
_url_re = re.compile("""http(?:s)?://(?:\w+\.)?rtlxl.nl/#!/(?:.*)/(?P<uuid>.*?)\Z""", re.IGNORECASE)
class rtlxl(Plugin):
@classmethod
def can_handle_url(cls, url):
return _url_re.match(url)
def _get_streams(self):
match = _url_re.match(self.url)
uuid = match.group("uuid")
html = http.get('http://www.rtl.nl/system/s4m/vfd/version=2/uuid={}/d=pc/fmt=adaptive/'.format(uuid)).text
playlist_url = "http://manifest.us.rtl.nl" + re.compile('videopath":"(?P<playlist_url>.*?)",', re.IGNORECASE).search(html).group("playlist_url")
return HLSStream.parse_variant_playlist(self.session, playlist_url)
__plugin__ = rtlxl
|
cc3a970e893ebe6635982bcd49c48e6549cb5ac3
|
stdnum/au/__init__.py
|
stdnum/au/__init__.py
|
# __init__.py - collection of Australian numbers
# coding: utf-8
#
# Copyright (C) 2016 Vincent Bastos
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
"""Collection of Australian numbers."""
# provide aliases
from stdnum.au import tfn as vat # noqa: F401
|
# __init__.py - collection of Australian numbers
# coding: utf-8
#
# Copyright (C) 2016 Vincent Bastos
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
"""Collection of Australian numbers."""
# provide aliases
from stdnum.au import abn as vat # noqa: F401
|
Use ABN as Australian VAT number
|
Use ABN as Australian VAT number
See https://www.ato.gov.au/Business/GST/Tax-invoices/
Closes https://github.com/arthurdejong/python-stdnum/pull/246
|
Python
|
lgpl-2.1
|
arthurdejong/python-stdnum,arthurdejong/python-stdnum,arthurdejong/python-stdnum
|
# __init__.py - collection of Australian numbers
# coding: utf-8
#
# Copyright (C) 2016 Vincent Bastos
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
"""Collection of Australian numbers."""
# provide aliases
from stdnum.au import tfn as vat # noqa: F401
Use ABN as Australian VAT number
See https://www.ato.gov.au/Business/GST/Tax-invoices/
Closes https://github.com/arthurdejong/python-stdnum/pull/246
|
# __init__.py - collection of Australian numbers
# coding: utf-8
#
# Copyright (C) 2016 Vincent Bastos
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
"""Collection of Australian numbers."""
# provide aliases
from stdnum.au import abn as vat # noqa: F401
|
<commit_before># __init__.py - collection of Australian numbers
# coding: utf-8
#
# Copyright (C) 2016 Vincent Bastos
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
"""Collection of Australian numbers."""
# provide aliases
from stdnum.au import tfn as vat # noqa: F401
<commit_msg>Use ABN as Australian VAT number
See https://www.ato.gov.au/Business/GST/Tax-invoices/
Closes https://github.com/arthurdejong/python-stdnum/pull/246<commit_after>
|
# __init__.py - collection of Australian numbers
# coding: utf-8
#
# Copyright (C) 2016 Vincent Bastos
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
"""Collection of Australian numbers."""
# provide aliases
from stdnum.au import abn as vat # noqa: F401
|
# __init__.py - collection of Australian numbers
# coding: utf-8
#
# Copyright (C) 2016 Vincent Bastos
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
"""Collection of Australian numbers."""
# provide aliases
from stdnum.au import tfn as vat # noqa: F401
Use ABN as Australian VAT number
See https://www.ato.gov.au/Business/GST/Tax-invoices/
Closes https://github.com/arthurdejong/python-stdnum/pull/246# __init__.py - collection of Australian numbers
# coding: utf-8
#
# Copyright (C) 2016 Vincent Bastos
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
"""Collection of Australian numbers."""
# provide aliases
from stdnum.au import abn as vat # noqa: F401
|
<commit_before># __init__.py - collection of Australian numbers
# coding: utf-8
#
# Copyright (C) 2016 Vincent Bastos
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
"""Collection of Australian numbers."""
# provide aliases
from stdnum.au import tfn as vat # noqa: F401
<commit_msg>Use ABN as Australian VAT number
See https://www.ato.gov.au/Business/GST/Tax-invoices/
Closes https://github.com/arthurdejong/python-stdnum/pull/246<commit_after># __init__.py - collection of Australian numbers
# coding: utf-8
#
# Copyright (C) 2016 Vincent Bastos
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
"""Collection of Australian numbers."""
# provide aliases
from stdnum.au import abn as vat # noqa: F401
|
9be7deeaf400858dc00118d274b4cf4d19c60858
|
stdnum/cr/__init__.py
|
stdnum/cr/__init__.py
|
# __init__.py - collection of Costa Rican numbers
# coding: utf-8
#
# Copyright (C) 2019 Leandro Regueiro
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
"""Collection of Costa Rican numbers."""
|
# __init__.py - collection of Costa Rican numbers
# coding: utf-8
#
# Copyright (C) 2019 Leandro Regueiro
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
"""Collection of Costa Rican numbers."""
from stdnum.cr import cpj as vat # noqa: F401
|
Add missing vat alias for Costa Rica
|
Add missing vat alias for Costa Rica
|
Python
|
lgpl-2.1
|
arthurdejong/python-stdnum,arthurdejong/python-stdnum,arthurdejong/python-stdnum
|
# __init__.py - collection of Costa Rican numbers
# coding: utf-8
#
# Copyright (C) 2019 Leandro Regueiro
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
"""Collection of Costa Rican numbers."""
Add missing vat alias for Costa Rica
|
# __init__.py - collection of Costa Rican numbers
# coding: utf-8
#
# Copyright (C) 2019 Leandro Regueiro
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
"""Collection of Costa Rican numbers."""
from stdnum.cr import cpj as vat # noqa: F401
|
<commit_before># __init__.py - collection of Costa Rican numbers
# coding: utf-8
#
# Copyright (C) 2019 Leandro Regueiro
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
"""Collection of Costa Rican numbers."""
<commit_msg>Add missing vat alias for Costa Rica<commit_after>
|
# __init__.py - collection of Costa Rican numbers
# coding: utf-8
#
# Copyright (C) 2019 Leandro Regueiro
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
"""Collection of Costa Rican numbers."""
from stdnum.cr import cpj as vat # noqa: F401
|
# __init__.py - collection of Costa Rican numbers
# coding: utf-8
#
# Copyright (C) 2019 Leandro Regueiro
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
"""Collection of Costa Rican numbers."""
Add missing vat alias for Costa Rica# __init__.py - collection of Costa Rican numbers
# coding: utf-8
#
# Copyright (C) 2019 Leandro Regueiro
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
"""Collection of Costa Rican numbers."""
from stdnum.cr import cpj as vat # noqa: F401
|
<commit_before># __init__.py - collection of Costa Rican numbers
# coding: utf-8
#
# Copyright (C) 2019 Leandro Regueiro
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
"""Collection of Costa Rican numbers."""
<commit_msg>Add missing vat alias for Costa Rica<commit_after># __init__.py - collection of Costa Rican numbers
# coding: utf-8
#
# Copyright (C) 2019 Leandro Regueiro
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
"""Collection of Costa Rican numbers."""
from stdnum.cr import cpj as vat # noqa: F401
|
12c2c7f20e46dce54990d5cf4c0e51ab02d549c4
|
adder/__init__.py
|
adder/__init__.py
|
"""adder is an amazing module which adds things"""
def add(first, second):
"""The power of add is that it adds its arguments"""
return first + second
|
"""A mighty module to add things to each other"""
def add(first, second):
"""The power of add is that it adds its arguments"""
return first + second
|
Make the docstring match the github description
|
Make the docstring match the github description
|
Python
|
mit
|
jamesmcdonald/adder
|
"""adder is an amazing module which adds things"""
def add(first, second):
"""The power of add is that it adds its arguments"""
return first + second
Make the docstring match the github description
|
"""A mighty module to add things to each other"""
def add(first, second):
"""The power of add is that it adds its arguments"""
return first + second
|
<commit_before>"""adder is an amazing module which adds things"""
def add(first, second):
"""The power of add is that it adds its arguments"""
return first + second
<commit_msg>Make the docstring match the github description<commit_after>
|
"""A mighty module to add things to each other"""
def add(first, second):
"""The power of add is that it adds its arguments"""
return first + second
|
"""adder is an amazing module which adds things"""
def add(first, second):
"""The power of add is that it adds its arguments"""
return first + second
Make the docstring match the github description"""A mighty module to add things to each other"""
def add(first, second):
"""The power of add is that it adds its arguments"""
return first + second
|
<commit_before>"""adder is an amazing module which adds things"""
def add(first, second):
"""The power of add is that it adds its arguments"""
return first + second
<commit_msg>Make the docstring match the github description<commit_after>"""A mighty module to add things to each other"""
def add(first, second):
"""The power of add is that it adds its arguments"""
return first + second
|
a263ad297000fbefb9399249198be630718350f8
|
transfers/pre-transfer/add_metadata.py
|
transfers/pre-transfer/add_metadata.py
|
#!/usr/bin/env python2
import json
import os
import sys
def main(transfer_path):
basename = os.path.basename(transfer_path)
try:
_, dc_id, _ = basename.split('---')
except ValueError:
return 1
metadata = [
{
'parts': 'objects',
'dc.identifier': dc_id,
}
]
metadata_path = os.path.join(transfer_path, 'metadata')
if not os.path.exists(metadata_path):
os.makedirs(metadata_path)
metadata_path = os.path.join(metadata_path, 'metadata.json')
with open(metadata_path, 'w') as f:
json.dump(metadata, f)
return 0
if __name__ == '__main__':
transfer_path = sys.argv[1]
sys.exit(main(transfer_path))
|
#!/usr/bin/env python2
import json
import os
import sys
def main(transfer_path):
basename = os.path.basename(transfer_path)
try:
dc_id, _, _ = basename.split('---')
except ValueError:
return 1
metadata = [
{
'parts': 'objects',
'dc.identifier': dc_id,
}
]
metadata_path = os.path.join(transfer_path, 'metadata')
if not os.path.exists(metadata_path):
os.makedirs(metadata_path)
metadata_path = os.path.join(metadata_path, 'metadata.json')
with open(metadata_path, 'w') as f:
json.dump(metadata, f)
return 0
if __name__ == '__main__':
transfer_path = sys.argv[1]
sys.exit(main(transfer_path))
|
Automate Transfers: Change default metadata added
|
Automate Transfers: Change default metadata added
|
Python
|
agpl-3.0
|
artefactual/automation-tools,artefactual/automation-tools,finoradin/automation-tools
|
#!/usr/bin/env python2
import json
import os
import sys
def main(transfer_path):
basename = os.path.basename(transfer_path)
try:
_, dc_id, _ = basename.split('---')
except ValueError:
return 1
metadata = [
{
'parts': 'objects',
'dc.identifier': dc_id,
}
]
metadata_path = os.path.join(transfer_path, 'metadata')
if not os.path.exists(metadata_path):
os.makedirs(metadata_path)
metadata_path = os.path.join(metadata_path, 'metadata.json')
with open(metadata_path, 'w') as f:
json.dump(metadata, f)
return 0
if __name__ == '__main__':
transfer_path = sys.argv[1]
sys.exit(main(transfer_path))
Automate Transfers: Change default metadata added
|
#!/usr/bin/env python2
import json
import os
import sys
def main(transfer_path):
basename = os.path.basename(transfer_path)
try:
dc_id, _, _ = basename.split('---')
except ValueError:
return 1
metadata = [
{
'parts': 'objects',
'dc.identifier': dc_id,
}
]
metadata_path = os.path.join(transfer_path, 'metadata')
if not os.path.exists(metadata_path):
os.makedirs(metadata_path)
metadata_path = os.path.join(metadata_path, 'metadata.json')
with open(metadata_path, 'w') as f:
json.dump(metadata, f)
return 0
if __name__ == '__main__':
transfer_path = sys.argv[1]
sys.exit(main(transfer_path))
|
<commit_before>#!/usr/bin/env python2
import json
import os
import sys
def main(transfer_path):
basename = os.path.basename(transfer_path)
try:
_, dc_id, _ = basename.split('---')
except ValueError:
return 1
metadata = [
{
'parts': 'objects',
'dc.identifier': dc_id,
}
]
metadata_path = os.path.join(transfer_path, 'metadata')
if not os.path.exists(metadata_path):
os.makedirs(metadata_path)
metadata_path = os.path.join(metadata_path, 'metadata.json')
with open(metadata_path, 'w') as f:
json.dump(metadata, f)
return 0
if __name__ == '__main__':
transfer_path = sys.argv[1]
sys.exit(main(transfer_path))
<commit_msg>Automate Transfers: Change default metadata added<commit_after>
|
#!/usr/bin/env python2
import json
import os
import sys
def main(transfer_path):
basename = os.path.basename(transfer_path)
try:
dc_id, _, _ = basename.split('---')
except ValueError:
return 1
metadata = [
{
'parts': 'objects',
'dc.identifier': dc_id,
}
]
metadata_path = os.path.join(transfer_path, 'metadata')
if not os.path.exists(metadata_path):
os.makedirs(metadata_path)
metadata_path = os.path.join(metadata_path, 'metadata.json')
with open(metadata_path, 'w') as f:
json.dump(metadata, f)
return 0
if __name__ == '__main__':
transfer_path = sys.argv[1]
sys.exit(main(transfer_path))
|
#!/usr/bin/env python2
import json
import os
import sys
def main(transfer_path):
basename = os.path.basename(transfer_path)
try:
_, dc_id, _ = basename.split('---')
except ValueError:
return 1
metadata = [
{
'parts': 'objects',
'dc.identifier': dc_id,
}
]
metadata_path = os.path.join(transfer_path, 'metadata')
if not os.path.exists(metadata_path):
os.makedirs(metadata_path)
metadata_path = os.path.join(metadata_path, 'metadata.json')
with open(metadata_path, 'w') as f:
json.dump(metadata, f)
return 0
if __name__ == '__main__':
transfer_path = sys.argv[1]
sys.exit(main(transfer_path))
Automate Transfers: Change default metadata added#!/usr/bin/env python2
import json
import os
import sys
def main(transfer_path):
basename = os.path.basename(transfer_path)
try:
dc_id, _, _ = basename.split('---')
except ValueError:
return 1
metadata = [
{
'parts': 'objects',
'dc.identifier': dc_id,
}
]
metadata_path = os.path.join(transfer_path, 'metadata')
if not os.path.exists(metadata_path):
os.makedirs(metadata_path)
metadata_path = os.path.join(metadata_path, 'metadata.json')
with open(metadata_path, 'w') as f:
json.dump(metadata, f)
return 0
if __name__ == '__main__':
transfer_path = sys.argv[1]
sys.exit(main(transfer_path))
|
<commit_before>#!/usr/bin/env python2
import json
import os
import sys
def main(transfer_path):
basename = os.path.basename(transfer_path)
try:
_, dc_id, _ = basename.split('---')
except ValueError:
return 1
metadata = [
{
'parts': 'objects',
'dc.identifier': dc_id,
}
]
metadata_path = os.path.join(transfer_path, 'metadata')
if not os.path.exists(metadata_path):
os.makedirs(metadata_path)
metadata_path = os.path.join(metadata_path, 'metadata.json')
with open(metadata_path, 'w') as f:
json.dump(metadata, f)
return 0
if __name__ == '__main__':
transfer_path = sys.argv[1]
sys.exit(main(transfer_path))
<commit_msg>Automate Transfers: Change default metadata added<commit_after>#!/usr/bin/env python2
import json
import os
import sys
def main(transfer_path):
basename = os.path.basename(transfer_path)
try:
dc_id, _, _ = basename.split('---')
except ValueError:
return 1
metadata = [
{
'parts': 'objects',
'dc.identifier': dc_id,
}
]
metadata_path = os.path.join(transfer_path, 'metadata')
if not os.path.exists(metadata_path):
os.makedirs(metadata_path)
metadata_path = os.path.join(metadata_path, 'metadata.json')
with open(metadata_path, 'w') as f:
json.dump(metadata, f)
return 0
if __name__ == '__main__':
transfer_path = sys.argv[1]
sys.exit(main(transfer_path))
|
cfeaf5b01b6c822b2351a556e48a1a68aa2bce88
|
glue_vispy_viewers/volume/tests/test_glue_viewer.py
|
glue_vispy_viewers/volume/tests/test_glue_viewer.py
|
import operator
import numpy as np
from glue.qt import get_qapp
from glue.core.data import Data
from glue.core.data_collection import DataCollection
from glue.app.qt.application import GlueApplication
from glue.core.subset import InequalitySubsetState
# from glue.core.tests.util import simple_session
from ..vol_glue_viewer import GlueVispyViewer
def test_viewer():
app = get_qapp()
data = Data(x=np.arange(1000).reshape((10, 10, 10)) / 1000.)
dc = DataCollection([data])
app = GlueApplication(dc)
app.new_data_viewer(GlueVispyViewer, data=data)
subset_state1 = InequalitySubsetState(data.find_component_id('x'), 2/3., operator.gt)
dc.new_subset_group(label='test_subset1', subset_state=subset_state1)
subset_state2 = InequalitySubsetState(data.find_component_id('x'), 1/3., operator.lt)
dc.new_subset_group(label='test_subset2', subset_state=subset_state2)
app.show()
|
import operator
import numpy as np
from glue.qt import get_qapp
from glue.core.data import Data
from glue.core.data_collection import DataCollection
try:
from glue.app.qt.application import GlueApplication
except:
from glue.qt.glue_application import GlueApplication
from glue.core.subset import InequalitySubsetState
# from glue.core.tests.util import simple_session
from ..vol_glue_viewer import GlueVispyViewer
def test_viewer():
app = get_qapp()
data = Data(x=np.arange(1000).reshape((10, 10, 10)) / 1000.)
dc = DataCollection([data])
app = GlueApplication(dc)
app.new_data_viewer(GlueVispyViewer, data=data)
subset_state1 = InequalitySubsetState(data.find_component_id('x'), 2/3., operator.gt)
dc.new_subset_group(label='test_subset1', subset_state=subset_state1)
subset_state2 = InequalitySubsetState(data.find_component_id('x'), 1/3., operator.lt)
dc.new_subset_group(label='test_subset2', subset_state=subset_state2)
app.show()
|
Fix compatibility with latest stable glue version
|
Fix compatibility with latest stable glue version
|
Python
|
bsd-2-clause
|
PennyQ/astro-vispy,PennyQ/glue-3d-viewer,astrofrog/glue-vispy-viewers,glue-viz/glue-3d-viewer,glue-viz/glue-vispy-viewers,astrofrog/glue-3d-viewer
|
import operator
import numpy as np
from glue.qt import get_qapp
from glue.core.data import Data
from glue.core.data_collection import DataCollection
from glue.app.qt.application import GlueApplication
from glue.core.subset import InequalitySubsetState
# from glue.core.tests.util import simple_session
from ..vol_glue_viewer import GlueVispyViewer
def test_viewer():
app = get_qapp()
data = Data(x=np.arange(1000).reshape((10, 10, 10)) / 1000.)
dc = DataCollection([data])
app = GlueApplication(dc)
app.new_data_viewer(GlueVispyViewer, data=data)
subset_state1 = InequalitySubsetState(data.find_component_id('x'), 2/3., operator.gt)
dc.new_subset_group(label='test_subset1', subset_state=subset_state1)
subset_state2 = InequalitySubsetState(data.find_component_id('x'), 1/3., operator.lt)
dc.new_subset_group(label='test_subset2', subset_state=subset_state2)
app.show()
Fix compatibility with latest stable glue version
|
import operator
import numpy as np
from glue.qt import get_qapp
from glue.core.data import Data
from glue.core.data_collection import DataCollection
try:
from glue.app.qt.application import GlueApplication
except:
from glue.qt.glue_application import GlueApplication
from glue.core.subset import InequalitySubsetState
# from glue.core.tests.util import simple_session
from ..vol_glue_viewer import GlueVispyViewer
def test_viewer():
app = get_qapp()
data = Data(x=np.arange(1000).reshape((10, 10, 10)) / 1000.)
dc = DataCollection([data])
app = GlueApplication(dc)
app.new_data_viewer(GlueVispyViewer, data=data)
subset_state1 = InequalitySubsetState(data.find_component_id('x'), 2/3., operator.gt)
dc.new_subset_group(label='test_subset1', subset_state=subset_state1)
subset_state2 = InequalitySubsetState(data.find_component_id('x'), 1/3., operator.lt)
dc.new_subset_group(label='test_subset2', subset_state=subset_state2)
app.show()
|
<commit_before>import operator
import numpy as np
from glue.qt import get_qapp
from glue.core.data import Data
from glue.core.data_collection import DataCollection
from glue.app.qt.application import GlueApplication
from glue.core.subset import InequalitySubsetState
# from glue.core.tests.util import simple_session
from ..vol_glue_viewer import GlueVispyViewer
def test_viewer():
app = get_qapp()
data = Data(x=np.arange(1000).reshape((10, 10, 10)) / 1000.)
dc = DataCollection([data])
app = GlueApplication(dc)
app.new_data_viewer(GlueVispyViewer, data=data)
subset_state1 = InequalitySubsetState(data.find_component_id('x'), 2/3., operator.gt)
dc.new_subset_group(label='test_subset1', subset_state=subset_state1)
subset_state2 = InequalitySubsetState(data.find_component_id('x'), 1/3., operator.lt)
dc.new_subset_group(label='test_subset2', subset_state=subset_state2)
app.show()
<commit_msg>Fix compatibility with latest stable glue version<commit_after>
|
import operator
import numpy as np
from glue.qt import get_qapp
from glue.core.data import Data
from glue.core.data_collection import DataCollection
try:
from glue.app.qt.application import GlueApplication
except:
from glue.qt.glue_application import GlueApplication
from glue.core.subset import InequalitySubsetState
# from glue.core.tests.util import simple_session
from ..vol_glue_viewer import GlueVispyViewer
def test_viewer():
app = get_qapp()
data = Data(x=np.arange(1000).reshape((10, 10, 10)) / 1000.)
dc = DataCollection([data])
app = GlueApplication(dc)
app.new_data_viewer(GlueVispyViewer, data=data)
subset_state1 = InequalitySubsetState(data.find_component_id('x'), 2/3., operator.gt)
dc.new_subset_group(label='test_subset1', subset_state=subset_state1)
subset_state2 = InequalitySubsetState(data.find_component_id('x'), 1/3., operator.lt)
dc.new_subset_group(label='test_subset2', subset_state=subset_state2)
app.show()
|
import operator
import numpy as np
from glue.qt import get_qapp
from glue.core.data import Data
from glue.core.data_collection import DataCollection
from glue.app.qt.application import GlueApplication
from glue.core.subset import InequalitySubsetState
# from glue.core.tests.util import simple_session
from ..vol_glue_viewer import GlueVispyViewer
def test_viewer():
app = get_qapp()
data = Data(x=np.arange(1000).reshape((10, 10, 10)) / 1000.)
dc = DataCollection([data])
app = GlueApplication(dc)
app.new_data_viewer(GlueVispyViewer, data=data)
subset_state1 = InequalitySubsetState(data.find_component_id('x'), 2/3., operator.gt)
dc.new_subset_group(label='test_subset1', subset_state=subset_state1)
subset_state2 = InequalitySubsetState(data.find_component_id('x'), 1/3., operator.lt)
dc.new_subset_group(label='test_subset2', subset_state=subset_state2)
app.show()
Fix compatibility with latest stable glue versionimport operator
import numpy as np
from glue.qt import get_qapp
from glue.core.data import Data
from glue.core.data_collection import DataCollection
try:
from glue.app.qt.application import GlueApplication
except:
from glue.qt.glue_application import GlueApplication
from glue.core.subset import InequalitySubsetState
# from glue.core.tests.util import simple_session
from ..vol_glue_viewer import GlueVispyViewer
def test_viewer():
app = get_qapp()
data = Data(x=np.arange(1000).reshape((10, 10, 10)) / 1000.)
dc = DataCollection([data])
app = GlueApplication(dc)
app.new_data_viewer(GlueVispyViewer, data=data)
subset_state1 = InequalitySubsetState(data.find_component_id('x'), 2/3., operator.gt)
dc.new_subset_group(label='test_subset1', subset_state=subset_state1)
subset_state2 = InequalitySubsetState(data.find_component_id('x'), 1/3., operator.lt)
dc.new_subset_group(label='test_subset2', subset_state=subset_state2)
app.show()
|
<commit_before>import operator
import numpy as np
from glue.qt import get_qapp
from glue.core.data import Data
from glue.core.data_collection import DataCollection
from glue.app.qt.application import GlueApplication
from glue.core.subset import InequalitySubsetState
# from glue.core.tests.util import simple_session
from ..vol_glue_viewer import GlueVispyViewer
def test_viewer():
app = get_qapp()
data = Data(x=np.arange(1000).reshape((10, 10, 10)) / 1000.)
dc = DataCollection([data])
app = GlueApplication(dc)
app.new_data_viewer(GlueVispyViewer, data=data)
subset_state1 = InequalitySubsetState(data.find_component_id('x'), 2/3., operator.gt)
dc.new_subset_group(label='test_subset1', subset_state=subset_state1)
subset_state2 = InequalitySubsetState(data.find_component_id('x'), 1/3., operator.lt)
dc.new_subset_group(label='test_subset2', subset_state=subset_state2)
app.show()
<commit_msg>Fix compatibility with latest stable glue version<commit_after>import operator
import numpy as np
from glue.qt import get_qapp
from glue.core.data import Data
from glue.core.data_collection import DataCollection
try:
from glue.app.qt.application import GlueApplication
except:
from glue.qt.glue_application import GlueApplication
from glue.core.subset import InequalitySubsetState
# from glue.core.tests.util import simple_session
from ..vol_glue_viewer import GlueVispyViewer
def test_viewer():
app = get_qapp()
data = Data(x=np.arange(1000).reshape((10, 10, 10)) / 1000.)
dc = DataCollection([data])
app = GlueApplication(dc)
app.new_data_viewer(GlueVispyViewer, data=data)
subset_state1 = InequalitySubsetState(data.find_component_id('x'), 2/3., operator.gt)
dc.new_subset_group(label='test_subset1', subset_state=subset_state1)
subset_state2 = InequalitySubsetState(data.find_component_id('x'), 1/3., operator.lt)
dc.new_subset_group(label='test_subset2', subset_state=subset_state2)
app.show()
|
b5bfa67c87c7043f521cde32e7212c0fffdbacd9
|
Solutions/problem67.py
|
Solutions/problem67.py
|
# Project Euler Problem 67
# Created on: 2012-06-18
# Created by: William McDonald
def importTri():
t = []
f = open("problem67.txt")
for line in f:
t.append(map(int, line.split(" ")))
return t
def getMax(lm, cur):
l = len(cur) - 1
maxL = [lm[0] + cur[0]]
i = 1
while True:
if i == l:
maxL.append(lm[i - 1] + cur[i])
break
maxL.append(max((lm[i - 1]), lm[i]) + cur[i])
i += 1
return maxL
def getAns():
t = importTri()
lmax = t[0]
for i in range(1, len(t)):
lmax = getMax(lmax, t[i])
print(max(x for x in lmax))
getAns()
|
# Project Euler Problem 67
def import_triangle():
with open('problem67.txt') as f:
# Split each line by spaces and convert to integers
return [list(map(int, line.split(' '))) for line in f]
# The max of this row is the maximum sum up to its parent items plus the value
# in this row. But note that the first and last items in this row only have one
# parent each, so it can make the code a little funky to write.
def get_max(last_maxes, cur):
current_maxes = [cur[0] + last_maxes[0]]
for idx, lm in enumerate(last_maxes):
# Our left child was the right child of a previous element; get max
max_for_left_child = cur[idx] + lm
current_maxes[idx] = max(current_maxes[idx], max_for_left_child)
# Right child hasn't been seen yet, just append it
current_maxes.append(lm + cur[idx + 1])
return current_maxes
def solve():
triangle = import_triangle()
max_for_last_row = triangle[0]
for current_row in triangle[1:]:
max_for_last_row = get_max(max_for_last_row, current_row)
print('Answer: {}'.format(max(max_for_last_row)))
if __name__ == '__main__':
solve()
|
Update problem 67 to be legible
|
Update problem 67 to be legible
|
Python
|
mit
|
WalrusCow/euler
|
# Project Euler Problem 67
# Created on: 2012-06-18
# Created by: William McDonald
def importTri():
t = []
f = open("problem67.txt")
for line in f:
t.append(map(int, line.split(" ")))
return t
def getMax(lm, cur):
l = len(cur) - 1
maxL = [lm[0] + cur[0]]
i = 1
while True:
if i == l:
maxL.append(lm[i - 1] + cur[i])
break
maxL.append(max((lm[i - 1]), lm[i]) + cur[i])
i += 1
return maxL
def getAns():
t = importTri()
lmax = t[0]
for i in range(1, len(t)):
lmax = getMax(lmax, t[i])
print(max(x for x in lmax))
getAns()
Update problem 67 to be legible
|
# Project Euler Problem 67
def import_triangle():
with open('problem67.txt') as f:
# Split each line by spaces and convert to integers
return [list(map(int, line.split(' '))) for line in f]
# The max of this row is the maximum sum up to its parent items plus the value
# in this row. But note that the first and last items in this row only have one
# parent each, so it can make the code a little funky to write.
def get_max(last_maxes, cur):
current_maxes = [cur[0] + last_maxes[0]]
for idx, lm in enumerate(last_maxes):
# Our left child was the right child of a previous element; get max
max_for_left_child = cur[idx] + lm
current_maxes[idx] = max(current_maxes[idx], max_for_left_child)
# Right child hasn't been seen yet, just append it
current_maxes.append(lm + cur[idx + 1])
return current_maxes
def solve():
triangle = import_triangle()
max_for_last_row = triangle[0]
for current_row in triangle[1:]:
max_for_last_row = get_max(max_for_last_row, current_row)
print('Answer: {}'.format(max(max_for_last_row)))
if __name__ == '__main__':
solve()
|
<commit_before># Project Euler Problem 67
# Created on: 2012-06-18
# Created by: William McDonald
def importTri():
t = []
f = open("problem67.txt")
for line in f:
t.append(map(int, line.split(" ")))
return t
def getMax(lm, cur):
l = len(cur) - 1
maxL = [lm[0] + cur[0]]
i = 1
while True:
if i == l:
maxL.append(lm[i - 1] + cur[i])
break
maxL.append(max((lm[i - 1]), lm[i]) + cur[i])
i += 1
return maxL
def getAns():
t = importTri()
lmax = t[0]
for i in range(1, len(t)):
lmax = getMax(lmax, t[i])
print(max(x for x in lmax))
getAns()
<commit_msg>Update problem 67 to be legible<commit_after>
|
# Project Euler Problem 67
def import_triangle():
with open('problem67.txt') as f:
# Split each line by spaces and convert to integers
return [list(map(int, line.split(' '))) for line in f]
# The max of this row is the maximum sum up to its parent items plus the value
# in this row. But note that the first and last items in this row only have one
# parent each, so it can make the code a little funky to write.
def get_max(last_maxes, cur):
current_maxes = [cur[0] + last_maxes[0]]
for idx, lm in enumerate(last_maxes):
# Our left child was the right child of a previous element; get max
max_for_left_child = cur[idx] + lm
current_maxes[idx] = max(current_maxes[idx], max_for_left_child)
# Right child hasn't been seen yet, just append it
current_maxes.append(lm + cur[idx + 1])
return current_maxes
def solve():
triangle = import_triangle()
max_for_last_row = triangle[0]
for current_row in triangle[1:]:
max_for_last_row = get_max(max_for_last_row, current_row)
print('Answer: {}'.format(max(max_for_last_row)))
if __name__ == '__main__':
solve()
|
# Project Euler Problem 67
# Created on: 2012-06-18
# Created by: William McDonald
def importTri():
t = []
f = open("problem67.txt")
for line in f:
t.append(map(int, line.split(" ")))
return t
def getMax(lm, cur):
l = len(cur) - 1
maxL = [lm[0] + cur[0]]
i = 1
while True:
if i == l:
maxL.append(lm[i - 1] + cur[i])
break
maxL.append(max((lm[i - 1]), lm[i]) + cur[i])
i += 1
return maxL
def getAns():
t = importTri()
lmax = t[0]
for i in range(1, len(t)):
lmax = getMax(lmax, t[i])
print(max(x for x in lmax))
getAns()
Update problem 67 to be legible# Project Euler Problem 67
def import_triangle():
with open('problem67.txt') as f:
# Split each line by spaces and convert to integers
return [list(map(int, line.split(' '))) for line in f]
# The max of this row is the maximum sum up to its parent items plus the value
# in this row. But note that the first and last items in this row only have one
# parent each, so it can make the code a little funky to write.
def get_max(last_maxes, cur):
current_maxes = [cur[0] + last_maxes[0]]
for idx, lm in enumerate(last_maxes):
# Our left child was the right child of a previous element; get max
max_for_left_child = cur[idx] + lm
current_maxes[idx] = max(current_maxes[idx], max_for_left_child)
# Right child hasn't been seen yet, just append it
current_maxes.append(lm + cur[idx + 1])
return current_maxes
def solve():
triangle = import_triangle()
max_for_last_row = triangle[0]
for current_row in triangle[1:]:
max_for_last_row = get_max(max_for_last_row, current_row)
print('Answer: {}'.format(max(max_for_last_row)))
if __name__ == '__main__':
solve()
|
<commit_before># Project Euler Problem 67
# Created on: 2012-06-18
# Created by: William McDonald
def importTri():
t = []
f = open("problem67.txt")
for line in f:
t.append(map(int, line.split(" ")))
return t
def getMax(lm, cur):
l = len(cur) - 1
maxL = [lm[0] + cur[0]]
i = 1
while True:
if i == l:
maxL.append(lm[i - 1] + cur[i])
break
maxL.append(max((lm[i - 1]), lm[i]) + cur[i])
i += 1
return maxL
def getAns():
t = importTri()
lmax = t[0]
for i in range(1, len(t)):
lmax = getMax(lmax, t[i])
print(max(x for x in lmax))
getAns()
<commit_msg>Update problem 67 to be legible<commit_after># Project Euler Problem 67
def import_triangle():
with open('problem67.txt') as f:
# Split each line by spaces and convert to integers
return [list(map(int, line.split(' '))) for line in f]
# The max of this row is the maximum sum up to its parent items plus the value
# in this row. But note that the first and last items in this row only have one
# parent each, so it can make the code a little funky to write.
def get_max(last_maxes, cur):
current_maxes = [cur[0] + last_maxes[0]]
for idx, lm in enumerate(last_maxes):
# Our left child was the right child of a previous element; get max
max_for_left_child = cur[idx] + lm
current_maxes[idx] = max(current_maxes[idx], max_for_left_child)
# Right child hasn't been seen yet, just append it
current_maxes.append(lm + cur[idx + 1])
return current_maxes
def solve():
triangle = import_triangle()
max_for_last_row = triangle[0]
for current_row in triangle[1:]:
max_for_last_row = get_max(max_for_last_row, current_row)
print('Answer: {}'.format(max(max_for_last_row)))
if __name__ == '__main__':
solve()
|
c787d7a0967a57ad6bec1924f4f5fdeeb07ffd0e
|
UM/Mesh/ReadMeshJob.py
|
UM/Mesh/ReadMeshJob.py
|
# Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from UM.Job import Job
from UM.Application import Application
from UM.Message import Message
import os.path
from UM.i18n import i18nCatalog
i18n_catalog = i18nCatalog("uranium")
## A Job subclass that performs mesh loading.
#
# The result of this Job is a MeshData object.
class ReadMeshJob(Job):
def __init__(self, filename):
super().__init__()
self._filename = filename
self._handler = Application.getInstance().getMeshFileHandler()
self._device = Application.getInstance().getStorageDevice("LocalFileStorage")
def getFileName(self):
return self._filename
def run(self):
loading_message = Message(i18n_catalog.i18nc("Loading mesh message, {0} is file name", "Loading {0}".format(self._filename)), lifetime = 0, dismissable = False)
loading_message.setProgress(-1)
loading_message.show()
self.setResult(self._handler.read(self._filename, self._device))
loading_message.hide()
result_message = Message(i18n_catalog.i18nc("Finished loading mesh message, {0} is file name", "Loaded {0}".format(self._filename)))
result_message.show()
|
# Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from UM.Job import Job
from UM.Application import Application
from UM.Message import Message
import os.path
from UM.i18n import i18nCatalog
i18n_catalog = i18nCatalog("uranium")
## A Job subclass that performs mesh loading.
#
# The result of this Job is a MeshData object.
class ReadMeshJob(Job):
def __init__(self, filename):
super().__init__()
self._filename = filename
self._handler = Application.getInstance().getMeshFileHandler()
self._device = Application.getInstance().getStorageDevice("LocalFileStorage")
def getFileName(self):
return self._filename
def run(self):
loading_message = Message(i18n_catalog.i18nc("Loading mesh message, {0} is file name", "Loading {0}").format(self._filename), lifetime = 0, dismissable = False)
loading_message.setProgress(-1)
loading_message.show()
self.setResult(self._handler.read(self._filename, self._device))
loading_message.hide()
result_message = Message(i18n_catalog.i18nc("Finished loading mesh message, {0} is file name", "Loaded {0}").format(self._filename))
result_message.show()
|
Format the message string after translating, not before
|
Format the message string after translating, not before
This makes sure we use the right translated string.
Contributes to Ultimaker/Cura#57
|
Python
|
agpl-3.0
|
onitake/Uranium,onitake/Uranium
|
# Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from UM.Job import Job
from UM.Application import Application
from UM.Message import Message
import os.path
from UM.i18n import i18nCatalog
i18n_catalog = i18nCatalog("uranium")
## A Job subclass that performs mesh loading.
#
# The result of this Job is a MeshData object.
class ReadMeshJob(Job):
def __init__(self, filename):
super().__init__()
self._filename = filename
self._handler = Application.getInstance().getMeshFileHandler()
self._device = Application.getInstance().getStorageDevice("LocalFileStorage")
def getFileName(self):
return self._filename
def run(self):
loading_message = Message(i18n_catalog.i18nc("Loading mesh message, {0} is file name", "Loading {0}".format(self._filename)), lifetime = 0, dismissable = False)
loading_message.setProgress(-1)
loading_message.show()
self.setResult(self._handler.read(self._filename, self._device))
loading_message.hide()
result_message = Message(i18n_catalog.i18nc("Finished loading mesh message, {0} is file name", "Loaded {0}".format(self._filename)))
result_message.show()Format the message string after translating, not before
This makes sure we use the right translated string.
Contributes to Ultimaker/Cura#57
|
# Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from UM.Job import Job
from UM.Application import Application
from UM.Message import Message
import os.path
from UM.i18n import i18nCatalog
i18n_catalog = i18nCatalog("uranium")
## A Job subclass that performs mesh loading.
#
# The result of this Job is a MeshData object.
class ReadMeshJob(Job):
def __init__(self, filename):
super().__init__()
self._filename = filename
self._handler = Application.getInstance().getMeshFileHandler()
self._device = Application.getInstance().getStorageDevice("LocalFileStorage")
def getFileName(self):
return self._filename
def run(self):
loading_message = Message(i18n_catalog.i18nc("Loading mesh message, {0} is file name", "Loading {0}").format(self._filename), lifetime = 0, dismissable = False)
loading_message.setProgress(-1)
loading_message.show()
self.setResult(self._handler.read(self._filename, self._device))
loading_message.hide()
result_message = Message(i18n_catalog.i18nc("Finished loading mesh message, {0} is file name", "Loaded {0}").format(self._filename))
result_message.show()
|
<commit_before># Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from UM.Job import Job
from UM.Application import Application
from UM.Message import Message
import os.path
from UM.i18n import i18nCatalog
i18n_catalog = i18nCatalog("uranium")
## A Job subclass that performs mesh loading.
#
# The result of this Job is a MeshData object.
class ReadMeshJob(Job):
def __init__(self, filename):
super().__init__()
self._filename = filename
self._handler = Application.getInstance().getMeshFileHandler()
self._device = Application.getInstance().getStorageDevice("LocalFileStorage")
def getFileName(self):
return self._filename
def run(self):
loading_message = Message(i18n_catalog.i18nc("Loading mesh message, {0} is file name", "Loading {0}".format(self._filename)), lifetime = 0, dismissable = False)
loading_message.setProgress(-1)
loading_message.show()
self.setResult(self._handler.read(self._filename, self._device))
loading_message.hide()
result_message = Message(i18n_catalog.i18nc("Finished loading mesh message, {0} is file name", "Loaded {0}".format(self._filename)))
result_message.show()<commit_msg>Format the message string after translating, not before
This makes sure we use the right translated string.
Contributes to Ultimaker/Cura#57<commit_after>
|
# Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from UM.Job import Job
from UM.Application import Application
from UM.Message import Message
import os.path
from UM.i18n import i18nCatalog
i18n_catalog = i18nCatalog("uranium")
## A Job subclass that performs mesh loading.
#
# The result of this Job is a MeshData object.
class ReadMeshJob(Job):
def __init__(self, filename):
super().__init__()
self._filename = filename
self._handler = Application.getInstance().getMeshFileHandler()
self._device = Application.getInstance().getStorageDevice("LocalFileStorage")
def getFileName(self):
return self._filename
def run(self):
loading_message = Message(i18n_catalog.i18nc("Loading mesh message, {0} is file name", "Loading {0}").format(self._filename), lifetime = 0, dismissable = False)
loading_message.setProgress(-1)
loading_message.show()
self.setResult(self._handler.read(self._filename, self._device))
loading_message.hide()
result_message = Message(i18n_catalog.i18nc("Finished loading mesh message, {0} is file name", "Loaded {0}").format(self._filename))
result_message.show()
|
# Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from UM.Job import Job
from UM.Application import Application
from UM.Message import Message
import os.path
from UM.i18n import i18nCatalog
i18n_catalog = i18nCatalog("uranium")
## A Job subclass that performs mesh loading.
#
# The result of this Job is a MeshData object.
class ReadMeshJob(Job):
def __init__(self, filename):
super().__init__()
self._filename = filename
self._handler = Application.getInstance().getMeshFileHandler()
self._device = Application.getInstance().getStorageDevice("LocalFileStorage")
def getFileName(self):
return self._filename
def run(self):
loading_message = Message(i18n_catalog.i18nc("Loading mesh message, {0} is file name", "Loading {0}".format(self._filename)), lifetime = 0, dismissable = False)
loading_message.setProgress(-1)
loading_message.show()
self.setResult(self._handler.read(self._filename, self._device))
loading_message.hide()
result_message = Message(i18n_catalog.i18nc("Finished loading mesh message, {0} is file name", "Loaded {0}".format(self._filename)))
result_message.show()Format the message string after translating, not before
This makes sure we use the right translated string.
Contributes to Ultimaker/Cura#57# Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from UM.Job import Job
from UM.Application import Application
from UM.Message import Message
import os.path
from UM.i18n import i18nCatalog
i18n_catalog = i18nCatalog("uranium")
## A Job subclass that performs mesh loading.
#
# The result of this Job is a MeshData object.
class ReadMeshJob(Job):
def __init__(self, filename):
super().__init__()
self._filename = filename
self._handler = Application.getInstance().getMeshFileHandler()
self._device = Application.getInstance().getStorageDevice("LocalFileStorage")
def getFileName(self):
return self._filename
def run(self):
loading_message = Message(i18n_catalog.i18nc("Loading mesh message, {0} is file name", "Loading {0}").format(self._filename), lifetime = 0, dismissable = False)
loading_message.setProgress(-1)
loading_message.show()
self.setResult(self._handler.read(self._filename, self._device))
loading_message.hide()
result_message = Message(i18n_catalog.i18nc("Finished loading mesh message, {0} is file name", "Loaded {0}").format(self._filename))
result_message.show()
|
<commit_before># Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from UM.Job import Job
from UM.Application import Application
from UM.Message import Message
import os.path
from UM.i18n import i18nCatalog
i18n_catalog = i18nCatalog("uranium")
## A Job subclass that performs mesh loading.
#
# The result of this Job is a MeshData object.
class ReadMeshJob(Job):
def __init__(self, filename):
super().__init__()
self._filename = filename
self._handler = Application.getInstance().getMeshFileHandler()
self._device = Application.getInstance().getStorageDevice("LocalFileStorage")
def getFileName(self):
return self._filename
def run(self):
loading_message = Message(i18n_catalog.i18nc("Loading mesh message, {0} is file name", "Loading {0}".format(self._filename)), lifetime = 0, dismissable = False)
loading_message.setProgress(-1)
loading_message.show()
self.setResult(self._handler.read(self._filename, self._device))
loading_message.hide()
result_message = Message(i18n_catalog.i18nc("Finished loading mesh message, {0} is file name", "Loaded {0}".format(self._filename)))
result_message.show()<commit_msg>Format the message string after translating, not before
This makes sure we use the right translated string.
Contributes to Ultimaker/Cura#57<commit_after># Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from UM.Job import Job
from UM.Application import Application
from UM.Message import Message
import os.path
from UM.i18n import i18nCatalog
i18n_catalog = i18nCatalog("uranium")
## A Job subclass that performs mesh loading.
#
# The result of this Job is a MeshData object.
class ReadMeshJob(Job):
def __init__(self, filename):
super().__init__()
self._filename = filename
self._handler = Application.getInstance().getMeshFileHandler()
self._device = Application.getInstance().getStorageDevice("LocalFileStorage")
def getFileName(self):
return self._filename
def run(self):
loading_message = Message(i18n_catalog.i18nc("Loading mesh message, {0} is file name", "Loading {0}").format(self._filename), lifetime = 0, dismissable = False)
loading_message.setProgress(-1)
loading_message.show()
self.setResult(self._handler.read(self._filename, self._device))
loading_message.hide()
result_message = Message(i18n_catalog.i18nc("Finished loading mesh message, {0} is file name", "Loaded {0}").format(self._filename))
result_message.show()
|
22ac94423dff44db01abdc28358c00fe5eaca79e
|
actually-do-refunds.py
|
actually-do-refunds.py
|
#!/usr/bin/env python -u
from __future__ import absolute_import, division, print_function, unicode_literals
import csv, os, requests
url = 'https://api.balancedpayments.com/debits/{}/refunds'
username = os.environ['BALANCED_API_USER']
inp = csv.reader(open('refunds.csv'))
inp.next() # headers
out = csv.reader(open('refunds.completed.csv', 'w+'))
out.writerow('ts', 'id', 'amount', 'code', 'body')
for ts, id, amount in inp:
response = requests.post( url.format(id)
, data={'amount': amount}
, auth=(username, '')
)
out.writerow((ts,id,amount,response.status_code,response.content))
|
#!/usr/bin/env python -u
from __future__ import absolute_import, division, print_function, unicode_literals
import csv, os, requests
url = 'https://api.balancedpayments.com/debits/{}/refunds'
username = os.environ['BALANCED_API_USER']
inp = csv.reader(open('refunds.csv'))
inp.next() # headers
out = csv.writer(open('refunds.completed.csv', 'w+'))
out.writerow(('ts', 'id', 'amount', 'code', 'body'))
for ts, id, amount in inp:
response = requests.post( url.format(id)
, data={'amount': amount}
, auth=(username, '')
)
out.writerow((ts,id,amount,response.status_code,response.content))
|
Clean up script to make refunds
|
Clean up script to make refunds
Tested against httpbin.org
|
Python
|
mit
|
gratipay/gratipay.com,gratipay/gratipay.com,gratipay/gratipay.com,gratipay/gratipay.com
|
#!/usr/bin/env python -u
from __future__ import absolute_import, division, print_function, unicode_literals
import csv, os, requests
url = 'https://api.balancedpayments.com/debits/{}/refunds'
username = os.environ['BALANCED_API_USER']
inp = csv.reader(open('refunds.csv'))
inp.next() # headers
out = csv.reader(open('refunds.completed.csv', 'w+'))
out.writerow('ts', 'id', 'amount', 'code', 'body')
for ts, id, amount in inp:
response = requests.post( url.format(id)
, data={'amount': amount}
, auth=(username, '')
)
out.writerow((ts,id,amount,response.status_code,response.content))
Clean up script to make refunds
Tested against httpbin.org
|
#!/usr/bin/env python -u
from __future__ import absolute_import, division, print_function, unicode_literals
import csv, os, requests
url = 'https://api.balancedpayments.com/debits/{}/refunds'
username = os.environ['BALANCED_API_USER']
inp = csv.reader(open('refunds.csv'))
inp.next() # headers
out = csv.writer(open('refunds.completed.csv', 'w+'))
out.writerow(('ts', 'id', 'amount', 'code', 'body'))
for ts, id, amount in inp:
response = requests.post( url.format(id)
, data={'amount': amount}
, auth=(username, '')
)
out.writerow((ts,id,amount,response.status_code,response.content))
|
<commit_before>#!/usr/bin/env python -u
from __future__ import absolute_import, division, print_function, unicode_literals
import csv, os, requests
url = 'https://api.balancedpayments.com/debits/{}/refunds'
username = os.environ['BALANCED_API_USER']
inp = csv.reader(open('refunds.csv'))
inp.next() # headers
out = csv.reader(open('refunds.completed.csv', 'w+'))
out.writerow('ts', 'id', 'amount', 'code', 'body')
for ts, id, amount in inp:
response = requests.post( url.format(id)
, data={'amount': amount}
, auth=(username, '')
)
out.writerow((ts,id,amount,response.status_code,response.content))
<commit_msg>Clean up script to make refunds
Tested against httpbin.org<commit_after>
|
#!/usr/bin/env python -u
from __future__ import absolute_import, division, print_function, unicode_literals
import csv, os, requests
url = 'https://api.balancedpayments.com/debits/{}/refunds'
username = os.environ['BALANCED_API_USER']
inp = csv.reader(open('refunds.csv'))
inp.next() # headers
out = csv.writer(open('refunds.completed.csv', 'w+'))
out.writerow(('ts', 'id', 'amount', 'code', 'body'))
for ts, id, amount in inp:
response = requests.post( url.format(id)
, data={'amount': amount}
, auth=(username, '')
)
out.writerow((ts,id,amount,response.status_code,response.content))
|
#!/usr/bin/env python -u
from __future__ import absolute_import, division, print_function, unicode_literals
import csv, os, requests
url = 'https://api.balancedpayments.com/debits/{}/refunds'
username = os.environ['BALANCED_API_USER']
inp = csv.reader(open('refunds.csv'))
inp.next() # headers
out = csv.reader(open('refunds.completed.csv', 'w+'))
out.writerow('ts', 'id', 'amount', 'code', 'body')
for ts, id, amount in inp:
response = requests.post( url.format(id)
, data={'amount': amount}
, auth=(username, '')
)
out.writerow((ts,id,amount,response.status_code,response.content))
Clean up script to make refunds
Tested against httpbin.org#!/usr/bin/env python -u
from __future__ import absolute_import, division, print_function, unicode_literals
import csv, os, requests
url = 'https://api.balancedpayments.com/debits/{}/refunds'
username = os.environ['BALANCED_API_USER']
inp = csv.reader(open('refunds.csv'))
inp.next() # headers
out = csv.writer(open('refunds.completed.csv', 'w+'))
out.writerow(('ts', 'id', 'amount', 'code', 'body'))
for ts, id, amount in inp:
response = requests.post( url.format(id)
, data={'amount': amount}
, auth=(username, '')
)
out.writerow((ts,id,amount,response.status_code,response.content))
|
<commit_before>#!/usr/bin/env python -u
from __future__ import absolute_import, division, print_function, unicode_literals
import csv, os, requests
url = 'https://api.balancedpayments.com/debits/{}/refunds'
username = os.environ['BALANCED_API_USER']
inp = csv.reader(open('refunds.csv'))
inp.next() # headers
out = csv.reader(open('refunds.completed.csv', 'w+'))
out.writerow('ts', 'id', 'amount', 'code', 'body')
for ts, id, amount in inp:
response = requests.post( url.format(id)
, data={'amount': amount}
, auth=(username, '')
)
out.writerow((ts,id,amount,response.status_code,response.content))
<commit_msg>Clean up script to make refunds
Tested against httpbin.org<commit_after>#!/usr/bin/env python -u
from __future__ import absolute_import, division, print_function, unicode_literals
import csv, os, requests
url = 'https://api.balancedpayments.com/debits/{}/refunds'
username = os.environ['BALANCED_API_USER']
inp = csv.reader(open('refunds.csv'))
inp.next() # headers
out = csv.writer(open('refunds.completed.csv', 'w+'))
out.writerow(('ts', 'id', 'amount', 'code', 'body'))
for ts, id, amount in inp:
response = requests.post( url.format(id)
, data={'amount': amount}
, auth=(username, '')
)
out.writerow((ts,id,amount,response.status_code,response.content))
|
715987e85b61807a7ba5a3ae8ead8a44fff425cb
|
src/sentry/tasks/base.py
|
src/sentry/tasks/base.py
|
"""
sentry.tasks.base
~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
from celery.task import current
from functools import wraps
from sentry.celery import app
from sentry.utils import metrics
def instrumented_task(name, stat_suffix=None, **kwargs):
def wrapped(func):
@wraps(func)
def _wrapped(*args, **kwargs):
key = 'jobs.duration'
if stat_suffix:
instance = '{}.{}'.format(name, stat_suffix(*args, **kwargs))
else:
instance = name
with metrics.timer(key, instance=instance):
result = func(*args, **kwargs)
return result
return app.task(name=name, **kwargs)(_wrapped)
return wrapped
def retry(func):
@wraps(func)
def wrapped(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as exc:
current.retry(exc=exc)
return wrapped
|
"""
sentry.tasks.base
~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
from celery.task import current
from raven.contrib.django.models import client as Raven
from functools import wraps
from sentry.celery import app
from sentry.utils import metrics
def instrumented_task(name, stat_suffix=None, **kwargs):
def wrapped(func):
@wraps(func)
def _wrapped(*args, **kwargs):
key = 'jobs.duration'
if stat_suffix:
instance = '{}.{}'.format(name, stat_suffix(*args, **kwargs))
else:
instance = name
with metrics.timer(key, instance=instance):
try:
result = func(*args, **kwargs)
finally:
Raven.context.clear()
return result
return app.task(name=name, **kwargs)(_wrapped)
return wrapped
def retry(func):
@wraps(func)
def wrapped(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as exc:
current.retry(exc=exc)
return wrapped
|
Clear context for celery tasks
|
Clear context for celery tasks
|
Python
|
bsd-3-clause
|
jean/sentry,ifduyue/sentry,mitsuhiko/sentry,gencer/sentry,mvaled/sentry,jean/sentry,zenefits/sentry,alexm92/sentry,looker/sentry,fotinakis/sentry,jean/sentry,beeftornado/sentry,beeftornado/sentry,looker/sentry,daevaorn/sentry,JamesMura/sentry,alexm92/sentry,JackDanger/sentry,ifduyue/sentry,JackDanger/sentry,looker/sentry,JamesMura/sentry,BuildingLink/sentry,JamesMura/sentry,looker/sentry,ifduyue/sentry,gencer/sentry,mvaled/sentry,nicholasserra/sentry,mvaled/sentry,BuildingLink/sentry,ifduyue/sentry,BuildingLink/sentry,gencer/sentry,zenefits/sentry,BuildingLink/sentry,daevaorn/sentry,zenefits/sentry,daevaorn/sentry,zenefits/sentry,daevaorn/sentry,fotinakis/sentry,alexm92/sentry,jean/sentry,JamesMura/sentry,JackDanger/sentry,nicholasserra/sentry,zenefits/sentry,ifduyue/sentry,gencer/sentry,fotinakis/sentry,JamesMura/sentry,mvaled/sentry,mvaled/sentry,nicholasserra/sentry,mvaled/sentry,BuildingLink/sentry,gencer/sentry,fotinakis/sentry,beeftornado/sentry,looker/sentry,jean/sentry,mitsuhiko/sentry
|
"""
sentry.tasks.base
~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
from celery.task import current
from functools import wraps
from sentry.celery import app
from sentry.utils import metrics
def instrumented_task(name, stat_suffix=None, **kwargs):
def wrapped(func):
@wraps(func)
def _wrapped(*args, **kwargs):
key = 'jobs.duration'
if stat_suffix:
instance = '{}.{}'.format(name, stat_suffix(*args, **kwargs))
else:
instance = name
with metrics.timer(key, instance=instance):
result = func(*args, **kwargs)
return result
return app.task(name=name, **kwargs)(_wrapped)
return wrapped
def retry(func):
@wraps(func)
def wrapped(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as exc:
current.retry(exc=exc)
return wrapped
Clear context for celery tasks
|
"""
sentry.tasks.base
~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
from celery.task import current
from raven.contrib.django.models import client as Raven
from functools import wraps
from sentry.celery import app
from sentry.utils import metrics
def instrumented_task(name, stat_suffix=None, **kwargs):
def wrapped(func):
@wraps(func)
def _wrapped(*args, **kwargs):
key = 'jobs.duration'
if stat_suffix:
instance = '{}.{}'.format(name, stat_suffix(*args, **kwargs))
else:
instance = name
with metrics.timer(key, instance=instance):
try:
result = func(*args, **kwargs)
finally:
Raven.context.clear()
return result
return app.task(name=name, **kwargs)(_wrapped)
return wrapped
def retry(func):
@wraps(func)
def wrapped(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as exc:
current.retry(exc=exc)
return wrapped
|
<commit_before>"""
sentry.tasks.base
~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
from celery.task import current
from functools import wraps
from sentry.celery import app
from sentry.utils import metrics
def instrumented_task(name, stat_suffix=None, **kwargs):
def wrapped(func):
@wraps(func)
def _wrapped(*args, **kwargs):
key = 'jobs.duration'
if stat_suffix:
instance = '{}.{}'.format(name, stat_suffix(*args, **kwargs))
else:
instance = name
with metrics.timer(key, instance=instance):
result = func(*args, **kwargs)
return result
return app.task(name=name, **kwargs)(_wrapped)
return wrapped
def retry(func):
@wraps(func)
def wrapped(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as exc:
current.retry(exc=exc)
return wrapped
<commit_msg>Clear context for celery tasks<commit_after>
|
"""
sentry.tasks.base
~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
from celery.task import current
from raven.contrib.django.models import client as Raven
from functools import wraps
from sentry.celery import app
from sentry.utils import metrics
def instrumented_task(name, stat_suffix=None, **kwargs):
def wrapped(func):
@wraps(func)
def _wrapped(*args, **kwargs):
key = 'jobs.duration'
if stat_suffix:
instance = '{}.{}'.format(name, stat_suffix(*args, **kwargs))
else:
instance = name
with metrics.timer(key, instance=instance):
try:
result = func(*args, **kwargs)
finally:
Raven.context.clear()
return result
return app.task(name=name, **kwargs)(_wrapped)
return wrapped
def retry(func):
@wraps(func)
def wrapped(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as exc:
current.retry(exc=exc)
return wrapped
|
"""
sentry.tasks.base
~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
from celery.task import current
from functools import wraps
from sentry.celery import app
from sentry.utils import metrics
def instrumented_task(name, stat_suffix=None, **kwargs):
def wrapped(func):
@wraps(func)
def _wrapped(*args, **kwargs):
key = 'jobs.duration'
if stat_suffix:
instance = '{}.{}'.format(name, stat_suffix(*args, **kwargs))
else:
instance = name
with metrics.timer(key, instance=instance):
result = func(*args, **kwargs)
return result
return app.task(name=name, **kwargs)(_wrapped)
return wrapped
def retry(func):
@wraps(func)
def wrapped(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as exc:
current.retry(exc=exc)
return wrapped
Clear context for celery tasks"""
sentry.tasks.base
~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
from celery.task import current
from raven.contrib.django.models import client as Raven
from functools import wraps
from sentry.celery import app
from sentry.utils import metrics
def instrumented_task(name, stat_suffix=None, **kwargs):
def wrapped(func):
@wraps(func)
def _wrapped(*args, **kwargs):
key = 'jobs.duration'
if stat_suffix:
instance = '{}.{}'.format(name, stat_suffix(*args, **kwargs))
else:
instance = name
with metrics.timer(key, instance=instance):
try:
result = func(*args, **kwargs)
finally:
Raven.context.clear()
return result
return app.task(name=name, **kwargs)(_wrapped)
return wrapped
def retry(func):
@wraps(func)
def wrapped(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as exc:
current.retry(exc=exc)
return wrapped
|
<commit_before>"""
sentry.tasks.base
~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
from celery.task import current
from functools import wraps
from sentry.celery import app
from sentry.utils import metrics
def instrumented_task(name, stat_suffix=None, **kwargs):
def wrapped(func):
@wraps(func)
def _wrapped(*args, **kwargs):
key = 'jobs.duration'
if stat_suffix:
instance = '{}.{}'.format(name, stat_suffix(*args, **kwargs))
else:
instance = name
with metrics.timer(key, instance=instance):
result = func(*args, **kwargs)
return result
return app.task(name=name, **kwargs)(_wrapped)
return wrapped
def retry(func):
@wraps(func)
def wrapped(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as exc:
current.retry(exc=exc)
return wrapped
<commit_msg>Clear context for celery tasks<commit_after>"""
sentry.tasks.base
~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
from celery.task import current
from raven.contrib.django.models import client as Raven
from functools import wraps
from sentry.celery import app
from sentry.utils import metrics
def instrumented_task(name, stat_suffix=None, **kwargs):
def wrapped(func):
@wraps(func)
def _wrapped(*args, **kwargs):
key = 'jobs.duration'
if stat_suffix:
instance = '{}.{}'.format(name, stat_suffix(*args, **kwargs))
else:
instance = name
with metrics.timer(key, instance=instance):
try:
result = func(*args, **kwargs)
finally:
Raven.context.clear()
return result
return app.task(name=name, **kwargs)(_wrapped)
return wrapped
def retry(func):
@wraps(func)
def wrapped(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as exc:
current.retry(exc=exc)
return wrapped
|
ac11d7e7f90a2ee6a240be5fd95093f98c7d42dc
|
db/create_db.py
|
db/create_db.py
|
from models import Base, engine, MetricType
from sqlalchemy.orm import Session
import uuid
import os
# Create all tables in the engine. This is equivalent to "Create Table"
# statements in raw SQL.
Base.metadata.create_all(engine)
session = Session(engine)
def initialize_metric_types():
metric_types = [None] * 2
metric_types[0] = MetricType()
metric_types[0].id = str(uuid.uuid4())
metric_types[0].name = 'Temperature'
metric_types[0].min_value = -50.0
metric_types[0].max_value = 50.0
metric_types[0].unit = 'C'
metric_types[1] = MetricType()
metric_types[1].id = str(uuid.uuid4())
metric_types[1].name = 'Humidity'
metric_types[1].min_value = 0.0
metric_types[1].max_value = 100.0
metric_types[1].unit = '%'
session.add_all(metric_types)
session.commit()
try:
os.remove('station_db.db')
except Exception as ex:
pass
initialize_metric_types()
|
from models import Base, engine, MetricType
from sqlalchemy.orm import Session
import uuid
import os
try:
os.remove('station_db.db')
except Exception as ex:
pass
# Create all tables in the engine. This is equivalent to "Create Table"
# statements in raw SQL.
Base.metadata.create_all(engine)
session = Session(engine)
def initialize_metric_types():
metric_types = [None] * 2
metric_types[0] = MetricType()
metric_types[0].id = str(uuid.uuid4())
metric_types[0].name = 'Temperature'
metric_types[0].min_value = -50.0
metric_types[0].max_value = 50.0
metric_types[0].unit = 'C'
metric_types[1] = MetricType()
metric_types[1].id = str(uuid.uuid4())
metric_types[1].name = 'Humidity'
metric_types[1].min_value = 0.0
metric_types[1].max_value = 100.0
metric_types[1].unit = '%'
session.add_all(metric_types)
session.commit()
initialize_metric_types()
|
Fix for lack of file.
|
Fix for lack of file.
Signed-off-by: Maciej Szankin <[email protected]>
|
Python
|
mit
|
joannarozes/ddb,joannarozes/ddb,joannarozes/ddb,joannarozes/ddb
|
from models import Base, engine, MetricType
from sqlalchemy.orm import Session
import uuid
import os
# Create all tables in the engine. This is equivalent to "Create Table"
# statements in raw SQL.
Base.metadata.create_all(engine)
session = Session(engine)
def initialize_metric_types():
metric_types = [None] * 2
metric_types[0] = MetricType()
metric_types[0].id = str(uuid.uuid4())
metric_types[0].name = 'Temperature'
metric_types[0].min_value = -50.0
metric_types[0].max_value = 50.0
metric_types[0].unit = 'C'
metric_types[1] = MetricType()
metric_types[1].id = str(uuid.uuid4())
metric_types[1].name = 'Humidity'
metric_types[1].min_value = 0.0
metric_types[1].max_value = 100.0
metric_types[1].unit = '%'
session.add_all(metric_types)
session.commit()
try:
os.remove('station_db.db')
except Exception as ex:
pass
initialize_metric_types()
Fix for lack of file.
Signed-off-by: Maciej Szankin <[email protected]>
|
from models import Base, engine, MetricType
from sqlalchemy.orm import Session
import uuid
import os
try:
os.remove('station_db.db')
except Exception as ex:
pass
# Create all tables in the engine. This is equivalent to "Create Table"
# statements in raw SQL.
Base.metadata.create_all(engine)
session = Session(engine)
def initialize_metric_types():
metric_types = [None] * 2
metric_types[0] = MetricType()
metric_types[0].id = str(uuid.uuid4())
metric_types[0].name = 'Temperature'
metric_types[0].min_value = -50.0
metric_types[0].max_value = 50.0
metric_types[0].unit = 'C'
metric_types[1] = MetricType()
metric_types[1].id = str(uuid.uuid4())
metric_types[1].name = 'Humidity'
metric_types[1].min_value = 0.0
metric_types[1].max_value = 100.0
metric_types[1].unit = '%'
session.add_all(metric_types)
session.commit()
initialize_metric_types()
|
<commit_before>from models import Base, engine, MetricType
from sqlalchemy.orm import Session
import uuid
import os
# Create all tables in the engine. This is equivalent to "Create Table"
# statements in raw SQL.
Base.metadata.create_all(engine)
session = Session(engine)
def initialize_metric_types():
metric_types = [None] * 2
metric_types[0] = MetricType()
metric_types[0].id = str(uuid.uuid4())
metric_types[0].name = 'Temperature'
metric_types[0].min_value = -50.0
metric_types[0].max_value = 50.0
metric_types[0].unit = 'C'
metric_types[1] = MetricType()
metric_types[1].id = str(uuid.uuid4())
metric_types[1].name = 'Humidity'
metric_types[1].min_value = 0.0
metric_types[1].max_value = 100.0
metric_types[1].unit = '%'
session.add_all(metric_types)
session.commit()
try:
os.remove('station_db.db')
except Exception as ex:
pass
initialize_metric_types()
<commit_msg>Fix for lack of file.
Signed-off-by: Maciej Szankin <[email protected]><commit_after>
|
from models import Base, engine, MetricType
from sqlalchemy.orm import Session
import uuid
import os
try:
os.remove('station_db.db')
except Exception as ex:
pass
# Create all tables in the engine. This is equivalent to "Create Table"
# statements in raw SQL.
Base.metadata.create_all(engine)
session = Session(engine)
def initialize_metric_types():
metric_types = [None] * 2
metric_types[0] = MetricType()
metric_types[0].id = str(uuid.uuid4())
metric_types[0].name = 'Temperature'
metric_types[0].min_value = -50.0
metric_types[0].max_value = 50.0
metric_types[0].unit = 'C'
metric_types[1] = MetricType()
metric_types[1].id = str(uuid.uuid4())
metric_types[1].name = 'Humidity'
metric_types[1].min_value = 0.0
metric_types[1].max_value = 100.0
metric_types[1].unit = '%'
session.add_all(metric_types)
session.commit()
initialize_metric_types()
|
from models import Base, engine, MetricType
from sqlalchemy.orm import Session
import uuid
import os
# Create all tables in the engine. This is equivalent to "Create Table"
# statements in raw SQL.
Base.metadata.create_all(engine)
session = Session(engine)
def initialize_metric_types():
metric_types = [None] * 2
metric_types[0] = MetricType()
metric_types[0].id = str(uuid.uuid4())
metric_types[0].name = 'Temperature'
metric_types[0].min_value = -50.0
metric_types[0].max_value = 50.0
metric_types[0].unit = 'C'
metric_types[1] = MetricType()
metric_types[1].id = str(uuid.uuid4())
metric_types[1].name = 'Humidity'
metric_types[1].min_value = 0.0
metric_types[1].max_value = 100.0
metric_types[1].unit = '%'
session.add_all(metric_types)
session.commit()
try:
os.remove('station_db.db')
except Exception as ex:
pass
initialize_metric_types()
Fix for lack of file.
Signed-off-by: Maciej Szankin <[email protected]>from models import Base, engine, MetricType
from sqlalchemy.orm import Session
import uuid
import os
try:
os.remove('station_db.db')
except Exception as ex:
pass
# Create all tables in the engine. This is equivalent to "Create Table"
# statements in raw SQL.
Base.metadata.create_all(engine)
session = Session(engine)
def initialize_metric_types():
metric_types = [None] * 2
metric_types[0] = MetricType()
metric_types[0].id = str(uuid.uuid4())
metric_types[0].name = 'Temperature'
metric_types[0].min_value = -50.0
metric_types[0].max_value = 50.0
metric_types[0].unit = 'C'
metric_types[1] = MetricType()
metric_types[1].id = str(uuid.uuid4())
metric_types[1].name = 'Humidity'
metric_types[1].min_value = 0.0
metric_types[1].max_value = 100.0
metric_types[1].unit = '%'
session.add_all(metric_types)
session.commit()
initialize_metric_types()
|
<commit_before>from models import Base, engine, MetricType
from sqlalchemy.orm import Session
import uuid
import os
# Create all tables in the engine. This is equivalent to "Create Table"
# statements in raw SQL.
Base.metadata.create_all(engine)
session = Session(engine)
def initialize_metric_types():
metric_types = [None] * 2
metric_types[0] = MetricType()
metric_types[0].id = str(uuid.uuid4())
metric_types[0].name = 'Temperature'
metric_types[0].min_value = -50.0
metric_types[0].max_value = 50.0
metric_types[0].unit = 'C'
metric_types[1] = MetricType()
metric_types[1].id = str(uuid.uuid4())
metric_types[1].name = 'Humidity'
metric_types[1].min_value = 0.0
metric_types[1].max_value = 100.0
metric_types[1].unit = '%'
session.add_all(metric_types)
session.commit()
try:
os.remove('station_db.db')
except Exception as ex:
pass
initialize_metric_types()
<commit_msg>Fix for lack of file.
Signed-off-by: Maciej Szankin <[email protected]><commit_after>from models import Base, engine, MetricType
from sqlalchemy.orm import Session
import uuid
import os
try:
os.remove('station_db.db')
except Exception as ex:
pass
# Create all tables in the engine. This is equivalent to "Create Table"
# statements in raw SQL.
Base.metadata.create_all(engine)
session = Session(engine)
def initialize_metric_types():
metric_types = [None] * 2
metric_types[0] = MetricType()
metric_types[0].id = str(uuid.uuid4())
metric_types[0].name = 'Temperature'
metric_types[0].min_value = -50.0
metric_types[0].max_value = 50.0
metric_types[0].unit = 'C'
metric_types[1] = MetricType()
metric_types[1].id = str(uuid.uuid4())
metric_types[1].name = 'Humidity'
metric_types[1].min_value = 0.0
metric_types[1].max_value = 100.0
metric_types[1].unit = '%'
session.add_all(metric_types)
session.commit()
initialize_metric_types()
|
6dbb40b2ca23d90b439fb08a2931b6a43b6c9e61
|
update.py
|
update.py
|
import os
os.system("git add *")
os.system("git commit -m 'first commit'")
os.system("git push origin master")
|
import os
print "Enter commit message:"
commit = raw_input();
os.system("git add *")
os.system("git commit -m '"+commit+"'")
os.system("git push origin master")
|
Set up git push script. ;)
|
Set up git push script. ;)
|
Python
|
mit
|
connornishijima/electropi2,connornishijima/electropi2
|
import os
os.system("git add *")
os.system("git commit -m 'first commit'")
os.system("git push origin master")
Set up git push script. ;)
|
import os
print "Enter commit message:"
commit = raw_input();
os.system("git add *")
os.system("git commit -m '"+commit+"'")
os.system("git push origin master")
|
<commit_before>import os
os.system("git add *")
os.system("git commit -m 'first commit'")
os.system("git push origin master")
<commit_msg>Set up git push script. ;)<commit_after>
|
import os
print "Enter commit message:"
commit = raw_input();
os.system("git add *")
os.system("git commit -m '"+commit+"'")
os.system("git push origin master")
|
import os
os.system("git add *")
os.system("git commit -m 'first commit'")
os.system("git push origin master")
Set up git push script. ;)import os
print "Enter commit message:"
commit = raw_input();
os.system("git add *")
os.system("git commit -m '"+commit+"'")
os.system("git push origin master")
|
<commit_before>import os
os.system("git add *")
os.system("git commit -m 'first commit'")
os.system("git push origin master")
<commit_msg>Set up git push script. ;)<commit_after>import os
print "Enter commit message:"
commit = raw_input();
os.system("git add *")
os.system("git commit -m '"+commit+"'")
os.system("git push origin master")
|
62e4f4b8262c78a20c26de7b9b23a89d2c2e1e90
|
examples/wsgi_app.py
|
examples/wsgi_app.py
|
import guv
guv.monkey_patch()
import guv.wsgi
import logger
logger.configure()
def app(environ, start_response):
status = '200 OK'
output = [b'Hello World!']
content_length = str(len(b''.join(output)))
response_headers = [('Content-type', 'text/plain'),
('Content-Length', content_length)]
start_response(status, response_headers)
return output
if __name__ == '__main__':
server_sock = guv.listen(('0.0.0.0', 8001))
guv.wsgi.serve(server_sock, app)
|
import guv
guv.monkey_patch()
import guv.wsgi
import logger
logger.configure()
def app(environ, start_response):
"""
This is very basic WSGI app useful for testing the performance of guv and guv.wsgi without
the overhead of a framework such as Flask. However, it can just as easily be any other WSGI app
callable object, such as a Flask or Bottle app.
"""
status = '200 OK'
output = [b'Hello World!']
content_length = str(len(b''.join(output)))
response_headers = [('Content-type', 'text/plain'),
('Content-Length', content_length)]
start_response(status, response_headers)
return output
if __name__ == '__main__':
server_sock = guv.listen(('0.0.0.0', 8001))
guv.wsgi.serve(server_sock, app)
|
Add docstring to WSGI example
|
Add docstring to WSGI example
|
Python
|
mit
|
veegee/guv,veegee/guv
|
import guv
guv.monkey_patch()
import guv.wsgi
import logger
logger.configure()
def app(environ, start_response):
status = '200 OK'
output = [b'Hello World!']
content_length = str(len(b''.join(output)))
response_headers = [('Content-type', 'text/plain'),
('Content-Length', content_length)]
start_response(status, response_headers)
return output
if __name__ == '__main__':
server_sock = guv.listen(('0.0.0.0', 8001))
guv.wsgi.serve(server_sock, app)
Add docstring to WSGI example
|
import guv
guv.monkey_patch()
import guv.wsgi
import logger
logger.configure()
def app(environ, start_response):
"""
This is very basic WSGI app useful for testing the performance of guv and guv.wsgi without
the overhead of a framework such as Flask. However, it can just as easily be any other WSGI app
callable object, such as a Flask or Bottle app.
"""
status = '200 OK'
output = [b'Hello World!']
content_length = str(len(b''.join(output)))
response_headers = [('Content-type', 'text/plain'),
('Content-Length', content_length)]
start_response(status, response_headers)
return output
if __name__ == '__main__':
server_sock = guv.listen(('0.0.0.0', 8001))
guv.wsgi.serve(server_sock, app)
|
<commit_before>import guv
guv.monkey_patch()
import guv.wsgi
import logger
logger.configure()
def app(environ, start_response):
status = '200 OK'
output = [b'Hello World!']
content_length = str(len(b''.join(output)))
response_headers = [('Content-type', 'text/plain'),
('Content-Length', content_length)]
start_response(status, response_headers)
return output
if __name__ == '__main__':
server_sock = guv.listen(('0.0.0.0', 8001))
guv.wsgi.serve(server_sock, app)
<commit_msg>Add docstring to WSGI example<commit_after>
|
import guv
guv.monkey_patch()
import guv.wsgi
import logger
logger.configure()
def app(environ, start_response):
"""
This is very basic WSGI app useful for testing the performance of guv and guv.wsgi without
the overhead of a framework such as Flask. However, it can just as easily be any other WSGI app
callable object, such as a Flask or Bottle app.
"""
status = '200 OK'
output = [b'Hello World!']
content_length = str(len(b''.join(output)))
response_headers = [('Content-type', 'text/plain'),
('Content-Length', content_length)]
start_response(status, response_headers)
return output
if __name__ == '__main__':
server_sock = guv.listen(('0.0.0.0', 8001))
guv.wsgi.serve(server_sock, app)
|
import guv
guv.monkey_patch()
import guv.wsgi
import logger
logger.configure()
def app(environ, start_response):
status = '200 OK'
output = [b'Hello World!']
content_length = str(len(b''.join(output)))
response_headers = [('Content-type', 'text/plain'),
('Content-Length', content_length)]
start_response(status, response_headers)
return output
if __name__ == '__main__':
server_sock = guv.listen(('0.0.0.0', 8001))
guv.wsgi.serve(server_sock, app)
Add docstring to WSGI exampleimport guv
guv.monkey_patch()
import guv.wsgi
import logger
logger.configure()
def app(environ, start_response):
"""
This is very basic WSGI app useful for testing the performance of guv and guv.wsgi without
the overhead of a framework such as Flask. However, it can just as easily be any other WSGI app
callable object, such as a Flask or Bottle app.
"""
status = '200 OK'
output = [b'Hello World!']
content_length = str(len(b''.join(output)))
response_headers = [('Content-type', 'text/plain'),
('Content-Length', content_length)]
start_response(status, response_headers)
return output
if __name__ == '__main__':
server_sock = guv.listen(('0.0.0.0', 8001))
guv.wsgi.serve(server_sock, app)
|
<commit_before>import guv
guv.monkey_patch()
import guv.wsgi
import logger
logger.configure()
def app(environ, start_response):
status = '200 OK'
output = [b'Hello World!']
content_length = str(len(b''.join(output)))
response_headers = [('Content-type', 'text/plain'),
('Content-Length', content_length)]
start_response(status, response_headers)
return output
if __name__ == '__main__':
server_sock = guv.listen(('0.0.0.0', 8001))
guv.wsgi.serve(server_sock, app)
<commit_msg>Add docstring to WSGI example<commit_after>import guv
guv.monkey_patch()
import guv.wsgi
import logger
logger.configure()
def app(environ, start_response):
"""
This is very basic WSGI app useful for testing the performance of guv and guv.wsgi without
the overhead of a framework such as Flask. However, it can just as easily be any other WSGI app
callable object, such as a Flask or Bottle app.
"""
status = '200 OK'
output = [b'Hello World!']
content_length = str(len(b''.join(output)))
response_headers = [('Content-type', 'text/plain'),
('Content-Length', content_length)]
start_response(status, response_headers)
return output
if __name__ == '__main__':
server_sock = guv.listen(('0.0.0.0', 8001))
guv.wsgi.serve(server_sock, app)
|
1ec9e85604eb8c69771a06d69681e7d7dbb00de7
|
node/delta.py
|
node/delta.py
|
#!/usr/bin/env python
import datetime
from nodes import Node
class Delta(Node):
char = "$"
args = 1
results = 1
@Node.test_func([[1, 2, 3, 5]], [[1, 1, 2]])
def delta(self, seq: Node.sequence):
"""Return the difference in terms in the input sequence.
Returns a sequence of the same type, one shorter."""
deltas = []
for i in range(len(seq)-1):
deltas.append(seq[i+1]-seq[i])
return[type(seq)(deltas)]
def float(self, inp:Node.number):
"""float(inp)"""
return float(inp)
@Node.test_func(["HELLO"], [0])
@Node.test_func(["world"], [1])
@Node.test_func(["@"], [0])
def is_lower(self, string:str):
"""Is a string lower case?"""
return int(string.islower())
def get_day_of_week(self, time: Node.clock):
new_time = datetime.datetime(*time.time_obj[:7])
return new_time.weekday()
|
#!/usr/bin/env python
import datetime
from nodes import Node
class Delta(Node):
char = "$"
args = 1
results = 1
contents = ["PADDING",
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"]
@Node.test_func([[1, 2, 3, 5]], [[1, 1, 2]])
def delta(self, seq: Node.sequence):
"""Return the difference in terms in the input sequence.
Returns a sequence of the same type, one shorter."""
deltas = []
for i in range(len(seq)-1):
deltas.append(seq[i+1]-seq[i])
return[type(seq)(deltas)]
def float(self, inp:Node.number):
"""float(inp)"""
return float(inp)
@Node.test_func(["HELLO"], [0])
@Node.test_func(["world"], [1])
@Node.test_func(["@"], [0])
def is_lower(self, string:str):
"""Is a string lower case?"""
return int(string.islower())
def get_day_of_week(self, time: Node.clock):
new_time = datetime.datetime(*time.time_obj[:7])
return new_time.weekday()
|
Update month names of year
|
Update month names of year
|
Python
|
mit
|
muddyfish/PYKE,muddyfish/PYKE
|
#!/usr/bin/env python
import datetime
from nodes import Node
class Delta(Node):
char = "$"
args = 1
results = 1
@Node.test_func([[1, 2, 3, 5]], [[1, 1, 2]])
def delta(self, seq: Node.sequence):
"""Return the difference in terms in the input sequence.
Returns a sequence of the same type, one shorter."""
deltas = []
for i in range(len(seq)-1):
deltas.append(seq[i+1]-seq[i])
return[type(seq)(deltas)]
def float(self, inp:Node.number):
"""float(inp)"""
return float(inp)
@Node.test_func(["HELLO"], [0])
@Node.test_func(["world"], [1])
@Node.test_func(["@"], [0])
def is_lower(self, string:str):
"""Is a string lower case?"""
return int(string.islower())
def get_day_of_week(self, time: Node.clock):
new_time = datetime.datetime(*time.time_obj[:7])
return new_time.weekday()
Update month names of year
|
#!/usr/bin/env python
import datetime
from nodes import Node
class Delta(Node):
char = "$"
args = 1
results = 1
contents = ["PADDING",
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"]
@Node.test_func([[1, 2, 3, 5]], [[1, 1, 2]])
def delta(self, seq: Node.sequence):
"""Return the difference in terms in the input sequence.
Returns a sequence of the same type, one shorter."""
deltas = []
for i in range(len(seq)-1):
deltas.append(seq[i+1]-seq[i])
return[type(seq)(deltas)]
def float(self, inp:Node.number):
"""float(inp)"""
return float(inp)
@Node.test_func(["HELLO"], [0])
@Node.test_func(["world"], [1])
@Node.test_func(["@"], [0])
def is_lower(self, string:str):
"""Is a string lower case?"""
return int(string.islower())
def get_day_of_week(self, time: Node.clock):
new_time = datetime.datetime(*time.time_obj[:7])
return new_time.weekday()
|
<commit_before>#!/usr/bin/env python
import datetime
from nodes import Node
class Delta(Node):
char = "$"
args = 1
results = 1
@Node.test_func([[1, 2, 3, 5]], [[1, 1, 2]])
def delta(self, seq: Node.sequence):
"""Return the difference in terms in the input sequence.
Returns a sequence of the same type, one shorter."""
deltas = []
for i in range(len(seq)-1):
deltas.append(seq[i+1]-seq[i])
return[type(seq)(deltas)]
def float(self, inp:Node.number):
"""float(inp)"""
return float(inp)
@Node.test_func(["HELLO"], [0])
@Node.test_func(["world"], [1])
@Node.test_func(["@"], [0])
def is_lower(self, string:str):
"""Is a string lower case?"""
return int(string.islower())
def get_day_of_week(self, time: Node.clock):
new_time = datetime.datetime(*time.time_obj[:7])
return new_time.weekday()
<commit_msg>Update month names of year<commit_after>
|
#!/usr/bin/env python
import datetime
from nodes import Node
class Delta(Node):
char = "$"
args = 1
results = 1
contents = ["PADDING",
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"]
@Node.test_func([[1, 2, 3, 5]], [[1, 1, 2]])
def delta(self, seq: Node.sequence):
"""Return the difference in terms in the input sequence.
Returns a sequence of the same type, one shorter."""
deltas = []
for i in range(len(seq)-1):
deltas.append(seq[i+1]-seq[i])
return[type(seq)(deltas)]
def float(self, inp:Node.number):
"""float(inp)"""
return float(inp)
@Node.test_func(["HELLO"], [0])
@Node.test_func(["world"], [1])
@Node.test_func(["@"], [0])
def is_lower(self, string:str):
"""Is a string lower case?"""
return int(string.islower())
def get_day_of_week(self, time: Node.clock):
new_time = datetime.datetime(*time.time_obj[:7])
return new_time.weekday()
|
#!/usr/bin/env python
import datetime
from nodes import Node
class Delta(Node):
char = "$"
args = 1
results = 1
@Node.test_func([[1, 2, 3, 5]], [[1, 1, 2]])
def delta(self, seq: Node.sequence):
"""Return the difference in terms in the input sequence.
Returns a sequence of the same type, one shorter."""
deltas = []
for i in range(len(seq)-1):
deltas.append(seq[i+1]-seq[i])
return[type(seq)(deltas)]
def float(self, inp:Node.number):
"""float(inp)"""
return float(inp)
@Node.test_func(["HELLO"], [0])
@Node.test_func(["world"], [1])
@Node.test_func(["@"], [0])
def is_lower(self, string:str):
"""Is a string lower case?"""
return int(string.islower())
def get_day_of_week(self, time: Node.clock):
new_time = datetime.datetime(*time.time_obj[:7])
return new_time.weekday()
Update month names of year#!/usr/bin/env python
import datetime
from nodes import Node
class Delta(Node):
char = "$"
args = 1
results = 1
contents = ["PADDING",
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"]
@Node.test_func([[1, 2, 3, 5]], [[1, 1, 2]])
def delta(self, seq: Node.sequence):
"""Return the difference in terms in the input sequence.
Returns a sequence of the same type, one shorter."""
deltas = []
for i in range(len(seq)-1):
deltas.append(seq[i+1]-seq[i])
return[type(seq)(deltas)]
def float(self, inp:Node.number):
"""float(inp)"""
return float(inp)
@Node.test_func(["HELLO"], [0])
@Node.test_func(["world"], [1])
@Node.test_func(["@"], [0])
def is_lower(self, string:str):
"""Is a string lower case?"""
return int(string.islower())
def get_day_of_week(self, time: Node.clock):
new_time = datetime.datetime(*time.time_obj[:7])
return new_time.weekday()
|
<commit_before>#!/usr/bin/env python
import datetime
from nodes import Node
class Delta(Node):
char = "$"
args = 1
results = 1
@Node.test_func([[1, 2, 3, 5]], [[1, 1, 2]])
def delta(self, seq: Node.sequence):
"""Return the difference in terms in the input sequence.
Returns a sequence of the same type, one shorter."""
deltas = []
for i in range(len(seq)-1):
deltas.append(seq[i+1]-seq[i])
return[type(seq)(deltas)]
def float(self, inp:Node.number):
"""float(inp)"""
return float(inp)
@Node.test_func(["HELLO"], [0])
@Node.test_func(["world"], [1])
@Node.test_func(["@"], [0])
def is_lower(self, string:str):
"""Is a string lower case?"""
return int(string.islower())
def get_day_of_week(self, time: Node.clock):
new_time = datetime.datetime(*time.time_obj[:7])
return new_time.weekday()
<commit_msg>Update month names of year<commit_after>#!/usr/bin/env python
import datetime
from nodes import Node
class Delta(Node):
char = "$"
args = 1
results = 1
contents = ["PADDING",
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"]
@Node.test_func([[1, 2, 3, 5]], [[1, 1, 2]])
def delta(self, seq: Node.sequence):
"""Return the difference in terms in the input sequence.
Returns a sequence of the same type, one shorter."""
deltas = []
for i in range(len(seq)-1):
deltas.append(seq[i+1]-seq[i])
return[type(seq)(deltas)]
def float(self, inp:Node.number):
"""float(inp)"""
return float(inp)
@Node.test_func(["HELLO"], [0])
@Node.test_func(["world"], [1])
@Node.test_func(["@"], [0])
def is_lower(self, string:str):
"""Is a string lower case?"""
return int(string.islower())
def get_day_of_week(self, time: Node.clock):
new_time = datetime.datetime(*time.time_obj[:7])
return new_time.weekday()
|
a035798ed00df2483a32e76a913cbc4cc8bf8df2
|
api/middleware.py
|
api/middleware.py
|
class AddResponseHeader:
def process_response(self, req, resp, resource):
resp.set_header('Access-Control-Allow-Origin', 'http://localhost:8000')
components = [AddResponseHeader()]
|
class AddResponseHeader:
def process_response(self, req, resp, resource):
resp.set_header('Access-Control-Allow-Origin', 'http://localhost:8000')
resp.set_header('Access-Control-Allow-Methods', 'GET, POST, PUT')
resp.set_header('Access-Control-Allow-Headers', 'Content-Type')
components = [AddResponseHeader()]
|
Fix API access control headers
|
Fix API access control headers
|
Python
|
mit
|
thepoly/Pipeline,thepoly/Pipeline,thepoly/Pipeline,thepoly/Pipeline,thepoly/Pipeline
|
class AddResponseHeader:
def process_response(self, req, resp, resource):
resp.set_header('Access-Control-Allow-Origin', 'http://localhost:8000')
components = [AddResponseHeader()]
Fix API access control headers
|
class AddResponseHeader:
def process_response(self, req, resp, resource):
resp.set_header('Access-Control-Allow-Origin', 'http://localhost:8000')
resp.set_header('Access-Control-Allow-Methods', 'GET, POST, PUT')
resp.set_header('Access-Control-Allow-Headers', 'Content-Type')
components = [AddResponseHeader()]
|
<commit_before>class AddResponseHeader:
def process_response(self, req, resp, resource):
resp.set_header('Access-Control-Allow-Origin', 'http://localhost:8000')
components = [AddResponseHeader()]
<commit_msg>Fix API access control headers<commit_after>
|
class AddResponseHeader:
def process_response(self, req, resp, resource):
resp.set_header('Access-Control-Allow-Origin', 'http://localhost:8000')
resp.set_header('Access-Control-Allow-Methods', 'GET, POST, PUT')
resp.set_header('Access-Control-Allow-Headers', 'Content-Type')
components = [AddResponseHeader()]
|
class AddResponseHeader:
def process_response(self, req, resp, resource):
resp.set_header('Access-Control-Allow-Origin', 'http://localhost:8000')
components = [AddResponseHeader()]
Fix API access control headersclass AddResponseHeader:
def process_response(self, req, resp, resource):
resp.set_header('Access-Control-Allow-Origin', 'http://localhost:8000')
resp.set_header('Access-Control-Allow-Methods', 'GET, POST, PUT')
resp.set_header('Access-Control-Allow-Headers', 'Content-Type')
components = [AddResponseHeader()]
|
<commit_before>class AddResponseHeader:
def process_response(self, req, resp, resource):
resp.set_header('Access-Control-Allow-Origin', 'http://localhost:8000')
components = [AddResponseHeader()]
<commit_msg>Fix API access control headers<commit_after>class AddResponseHeader:
def process_response(self, req, resp, resource):
resp.set_header('Access-Control-Allow-Origin', 'http://localhost:8000')
resp.set_header('Access-Control-Allow-Methods', 'GET, POST, PUT')
resp.set_header('Access-Control-Allow-Headers', 'Content-Type')
components = [AddResponseHeader()]
|
183bd0005b71a587021c21b095961a0760e12f23
|
swampdragon/file_upload_handler.py
|
swampdragon/file_upload_handler.py
|
from os.path import join
from os import makedirs
from django.conf import settings
def make_file_id(file_data):
return str(abs(hash(file_data)))
def get_file_location(file_name, file_id):
path = join(settings.MEDIA_ROOT, 'tmp')
path = join(path, str(file_id))
try:
makedirs(path)
except:
pass
return join(path, file_name)
def get_file_url(file_name, file_id):
path = join(settings.MEDIA_URL, 'tmp')
path = join(path, str(file_id))
return join(path, file_name)
|
from os.path import join
from os import makedirs
from django.conf import settings
from datetime import datetime
import time
def make_file_id(file_data):
timestamp = datetime.now()
timestamp = time.mktime(timestamp.timetuple()) * 1e3 + timestamp.microsecond / 1e3
timestamp = '{}'.format(timestamp).encode()
return str(abs(hash(file_data + timestamp)))
def get_file_location(file_name, file_id):
path = join(settings.MEDIA_ROOT, 'tmp')
path = join(path, str(file_id))
try:
makedirs(path)
except:
pass
return join(path, file_name)
def get_file_url(file_name, file_id):
path = join(settings.MEDIA_URL, 'tmp')
path = join(path, str(file_id))
return join(path, file_name)
|
Improve the file id hash
|
Improve the file id hash
|
Python
|
bsd-3-clause
|
sahlinet/swampdragon,denizs/swampdragon,sahlinet/swampdragon,aexeagmbh/swampdragon,bastianh/swampdragon,faulkner/swampdragon,faulkner/swampdragon,bastianh/swampdragon,boris-savic/swampdragon,d9pouces/swampdragon,seclinch/swampdragon,aexeagmbh/swampdragon,Manuel4131/swampdragon,seclinch/swampdragon,Manuel4131/swampdragon,michael-k/swampdragon,h-hirokawa/swampdragon,bastianh/swampdragon,jonashagstedt/swampdragon,Manuel4131/swampdragon,denizs/swampdragon,h-hirokawa/swampdragon,seclinch/swampdragon,d9pouces/swampdragon,michael-k/swampdragon,jonashagstedt/swampdragon,faulkner/swampdragon,boris-savic/swampdragon,michael-k/swampdragon,denizs/swampdragon,sahlinet/swampdragon,aexeagmbh/swampdragon,d9pouces/swampdragon,jonashagstedt/swampdragon,boris-savic/swampdragon
|
from os.path import join
from os import makedirs
from django.conf import settings
def make_file_id(file_data):
return str(abs(hash(file_data)))
def get_file_location(file_name, file_id):
path = join(settings.MEDIA_ROOT, 'tmp')
path = join(path, str(file_id))
try:
makedirs(path)
except:
pass
return join(path, file_name)
def get_file_url(file_name, file_id):
path = join(settings.MEDIA_URL, 'tmp')
path = join(path, str(file_id))
return join(path, file_name)
Improve the file id hash
|
from os.path import join
from os import makedirs
from django.conf import settings
from datetime import datetime
import time
def make_file_id(file_data):
timestamp = datetime.now()
timestamp = time.mktime(timestamp.timetuple()) * 1e3 + timestamp.microsecond / 1e3
timestamp = '{}'.format(timestamp).encode()
return str(abs(hash(file_data + timestamp)))
def get_file_location(file_name, file_id):
path = join(settings.MEDIA_ROOT, 'tmp')
path = join(path, str(file_id))
try:
makedirs(path)
except:
pass
return join(path, file_name)
def get_file_url(file_name, file_id):
path = join(settings.MEDIA_URL, 'tmp')
path = join(path, str(file_id))
return join(path, file_name)
|
<commit_before>from os.path import join
from os import makedirs
from django.conf import settings
def make_file_id(file_data):
return str(abs(hash(file_data)))
def get_file_location(file_name, file_id):
path = join(settings.MEDIA_ROOT, 'tmp')
path = join(path, str(file_id))
try:
makedirs(path)
except:
pass
return join(path, file_name)
def get_file_url(file_name, file_id):
path = join(settings.MEDIA_URL, 'tmp')
path = join(path, str(file_id))
return join(path, file_name)
<commit_msg>Improve the file id hash<commit_after>
|
from os.path import join
from os import makedirs
from django.conf import settings
from datetime import datetime
import time
def make_file_id(file_data):
timestamp = datetime.now()
timestamp = time.mktime(timestamp.timetuple()) * 1e3 + timestamp.microsecond / 1e3
timestamp = '{}'.format(timestamp).encode()
return str(abs(hash(file_data + timestamp)))
def get_file_location(file_name, file_id):
path = join(settings.MEDIA_ROOT, 'tmp')
path = join(path, str(file_id))
try:
makedirs(path)
except:
pass
return join(path, file_name)
def get_file_url(file_name, file_id):
path = join(settings.MEDIA_URL, 'tmp')
path = join(path, str(file_id))
return join(path, file_name)
|
from os.path import join
from os import makedirs
from django.conf import settings
def make_file_id(file_data):
return str(abs(hash(file_data)))
def get_file_location(file_name, file_id):
path = join(settings.MEDIA_ROOT, 'tmp')
path = join(path, str(file_id))
try:
makedirs(path)
except:
pass
return join(path, file_name)
def get_file_url(file_name, file_id):
path = join(settings.MEDIA_URL, 'tmp')
path = join(path, str(file_id))
return join(path, file_name)
Improve the file id hashfrom os.path import join
from os import makedirs
from django.conf import settings
from datetime import datetime
import time
def make_file_id(file_data):
timestamp = datetime.now()
timestamp = time.mktime(timestamp.timetuple()) * 1e3 + timestamp.microsecond / 1e3
timestamp = '{}'.format(timestamp).encode()
return str(abs(hash(file_data + timestamp)))
def get_file_location(file_name, file_id):
path = join(settings.MEDIA_ROOT, 'tmp')
path = join(path, str(file_id))
try:
makedirs(path)
except:
pass
return join(path, file_name)
def get_file_url(file_name, file_id):
path = join(settings.MEDIA_URL, 'tmp')
path = join(path, str(file_id))
return join(path, file_name)
|
<commit_before>from os.path import join
from os import makedirs
from django.conf import settings
def make_file_id(file_data):
return str(abs(hash(file_data)))
def get_file_location(file_name, file_id):
path = join(settings.MEDIA_ROOT, 'tmp')
path = join(path, str(file_id))
try:
makedirs(path)
except:
pass
return join(path, file_name)
def get_file_url(file_name, file_id):
path = join(settings.MEDIA_URL, 'tmp')
path = join(path, str(file_id))
return join(path, file_name)
<commit_msg>Improve the file id hash<commit_after>from os.path import join
from os import makedirs
from django.conf import settings
from datetime import datetime
import time
def make_file_id(file_data):
timestamp = datetime.now()
timestamp = time.mktime(timestamp.timetuple()) * 1e3 + timestamp.microsecond / 1e3
timestamp = '{}'.format(timestamp).encode()
return str(abs(hash(file_data + timestamp)))
def get_file_location(file_name, file_id):
path = join(settings.MEDIA_ROOT, 'tmp')
path = join(path, str(file_id))
try:
makedirs(path)
except:
pass
return join(path, file_name)
def get_file_url(file_name, file_id):
path = join(settings.MEDIA_URL, 'tmp')
path = join(path, str(file_id))
return join(path, file_name)
|
16a951a119f37927f4f023051e25968c60d4511a
|
python/crypto-square/crypto_square.py
|
python/crypto-square/crypto_square.py
|
import string
import math
import itertools
class CryptoSquare:
@classmethod
def encode(cls, msg):
if len(cls.normalize(msg)) == 0:
return ''
return ' '.join(cls.transpose_square(cls.squarify(cls.normalize(msg))))
@classmethod
def squarify(cls, msg):
return [msg[i:i + cls.square_size(len(msg))]
for i in range(0, len(msg), cls.square_size(len(msg)))]
@classmethod
def transpose_square(cls, square):
matrix = [list(row) for row in square]
transposed_matrix = cls.transpose_uneven_matrix(matrix)
joined_matrix = [''.join([x for x in row if x is not None]) for row in transposed_matrix]
return joined_matrix
@staticmethod
def normalize(msg):
return ''.join(ch.lower() for ch in msg if ch not in
set(string.punctuation + ' '))
@staticmethod
def square_size(msg_length):
return int(math.ceil(msg_length ** 0.5))
# https://stackoverflow.com/a/4938130/2813210
@staticmethod
def transpose_uneven_matrix(matrix):
return list(itertools.zip_longest(*matrix))
def encode(msg):
return CryptoSquare.encode(msg)
|
import string
import math
import itertools
class CryptoSquare:
@classmethod
def encode(cls, msg):
if len(cls.normalize(msg)) == 0:
return ''
return ' '.join(cls.transpose_square(cls.squarify(cls.normalize(msg))))
@classmethod
def squarify(cls, msg):
return [msg[i:i + cls.square_size(len(msg))]
for i in range(0, len(msg), cls.square_size(len(msg)))]
@classmethod
def transpose_square(cls, square):
matrix = [list(row) for row in square]
transposed_matrix = cls.filter_out_none(cls.transpose_uneven_matrix(matrix))
transposed_square = [''.join(row) for row in transposed_matrix]
return transposed_square
@staticmethod
def normalize(msg):
return ''.join(ch.lower() for ch in msg if ch not in
set(string.punctuation + ' '))
@staticmethod
def square_size(msg_length):
return int(math.ceil(msg_length ** 0.5))
# https://stackoverflow.com/a/4938130/2813210
@staticmethod
def transpose_uneven_matrix(matrix):
return list(itertools.zip_longest(*matrix))
@staticmethod
def filter_out_none(matrix):
return [[val for val in row if val is not None] for row in matrix]
def encode(msg):
return CryptoSquare.encode(msg)
|
Refactor filter out none to method
|
Refactor filter out none to method
|
Python
|
mit
|
rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism
|
import string
import math
import itertools
class CryptoSquare:
@classmethod
def encode(cls, msg):
if len(cls.normalize(msg)) == 0:
return ''
return ' '.join(cls.transpose_square(cls.squarify(cls.normalize(msg))))
@classmethod
def squarify(cls, msg):
return [msg[i:i + cls.square_size(len(msg))]
for i in range(0, len(msg), cls.square_size(len(msg)))]
@classmethod
def transpose_square(cls, square):
matrix = [list(row) for row in square]
transposed_matrix = cls.transpose_uneven_matrix(matrix)
joined_matrix = [''.join([x for x in row if x is not None]) for row in transposed_matrix]
return joined_matrix
@staticmethod
def normalize(msg):
return ''.join(ch.lower() for ch in msg if ch not in
set(string.punctuation + ' '))
@staticmethod
def square_size(msg_length):
return int(math.ceil(msg_length ** 0.5))
# https://stackoverflow.com/a/4938130/2813210
@staticmethod
def transpose_uneven_matrix(matrix):
return list(itertools.zip_longest(*matrix))
def encode(msg):
return CryptoSquare.encode(msg)
Refactor filter out none to method
|
import string
import math
import itertools
class CryptoSquare:
@classmethod
def encode(cls, msg):
if len(cls.normalize(msg)) == 0:
return ''
return ' '.join(cls.transpose_square(cls.squarify(cls.normalize(msg))))
@classmethod
def squarify(cls, msg):
return [msg[i:i + cls.square_size(len(msg))]
for i in range(0, len(msg), cls.square_size(len(msg)))]
@classmethod
def transpose_square(cls, square):
matrix = [list(row) for row in square]
transposed_matrix = cls.filter_out_none(cls.transpose_uneven_matrix(matrix))
transposed_square = [''.join(row) for row in transposed_matrix]
return transposed_square
@staticmethod
def normalize(msg):
return ''.join(ch.lower() for ch in msg if ch not in
set(string.punctuation + ' '))
@staticmethod
def square_size(msg_length):
return int(math.ceil(msg_length ** 0.5))
# https://stackoverflow.com/a/4938130/2813210
@staticmethod
def transpose_uneven_matrix(matrix):
return list(itertools.zip_longest(*matrix))
@staticmethod
def filter_out_none(matrix):
return [[val for val in row if val is not None] for row in matrix]
def encode(msg):
return CryptoSquare.encode(msg)
|
<commit_before>import string
import math
import itertools
class CryptoSquare:
@classmethod
def encode(cls, msg):
if len(cls.normalize(msg)) == 0:
return ''
return ' '.join(cls.transpose_square(cls.squarify(cls.normalize(msg))))
@classmethod
def squarify(cls, msg):
return [msg[i:i + cls.square_size(len(msg))]
for i in range(0, len(msg), cls.square_size(len(msg)))]
@classmethod
def transpose_square(cls, square):
matrix = [list(row) for row in square]
transposed_matrix = cls.transpose_uneven_matrix(matrix)
joined_matrix = [''.join([x for x in row if x is not None]) for row in transposed_matrix]
return joined_matrix
@staticmethod
def normalize(msg):
return ''.join(ch.lower() for ch in msg if ch not in
set(string.punctuation + ' '))
@staticmethod
def square_size(msg_length):
return int(math.ceil(msg_length ** 0.5))
# https://stackoverflow.com/a/4938130/2813210
@staticmethod
def transpose_uneven_matrix(matrix):
return list(itertools.zip_longest(*matrix))
def encode(msg):
return CryptoSquare.encode(msg)
<commit_msg>Refactor filter out none to method<commit_after>
|
import string
import math
import itertools
class CryptoSquare:
@classmethod
def encode(cls, msg):
if len(cls.normalize(msg)) == 0:
return ''
return ' '.join(cls.transpose_square(cls.squarify(cls.normalize(msg))))
@classmethod
def squarify(cls, msg):
return [msg[i:i + cls.square_size(len(msg))]
for i in range(0, len(msg), cls.square_size(len(msg)))]
@classmethod
def transpose_square(cls, square):
matrix = [list(row) for row in square]
transposed_matrix = cls.filter_out_none(cls.transpose_uneven_matrix(matrix))
transposed_square = [''.join(row) for row in transposed_matrix]
return transposed_square
@staticmethod
def normalize(msg):
return ''.join(ch.lower() for ch in msg if ch not in
set(string.punctuation + ' '))
@staticmethod
def square_size(msg_length):
return int(math.ceil(msg_length ** 0.5))
# https://stackoverflow.com/a/4938130/2813210
@staticmethod
def transpose_uneven_matrix(matrix):
return list(itertools.zip_longest(*matrix))
@staticmethod
def filter_out_none(matrix):
return [[val for val in row if val is not None] for row in matrix]
def encode(msg):
return CryptoSquare.encode(msg)
|
import string
import math
import itertools
class CryptoSquare:
@classmethod
def encode(cls, msg):
if len(cls.normalize(msg)) == 0:
return ''
return ' '.join(cls.transpose_square(cls.squarify(cls.normalize(msg))))
@classmethod
def squarify(cls, msg):
return [msg[i:i + cls.square_size(len(msg))]
for i in range(0, len(msg), cls.square_size(len(msg)))]
@classmethod
def transpose_square(cls, square):
matrix = [list(row) for row in square]
transposed_matrix = cls.transpose_uneven_matrix(matrix)
joined_matrix = [''.join([x for x in row if x is not None]) for row in transposed_matrix]
return joined_matrix
@staticmethod
def normalize(msg):
return ''.join(ch.lower() for ch in msg if ch not in
set(string.punctuation + ' '))
@staticmethod
def square_size(msg_length):
return int(math.ceil(msg_length ** 0.5))
# https://stackoverflow.com/a/4938130/2813210
@staticmethod
def transpose_uneven_matrix(matrix):
return list(itertools.zip_longest(*matrix))
def encode(msg):
return CryptoSquare.encode(msg)
Refactor filter out none to methodimport string
import math
import itertools
class CryptoSquare:
@classmethod
def encode(cls, msg):
if len(cls.normalize(msg)) == 0:
return ''
return ' '.join(cls.transpose_square(cls.squarify(cls.normalize(msg))))
@classmethod
def squarify(cls, msg):
return [msg[i:i + cls.square_size(len(msg))]
for i in range(0, len(msg), cls.square_size(len(msg)))]
@classmethod
def transpose_square(cls, square):
matrix = [list(row) for row in square]
transposed_matrix = cls.filter_out_none(cls.transpose_uneven_matrix(matrix))
transposed_square = [''.join(row) for row in transposed_matrix]
return transposed_square
@staticmethod
def normalize(msg):
return ''.join(ch.lower() for ch in msg if ch not in
set(string.punctuation + ' '))
@staticmethod
def square_size(msg_length):
return int(math.ceil(msg_length ** 0.5))
# https://stackoverflow.com/a/4938130/2813210
@staticmethod
def transpose_uneven_matrix(matrix):
return list(itertools.zip_longest(*matrix))
@staticmethod
def filter_out_none(matrix):
return [[val for val in row if val is not None] for row in matrix]
def encode(msg):
return CryptoSquare.encode(msg)
|
<commit_before>import string
import math
import itertools
class CryptoSquare:
@classmethod
def encode(cls, msg):
if len(cls.normalize(msg)) == 0:
return ''
return ' '.join(cls.transpose_square(cls.squarify(cls.normalize(msg))))
@classmethod
def squarify(cls, msg):
return [msg[i:i + cls.square_size(len(msg))]
for i in range(0, len(msg), cls.square_size(len(msg)))]
@classmethod
def transpose_square(cls, square):
matrix = [list(row) for row in square]
transposed_matrix = cls.transpose_uneven_matrix(matrix)
joined_matrix = [''.join([x for x in row if x is not None]) for row in transposed_matrix]
return joined_matrix
@staticmethod
def normalize(msg):
return ''.join(ch.lower() for ch in msg if ch not in
set(string.punctuation + ' '))
@staticmethod
def square_size(msg_length):
return int(math.ceil(msg_length ** 0.5))
# https://stackoverflow.com/a/4938130/2813210
@staticmethod
def transpose_uneven_matrix(matrix):
return list(itertools.zip_longest(*matrix))
def encode(msg):
return CryptoSquare.encode(msg)
<commit_msg>Refactor filter out none to method<commit_after>import string
import math
import itertools
class CryptoSquare:
@classmethod
def encode(cls, msg):
if len(cls.normalize(msg)) == 0:
return ''
return ' '.join(cls.transpose_square(cls.squarify(cls.normalize(msg))))
@classmethod
def squarify(cls, msg):
return [msg[i:i + cls.square_size(len(msg))]
for i in range(0, len(msg), cls.square_size(len(msg)))]
@classmethod
def transpose_square(cls, square):
matrix = [list(row) for row in square]
transposed_matrix = cls.filter_out_none(cls.transpose_uneven_matrix(matrix))
transposed_square = [''.join(row) for row in transposed_matrix]
return transposed_square
@staticmethod
def normalize(msg):
return ''.join(ch.lower() for ch in msg if ch not in
set(string.punctuation + ' '))
@staticmethod
def square_size(msg_length):
return int(math.ceil(msg_length ** 0.5))
# https://stackoverflow.com/a/4938130/2813210
@staticmethod
def transpose_uneven_matrix(matrix):
return list(itertools.zip_longest(*matrix))
@staticmethod
def filter_out_none(matrix):
return [[val for val in row if val is not None] for row in matrix]
def encode(msg):
return CryptoSquare.encode(msg)
|
e01ec3b6c877bc76ffa2e93d97d706036a90405c
|
test/on_yubikey/cli_piv/test_misc.py
|
test/on_yubikey/cli_piv/test_misc.py
|
import unittest
from ..framework import cli_test_suite
from .util import DEFAULT_MANAGEMENT_KEY
@cli_test_suite
def additional_tests(ykman_cli):
class Misc(unittest.TestCase):
def setUp(self):
ykman_cli('piv', 'reset', '-f')
def test_info(self):
output = ykman_cli('piv', 'info')
self.assertIn('PIV version:', output)
def test_reset(self):
output = ykman_cli('piv', 'reset', '-f')
self.assertIn('Success!', output)
def test_write_read_object(self):
ykman_cli(
'piv', 'write-object',
'-m', DEFAULT_MANAGEMENT_KEY, '0x5f0001',
'-', input='test data')
output = ykman_cli('piv', 'read-object', '0x5f0001')
self.assertEqual('test data\n', output)
return [Misc]
|
import unittest
from ..framework import cli_test_suite
from .util import DEFAULT_MANAGEMENT_KEY
@cli_test_suite
def additional_tests(ykman_cli):
class Misc(unittest.TestCase):
def setUp(self):
ykman_cli('piv', 'reset', '-f')
def test_info(self):
output = ykman_cli('piv', 'info')
self.assertIn('PIV version:', output)
def test_reset(self):
output = ykman_cli('piv', 'reset', '-f')
self.assertIn('Success!', output)
def test_write_read_object(self):
data = 'test data'
for i in range(0, 3):
ykman_cli(
'piv', 'write-object',
'-m', DEFAULT_MANAGEMENT_KEY, '0x5f0001',
'-', input=data)
data = ykman_cli('piv', 'read-object', '0x5f0001')
self.assertEqual(data, 'test data')
return [Misc]
|
Test that repeated read/write-object cycles do not change the data
|
Test that repeated read/write-object cycles do not change the data
|
Python
|
bsd-2-clause
|
Yubico/yubikey-manager,Yubico/yubikey-manager
|
import unittest
from ..framework import cli_test_suite
from .util import DEFAULT_MANAGEMENT_KEY
@cli_test_suite
def additional_tests(ykman_cli):
class Misc(unittest.TestCase):
def setUp(self):
ykman_cli('piv', 'reset', '-f')
def test_info(self):
output = ykman_cli('piv', 'info')
self.assertIn('PIV version:', output)
def test_reset(self):
output = ykman_cli('piv', 'reset', '-f')
self.assertIn('Success!', output)
def test_write_read_object(self):
ykman_cli(
'piv', 'write-object',
'-m', DEFAULT_MANAGEMENT_KEY, '0x5f0001',
'-', input='test data')
output = ykman_cli('piv', 'read-object', '0x5f0001')
self.assertEqual('test data\n', output)
return [Misc]
Test that repeated read/write-object cycles do not change the data
|
import unittest
from ..framework import cli_test_suite
from .util import DEFAULT_MANAGEMENT_KEY
@cli_test_suite
def additional_tests(ykman_cli):
class Misc(unittest.TestCase):
def setUp(self):
ykman_cli('piv', 'reset', '-f')
def test_info(self):
output = ykman_cli('piv', 'info')
self.assertIn('PIV version:', output)
def test_reset(self):
output = ykman_cli('piv', 'reset', '-f')
self.assertIn('Success!', output)
def test_write_read_object(self):
data = 'test data'
for i in range(0, 3):
ykman_cli(
'piv', 'write-object',
'-m', DEFAULT_MANAGEMENT_KEY, '0x5f0001',
'-', input=data)
data = ykman_cli('piv', 'read-object', '0x5f0001')
self.assertEqual(data, 'test data')
return [Misc]
|
<commit_before>import unittest
from ..framework import cli_test_suite
from .util import DEFAULT_MANAGEMENT_KEY
@cli_test_suite
def additional_tests(ykman_cli):
class Misc(unittest.TestCase):
def setUp(self):
ykman_cli('piv', 'reset', '-f')
def test_info(self):
output = ykman_cli('piv', 'info')
self.assertIn('PIV version:', output)
def test_reset(self):
output = ykman_cli('piv', 'reset', '-f')
self.assertIn('Success!', output)
def test_write_read_object(self):
ykman_cli(
'piv', 'write-object',
'-m', DEFAULT_MANAGEMENT_KEY, '0x5f0001',
'-', input='test data')
output = ykman_cli('piv', 'read-object', '0x5f0001')
self.assertEqual('test data\n', output)
return [Misc]
<commit_msg>Test that repeated read/write-object cycles do not change the data<commit_after>
|
import unittest
from ..framework import cli_test_suite
from .util import DEFAULT_MANAGEMENT_KEY
@cli_test_suite
def additional_tests(ykman_cli):
class Misc(unittest.TestCase):
def setUp(self):
ykman_cli('piv', 'reset', '-f')
def test_info(self):
output = ykman_cli('piv', 'info')
self.assertIn('PIV version:', output)
def test_reset(self):
output = ykman_cli('piv', 'reset', '-f')
self.assertIn('Success!', output)
def test_write_read_object(self):
data = 'test data'
for i in range(0, 3):
ykman_cli(
'piv', 'write-object',
'-m', DEFAULT_MANAGEMENT_KEY, '0x5f0001',
'-', input=data)
data = ykman_cli('piv', 'read-object', '0x5f0001')
self.assertEqual(data, 'test data')
return [Misc]
|
import unittest
from ..framework import cli_test_suite
from .util import DEFAULT_MANAGEMENT_KEY
@cli_test_suite
def additional_tests(ykman_cli):
class Misc(unittest.TestCase):
def setUp(self):
ykman_cli('piv', 'reset', '-f')
def test_info(self):
output = ykman_cli('piv', 'info')
self.assertIn('PIV version:', output)
def test_reset(self):
output = ykman_cli('piv', 'reset', '-f')
self.assertIn('Success!', output)
def test_write_read_object(self):
ykman_cli(
'piv', 'write-object',
'-m', DEFAULT_MANAGEMENT_KEY, '0x5f0001',
'-', input='test data')
output = ykman_cli('piv', 'read-object', '0x5f0001')
self.assertEqual('test data\n', output)
return [Misc]
Test that repeated read/write-object cycles do not change the dataimport unittest
from ..framework import cli_test_suite
from .util import DEFAULT_MANAGEMENT_KEY
@cli_test_suite
def additional_tests(ykman_cli):
class Misc(unittest.TestCase):
def setUp(self):
ykman_cli('piv', 'reset', '-f')
def test_info(self):
output = ykman_cli('piv', 'info')
self.assertIn('PIV version:', output)
def test_reset(self):
output = ykman_cli('piv', 'reset', '-f')
self.assertIn('Success!', output)
def test_write_read_object(self):
data = 'test data'
for i in range(0, 3):
ykman_cli(
'piv', 'write-object',
'-m', DEFAULT_MANAGEMENT_KEY, '0x5f0001',
'-', input=data)
data = ykman_cli('piv', 'read-object', '0x5f0001')
self.assertEqual(data, 'test data')
return [Misc]
|
<commit_before>import unittest
from ..framework import cli_test_suite
from .util import DEFAULT_MANAGEMENT_KEY
@cli_test_suite
def additional_tests(ykman_cli):
class Misc(unittest.TestCase):
def setUp(self):
ykman_cli('piv', 'reset', '-f')
def test_info(self):
output = ykman_cli('piv', 'info')
self.assertIn('PIV version:', output)
def test_reset(self):
output = ykman_cli('piv', 'reset', '-f')
self.assertIn('Success!', output)
def test_write_read_object(self):
ykman_cli(
'piv', 'write-object',
'-m', DEFAULT_MANAGEMENT_KEY, '0x5f0001',
'-', input='test data')
output = ykman_cli('piv', 'read-object', '0x5f0001')
self.assertEqual('test data\n', output)
return [Misc]
<commit_msg>Test that repeated read/write-object cycles do not change the data<commit_after>import unittest
from ..framework import cli_test_suite
from .util import DEFAULT_MANAGEMENT_KEY
@cli_test_suite
def additional_tests(ykman_cli):
class Misc(unittest.TestCase):
def setUp(self):
ykman_cli('piv', 'reset', '-f')
def test_info(self):
output = ykman_cli('piv', 'info')
self.assertIn('PIV version:', output)
def test_reset(self):
output = ykman_cli('piv', 'reset', '-f')
self.assertIn('Success!', output)
def test_write_read_object(self):
data = 'test data'
for i in range(0, 3):
ykman_cli(
'piv', 'write-object',
'-m', DEFAULT_MANAGEMENT_KEY, '0x5f0001',
'-', input=data)
data = ykman_cli('piv', 'read-object', '0x5f0001')
self.assertEqual(data, 'test data')
return [Misc]
|
979b521a037b44b300e02d66fa0dbd967e078575
|
troposphere/kms.py
|
troposphere/kms.py
|
# Copyright (c) 2012-2013, Mark Peek <[email protected]>
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSObject, Tags
from .compat import policytypes
from .validators import boolean, integer_range, key_usage_type
class Alias(AWSObject):
resource_type = "AWS::KMS::Alias"
props = {"AliasName": (str, True), "TargetKeyId": (str, True)}
class Key(AWSObject):
resource_type = "AWS::KMS::Key"
props = {
"Description": (str, False),
"EnableKeyRotation": (boolean, False),
"Enabled": (boolean, False),
"KeyPolicy": (policytypes, True),
"KeySpec": (str, False),
"KeyUsage": (key_usage_type, False),
"PendingWindowInDays": (integer_range(7, 30), False),
"Tags": ((Tags, list), False),
}
|
# Copyright (c) 2012-2013, Mark Peek <[email protected]>
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSObject, Tags
from .compat import policytypes
from .validators import boolean, integer, integer_range, key_usage_type
class Alias(AWSObject):
resource_type = "AWS::KMS::Alias"
props = {"AliasName": (str, True), "TargetKeyId": (str, True)}
class Key(AWSObject):
resource_type = "AWS::KMS::Key"
props = {
"Description": (str, False),
"EnableKeyRotation": (boolean, False),
"Enabled": (boolean, False),
"KeyPolicy": (policytypes, True),
"KeySpec": (str, False),
"KeyUsage": (key_usage_type, False),
"PendingWindowInDays": (integer_range(7, 30), False),
"Tags": ((Tags, list), False),
}
class ReplicaKey(AWSObject):
resource_type = "AWS::KMS::ReplicaKey"
props = {
"Description": (str, False),
"Enabled": (boolean, False),
"KeyPolicy": (dict, True),
"PendingWindowInDays": (integer, False),
"PrimaryKeyArn": (str, True),
"Tags": (Tags, False),
}
|
Update KMS per 2021-06-17 changes
|
Update KMS per 2021-06-17 changes
|
Python
|
bsd-2-clause
|
cloudtools/troposphere,cloudtools/troposphere
|
# Copyright (c) 2012-2013, Mark Peek <[email protected]>
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSObject, Tags
from .compat import policytypes
from .validators import boolean, integer_range, key_usage_type
class Alias(AWSObject):
resource_type = "AWS::KMS::Alias"
props = {"AliasName": (str, True), "TargetKeyId": (str, True)}
class Key(AWSObject):
resource_type = "AWS::KMS::Key"
props = {
"Description": (str, False),
"EnableKeyRotation": (boolean, False),
"Enabled": (boolean, False),
"KeyPolicy": (policytypes, True),
"KeySpec": (str, False),
"KeyUsage": (key_usage_type, False),
"PendingWindowInDays": (integer_range(7, 30), False),
"Tags": ((Tags, list), False),
}
Update KMS per 2021-06-17 changes
|
# Copyright (c) 2012-2013, Mark Peek <[email protected]>
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSObject, Tags
from .compat import policytypes
from .validators import boolean, integer, integer_range, key_usage_type
class Alias(AWSObject):
resource_type = "AWS::KMS::Alias"
props = {"AliasName": (str, True), "TargetKeyId": (str, True)}
class Key(AWSObject):
resource_type = "AWS::KMS::Key"
props = {
"Description": (str, False),
"EnableKeyRotation": (boolean, False),
"Enabled": (boolean, False),
"KeyPolicy": (policytypes, True),
"KeySpec": (str, False),
"KeyUsage": (key_usage_type, False),
"PendingWindowInDays": (integer_range(7, 30), False),
"Tags": ((Tags, list), False),
}
class ReplicaKey(AWSObject):
resource_type = "AWS::KMS::ReplicaKey"
props = {
"Description": (str, False),
"Enabled": (boolean, False),
"KeyPolicy": (dict, True),
"PendingWindowInDays": (integer, False),
"PrimaryKeyArn": (str, True),
"Tags": (Tags, False),
}
|
<commit_before># Copyright (c) 2012-2013, Mark Peek <[email protected]>
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSObject, Tags
from .compat import policytypes
from .validators import boolean, integer_range, key_usage_type
class Alias(AWSObject):
resource_type = "AWS::KMS::Alias"
props = {"AliasName": (str, True), "TargetKeyId": (str, True)}
class Key(AWSObject):
resource_type = "AWS::KMS::Key"
props = {
"Description": (str, False),
"EnableKeyRotation": (boolean, False),
"Enabled": (boolean, False),
"KeyPolicy": (policytypes, True),
"KeySpec": (str, False),
"KeyUsage": (key_usage_type, False),
"PendingWindowInDays": (integer_range(7, 30), False),
"Tags": ((Tags, list), False),
}
<commit_msg>Update KMS per 2021-06-17 changes<commit_after>
|
# Copyright (c) 2012-2013, Mark Peek <[email protected]>
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSObject, Tags
from .compat import policytypes
from .validators import boolean, integer, integer_range, key_usage_type
class Alias(AWSObject):
resource_type = "AWS::KMS::Alias"
props = {"AliasName": (str, True), "TargetKeyId": (str, True)}
class Key(AWSObject):
resource_type = "AWS::KMS::Key"
props = {
"Description": (str, False),
"EnableKeyRotation": (boolean, False),
"Enabled": (boolean, False),
"KeyPolicy": (policytypes, True),
"KeySpec": (str, False),
"KeyUsage": (key_usage_type, False),
"PendingWindowInDays": (integer_range(7, 30), False),
"Tags": ((Tags, list), False),
}
class ReplicaKey(AWSObject):
resource_type = "AWS::KMS::ReplicaKey"
props = {
"Description": (str, False),
"Enabled": (boolean, False),
"KeyPolicy": (dict, True),
"PendingWindowInDays": (integer, False),
"PrimaryKeyArn": (str, True),
"Tags": (Tags, False),
}
|
# Copyright (c) 2012-2013, Mark Peek <[email protected]>
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSObject, Tags
from .compat import policytypes
from .validators import boolean, integer_range, key_usage_type
class Alias(AWSObject):
resource_type = "AWS::KMS::Alias"
props = {"AliasName": (str, True), "TargetKeyId": (str, True)}
class Key(AWSObject):
resource_type = "AWS::KMS::Key"
props = {
"Description": (str, False),
"EnableKeyRotation": (boolean, False),
"Enabled": (boolean, False),
"KeyPolicy": (policytypes, True),
"KeySpec": (str, False),
"KeyUsage": (key_usage_type, False),
"PendingWindowInDays": (integer_range(7, 30), False),
"Tags": ((Tags, list), False),
}
Update KMS per 2021-06-17 changes# Copyright (c) 2012-2013, Mark Peek <[email protected]>
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSObject, Tags
from .compat import policytypes
from .validators import boolean, integer, integer_range, key_usage_type
class Alias(AWSObject):
resource_type = "AWS::KMS::Alias"
props = {"AliasName": (str, True), "TargetKeyId": (str, True)}
class Key(AWSObject):
resource_type = "AWS::KMS::Key"
props = {
"Description": (str, False),
"EnableKeyRotation": (boolean, False),
"Enabled": (boolean, False),
"KeyPolicy": (policytypes, True),
"KeySpec": (str, False),
"KeyUsage": (key_usage_type, False),
"PendingWindowInDays": (integer_range(7, 30), False),
"Tags": ((Tags, list), False),
}
class ReplicaKey(AWSObject):
resource_type = "AWS::KMS::ReplicaKey"
props = {
"Description": (str, False),
"Enabled": (boolean, False),
"KeyPolicy": (dict, True),
"PendingWindowInDays": (integer, False),
"PrimaryKeyArn": (str, True),
"Tags": (Tags, False),
}
|
<commit_before># Copyright (c) 2012-2013, Mark Peek <[email protected]>
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSObject, Tags
from .compat import policytypes
from .validators import boolean, integer_range, key_usage_type
class Alias(AWSObject):
resource_type = "AWS::KMS::Alias"
props = {"AliasName": (str, True), "TargetKeyId": (str, True)}
class Key(AWSObject):
resource_type = "AWS::KMS::Key"
props = {
"Description": (str, False),
"EnableKeyRotation": (boolean, False),
"Enabled": (boolean, False),
"KeyPolicy": (policytypes, True),
"KeySpec": (str, False),
"KeyUsage": (key_usage_type, False),
"PendingWindowInDays": (integer_range(7, 30), False),
"Tags": ((Tags, list), False),
}
<commit_msg>Update KMS per 2021-06-17 changes<commit_after># Copyright (c) 2012-2013, Mark Peek <[email protected]>
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSObject, Tags
from .compat import policytypes
from .validators import boolean, integer, integer_range, key_usage_type
class Alias(AWSObject):
resource_type = "AWS::KMS::Alias"
props = {"AliasName": (str, True), "TargetKeyId": (str, True)}
class Key(AWSObject):
resource_type = "AWS::KMS::Key"
props = {
"Description": (str, False),
"EnableKeyRotation": (boolean, False),
"Enabled": (boolean, False),
"KeyPolicy": (policytypes, True),
"KeySpec": (str, False),
"KeyUsage": (key_usage_type, False),
"PendingWindowInDays": (integer_range(7, 30), False),
"Tags": ((Tags, list), False),
}
class ReplicaKey(AWSObject):
resource_type = "AWS::KMS::ReplicaKey"
props = {
"Description": (str, False),
"Enabled": (boolean, False),
"KeyPolicy": (dict, True),
"PendingWindowInDays": (integer, False),
"PrimaryKeyArn": (str, True),
"Tags": (Tags, False),
}
|
a48b7bc7606d85705d8798f7823adb032df6dc0d
|
u2fval/__init__.py
|
u2fval/__init__.py
|
# Copyright (c) 2014 Yubico AB
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
__version__ = "0.9.1"
|
# Copyright (c) 2014 Yubico AB
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
__version__ = "0.9.1-dev0"
|
Set a development build version.
|
Set a development build version.
|
Python
|
bsd-2-clause
|
Yubico/u2fval
|
# Copyright (c) 2014 Yubico AB
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
__version__ = "0.9.1"
Set a development build version.
|
# Copyright (c) 2014 Yubico AB
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
__version__ = "0.9.1-dev0"
|
<commit_before># Copyright (c) 2014 Yubico AB
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
__version__ = "0.9.1"
<commit_msg>Set a development build version.<commit_after>
|
# Copyright (c) 2014 Yubico AB
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
__version__ = "0.9.1-dev0"
|
# Copyright (c) 2014 Yubico AB
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
__version__ = "0.9.1"
Set a development build version.# Copyright (c) 2014 Yubico AB
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
__version__ = "0.9.1-dev0"
|
<commit_before># Copyright (c) 2014 Yubico AB
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
__version__ = "0.9.1"
<commit_msg>Set a development build version.<commit_after># Copyright (c) 2014 Yubico AB
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
__version__ = "0.9.1-dev0"
|
d49ef15aca8b9955e02b8719f238cc3a4ea26602
|
dev/__init__.py
|
dev/__init__.py
|
# coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
import os
package_name = "ocspbuilder"
other_packages = []
requires_oscrypto = True
has_tests_package = False
package_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
build_root = os.path.abspath(os.path.join(package_root, '..'))
md_source_map = {
'docs/api.md': ['ocspbuilder/__init__.py'],
}
definition_replacements = {}
|
# coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
import os
package_name = "ocspbuilder"
other_packages = []
task_keyword_args = []
requires_oscrypto = True
has_tests_package = False
package_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
build_root = os.path.abspath(os.path.join(package_root, '..'))
md_source_map = {
'docs/api.md': ['ocspbuilder/__init__.py'],
}
definition_replacements = {}
|
Add missing dev config variable
|
Add missing dev config variable
|
Python
|
mit
|
wbond/ocspbuilder
|
# coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
import os
package_name = "ocspbuilder"
other_packages = []
requires_oscrypto = True
has_tests_package = False
package_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
build_root = os.path.abspath(os.path.join(package_root, '..'))
md_source_map = {
'docs/api.md': ['ocspbuilder/__init__.py'],
}
definition_replacements = {}
Add missing dev config variable
|
# coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
import os
package_name = "ocspbuilder"
other_packages = []
task_keyword_args = []
requires_oscrypto = True
has_tests_package = False
package_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
build_root = os.path.abspath(os.path.join(package_root, '..'))
md_source_map = {
'docs/api.md': ['ocspbuilder/__init__.py'],
}
definition_replacements = {}
|
<commit_before># coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
import os
package_name = "ocspbuilder"
other_packages = []
requires_oscrypto = True
has_tests_package = False
package_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
build_root = os.path.abspath(os.path.join(package_root, '..'))
md_source_map = {
'docs/api.md': ['ocspbuilder/__init__.py'],
}
definition_replacements = {}
<commit_msg>Add missing dev config variable<commit_after>
|
# coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
import os
package_name = "ocspbuilder"
other_packages = []
task_keyword_args = []
requires_oscrypto = True
has_tests_package = False
package_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
build_root = os.path.abspath(os.path.join(package_root, '..'))
md_source_map = {
'docs/api.md': ['ocspbuilder/__init__.py'],
}
definition_replacements = {}
|
# coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
import os
package_name = "ocspbuilder"
other_packages = []
requires_oscrypto = True
has_tests_package = False
package_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
build_root = os.path.abspath(os.path.join(package_root, '..'))
md_source_map = {
'docs/api.md': ['ocspbuilder/__init__.py'],
}
definition_replacements = {}
Add missing dev config variable# coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
import os
package_name = "ocspbuilder"
other_packages = []
task_keyword_args = []
requires_oscrypto = True
has_tests_package = False
package_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
build_root = os.path.abspath(os.path.join(package_root, '..'))
md_source_map = {
'docs/api.md': ['ocspbuilder/__init__.py'],
}
definition_replacements = {}
|
<commit_before># coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
import os
package_name = "ocspbuilder"
other_packages = []
requires_oscrypto = True
has_tests_package = False
package_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
build_root = os.path.abspath(os.path.join(package_root, '..'))
md_source_map = {
'docs/api.md': ['ocspbuilder/__init__.py'],
}
definition_replacements = {}
<commit_msg>Add missing dev config variable<commit_after># coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
import os
package_name = "ocspbuilder"
other_packages = []
task_keyword_args = []
requires_oscrypto = True
has_tests_package = False
package_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
build_root = os.path.abspath(os.path.join(package_root, '..'))
md_source_map = {
'docs/api.md': ['ocspbuilder/__init__.py'],
}
definition_replacements = {}
|
407d99a19c4427d4d94124b615d9d3c9bc5d3494
|
frameworks/Python/API-Hour/hello/etc/hello/api_hour/gunicorn_conf.py
|
frameworks/Python/API-Hour/hello/etc/hello/api_hour/gunicorn_conf.py
|
import multiprocessing
import os
_is_travis = os.environ.get('TRAVIS') == 'true'
workers = multiprocessing.cpu_count() * 3
if _is_travis:
workers = 2
bind = ['0.0.0.0:8008', '0.0.0.0:8009', '0.0.0.0:8011']
keepalive = 120
errorlog = '-'
pidfile = 'api_hour.pid'
pythonpath = 'hello'
backlog = 10240000
|
import multiprocessing
import os
_is_travis = os.environ.get('TRAVIS') == 'true'
workers = multiprocessing.cpu_count() * 2
if _is_travis:
workers = 2
bind = ['0.0.0.0:8008', '0.0.0.0:8009', '0.0.0.0:8011']
keepalive = 120
errorlog = '-'
pidfile = 'api_hour.pid'
pythonpath = 'hello'
backlog = 10240000
|
Reduce pgsql socket pool and number of workers to match 2000 maximum connections
|
Reduce pgsql socket pool and number of workers to match 2000 maximum connections
|
Python
|
bsd-3-clause
|
xitrum-framework/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,sxend/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,zloster/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,doom369/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,zapov/FrameworkBenchmarks,khellang/FrameworkBenchmarks,sxend/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,joshk/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,khellang/FrameworkBenchmarks,herloct/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,doom369/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,joshk/FrameworkBenchmarks,sxend/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,grob/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,zloster/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,jamming/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,methane/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,zloster/FrameworkBenchmarks,actframework/FrameworkBenchmarks,methane/FrameworkBenchmarks,testn/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,testn/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,sxend/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,valyala/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,doom369/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,denkab/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,khellang/FrameworkBenchmarks,Verber/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,herloct/FrameworkBenchmarks,doom369/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,Verber/FrameworkBenchmarks,denkab/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,joshk/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,testn/FrameworkBenchmarks,sxend/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,sgml/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,methane/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,joshk/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,doom369/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,denkab/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,testn/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,jamming/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,joshk/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,methane/FrameworkBenchmarks,actframework/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,sxend/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,valyala/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,sgml/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,herloct/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,actframework/FrameworkBenchmarks,zapov/FrameworkBenchmarks,herloct/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,zloster/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,doom369/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,valyala/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,zapov/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,sgml/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,jamming/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,zloster/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,valyala/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,zapov/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,Verber/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,zapov/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,testn/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,herloct/FrameworkBenchmarks,khellang/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,khellang/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,denkab/FrameworkBenchmarks,doom369/FrameworkBenchmarks,methane/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,actframework/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,doom369/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,zapov/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,doom369/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,herloct/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,zapov/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,methane/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,herloct/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,sxend/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,Verber/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,methane/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,zloster/FrameworkBenchmarks,zloster/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,doom369/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,herloct/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,sgml/FrameworkBenchmarks,testn/FrameworkBenchmarks,zapov/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,actframework/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,joshk/FrameworkBenchmarks,sxend/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,joshk/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,sgml/FrameworkBenchmarks,testn/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,valyala/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,jamming/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,testn/FrameworkBenchmarks,khellang/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,jamming/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,sxend/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,denkab/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,zloster/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,grob/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,valyala/FrameworkBenchmarks,zapov/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,sxend/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,actframework/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,actframework/FrameworkBenchmarks,zapov/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,doom369/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,Verber/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,grob/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,denkab/FrameworkBenchmarks,joshk/FrameworkBenchmarks,sgml/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,sgml/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,denkab/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,methane/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,actframework/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,sgml/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,denkab/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,doom369/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,testn/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,sgml/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,zloster/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,zapov/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,Verber/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,denkab/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,zapov/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,testn/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,khellang/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,sxend/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,grob/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,jamming/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,grob/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,herloct/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,doom369/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,joshk/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,herloct/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,herloct/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,zloster/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,Verber/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,methane/FrameworkBenchmarks,Verber/FrameworkBenchmarks,joshk/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,grob/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,khellang/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,actframework/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,jamming/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,jamming/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,valyala/FrameworkBenchmarks,Verber/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,zapov/FrameworkBenchmarks,zloster/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,zloster/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,grob/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,joshk/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,joshk/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,sxend/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,doom369/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,grob/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,valyala/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,sgml/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,grob/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,methane/FrameworkBenchmarks,actframework/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,methane/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,valyala/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,herloct/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,zloster/FrameworkBenchmarks,zloster/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,Verber/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,actframework/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,testn/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,grob/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,sxend/FrameworkBenchmarks,sxend/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,sxend/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,actframework/FrameworkBenchmarks,methane/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,sgml/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,zloster/FrameworkBenchmarks,jamming/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,sgml/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,denkab/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,grob/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,valyala/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,denkab/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,methane/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,actframework/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,Verber/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,khellang/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,valyala/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,khellang/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,herloct/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,joshk/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,denkab/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,doom369/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,denkab/FrameworkBenchmarks,actframework/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,MTDdk/FrameworkBenchmarks,valyala/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,sgml/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,zapov/FrameworkBenchmarks,grob/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,doom369/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,jamming/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,khellang/FrameworkBenchmarks,grob/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,khellang/FrameworkBenchmarks,alubbe/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,herloct/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,Verber/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,denkab/FrameworkBenchmarks,zapov/FrameworkBenchmarks,grob/FrameworkBenchmarks,yunspace/FrameworkBenchmarks,Rydgel/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,jamming/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,sxend/FrameworkBenchmarks,zapov/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,sagenschneider/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,kbrock/FrameworkBenchmarks,zloster/FrameworkBenchmarks,sxend/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,zloster/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,herloct/FrameworkBenchmarks,joshk/FrameworkBenchmarks,Jesterovskiy/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,Verber/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,thousandsofthem/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,testn/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,methane/FrameworkBenchmarks,testn/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks,jamming/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,khellang/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,jaguililla/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,jamming/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,jamming/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,fabianmurariu/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,sanjoydesk/FrameworkBenchmarks,actframework/FrameworkBenchmarks,sxend/FrameworkBenchmarks,greg-hellings/FrameworkBenchmarks,psfblair/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,valyala/FrameworkBenchmarks,victorbriz/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,kostya-sh/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,valyala/FrameworkBenchmarks,actframework/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,nbrady-techempower/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,sgml/FrameworkBenchmarks,Verber/FrameworkBenchmarks,youprofit/FrameworkBenchmarks,Rayne/FrameworkBenchmarks,zloster/FrameworkBenchmarks,knewmanTE/FrameworkBenchmarks,khellang/FrameworkBenchmarks,doom369/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,greenlaw110/FrameworkBenchmarks,saturday06/FrameworkBenchmarks,raziel057/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,testn/FrameworkBenchmarks,hperadin/FrameworkBenchmarks,PermeAgility/FrameworkBenchmarks,F3Community/FrameworkBenchmarks,martin-g/FrameworkBenchmarks,nathana1/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,jebbstewart/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,xitrum-framework/FrameworkBenchmarks
|
import multiprocessing
import os
_is_travis = os.environ.get('TRAVIS') == 'true'
workers = multiprocessing.cpu_count() * 3
if _is_travis:
workers = 2
bind = ['0.0.0.0:8008', '0.0.0.0:8009', '0.0.0.0:8011']
keepalive = 120
errorlog = '-'
pidfile = 'api_hour.pid'
pythonpath = 'hello'
backlog = 10240000Reduce pgsql socket pool and number of workers to match 2000 maximum connections
|
import multiprocessing
import os
_is_travis = os.environ.get('TRAVIS') == 'true'
workers = multiprocessing.cpu_count() * 2
if _is_travis:
workers = 2
bind = ['0.0.0.0:8008', '0.0.0.0:8009', '0.0.0.0:8011']
keepalive = 120
errorlog = '-'
pidfile = 'api_hour.pid'
pythonpath = 'hello'
backlog = 10240000
|
<commit_before>import multiprocessing
import os
_is_travis = os.environ.get('TRAVIS') == 'true'
workers = multiprocessing.cpu_count() * 3
if _is_travis:
workers = 2
bind = ['0.0.0.0:8008', '0.0.0.0:8009', '0.0.0.0:8011']
keepalive = 120
errorlog = '-'
pidfile = 'api_hour.pid'
pythonpath = 'hello'
backlog = 10240000<commit_msg>Reduce pgsql socket pool and number of workers to match 2000 maximum connections<commit_after>
|
import multiprocessing
import os
_is_travis = os.environ.get('TRAVIS') == 'true'
workers = multiprocessing.cpu_count() * 2
if _is_travis:
workers = 2
bind = ['0.0.0.0:8008', '0.0.0.0:8009', '0.0.0.0:8011']
keepalive = 120
errorlog = '-'
pidfile = 'api_hour.pid'
pythonpath = 'hello'
backlog = 10240000
|
import multiprocessing
import os
_is_travis = os.environ.get('TRAVIS') == 'true'
workers = multiprocessing.cpu_count() * 3
if _is_travis:
workers = 2
bind = ['0.0.0.0:8008', '0.0.0.0:8009', '0.0.0.0:8011']
keepalive = 120
errorlog = '-'
pidfile = 'api_hour.pid'
pythonpath = 'hello'
backlog = 10240000Reduce pgsql socket pool and number of workers to match 2000 maximum connectionsimport multiprocessing
import os
_is_travis = os.environ.get('TRAVIS') == 'true'
workers = multiprocessing.cpu_count() * 2
if _is_travis:
workers = 2
bind = ['0.0.0.0:8008', '0.0.0.0:8009', '0.0.0.0:8011']
keepalive = 120
errorlog = '-'
pidfile = 'api_hour.pid'
pythonpath = 'hello'
backlog = 10240000
|
<commit_before>import multiprocessing
import os
_is_travis = os.environ.get('TRAVIS') == 'true'
workers = multiprocessing.cpu_count() * 3
if _is_travis:
workers = 2
bind = ['0.0.0.0:8008', '0.0.0.0:8009', '0.0.0.0:8011']
keepalive = 120
errorlog = '-'
pidfile = 'api_hour.pid'
pythonpath = 'hello'
backlog = 10240000<commit_msg>Reduce pgsql socket pool and number of workers to match 2000 maximum connections<commit_after>import multiprocessing
import os
_is_travis = os.environ.get('TRAVIS') == 'true'
workers = multiprocessing.cpu_count() * 2
if _is_travis:
workers = 2
bind = ['0.0.0.0:8008', '0.0.0.0:8009', '0.0.0.0:8011']
keepalive = 120
errorlog = '-'
pidfile = 'api_hour.pid'
pythonpath = 'hello'
backlog = 10240000
|
d80a92cfe45907b9f91fd212a3b06fa0b2321364
|
wagtail/tests/routablepage/models.py
|
wagtail/tests/routablepage/models.py
|
from django.db import models
from django.http import HttpResponse
from django.conf.urls import url
from wagtail.contrib.wagtailroutablepage.models import RoutablePage
def routable_page_external_view(request, arg):
return HttpResponse("EXTERNAL VIEW: " + arg)
class RoutablePageTest(RoutablePage):
subpage_urls = (
url(r'^$', 'main', name='main'),
url(r'^archive/year/(\d+)/$', 'archive_by_year', name='archive_by_year'),
url(r'^archive/author/(?P<author_slug>.+)/$', 'archive_by_author', name='archive_by_author'),
url(r'^external/(.+)/$', routable_page_external_view, name='external_view')
)
def archive_by_year(self, request, year):
return HttpResponse("ARCHIVE BY YEAR: " + str(year))
def archive_by_author(self, request, author_slug):
return HttpResponse("ARCHIVE BY AUTHOR: " + author_slug)
def main(self, request):
return HttpResponse("MAIN VIEW")
|
from django.db import models
from django.http import HttpResponse
from django.conf.urls import url
from wagtail.contrib.wagtailroutablepage.models import RoutablePage
def routable_page_external_view(request, arg):
return HttpResponse("EXTERNAL VIEW: " + arg)
class RoutablePageTest(RoutablePage):
@property
def subpage_urls(self):
return (
url(r'^$', self.main, name='main'),
url(r'^archive/year/(\d+)/$', self.archive_by_year, name='archive_by_year'),
url(r'^archive/author/(?P<author_slug>.+)/$', self.archive_by_author, name='archive_by_author'),
url(r'^external/(.+)/$', routable_page_external_view, name='external_view')
)
def archive_by_year(self, request, year):
return HttpResponse("ARCHIVE BY YEAR: " + str(year))
def archive_by_author(self, request, author_slug):
return HttpResponse("ARCHIVE BY AUTHOR: " + author_slug)
def main(self, request):
return HttpResponse("MAIN VIEW")
|
Make subpage_urls a property on RoutablePageTest
|
Make subpage_urls a property on RoutablePageTest
|
Python
|
bsd-3-clause
|
JoshBarr/wagtail,mikedingjan/wagtail,gasman/wagtail,takeflight/wagtail,kurtw/wagtail,jorge-marques/wagtail,Pennebaker/wagtail,zerolab/wagtail,kurtw/wagtail,bjesus/wagtail,nilnvoid/wagtail,mayapurmedia/wagtail,chrxr/wagtail,nilnvoid/wagtail,zerolab/wagtail,Klaudit/wagtail,iho/wagtail,serzans/wagtail,Tivix/wagtail,wagtail/wagtail,zerolab/wagtail,kurtw/wagtail,inonit/wagtail,mephizzle/wagtail,quru/wagtail,mjec/wagtail,Toshakins/wagtail,rv816/wagtail,mjec/wagtail,nimasmi/wagtail,gasman/wagtail,nealtodd/wagtail,darith27/wagtail,KimGlazebrook/wagtail-experiment,quru/wagtail,iansprice/wagtail,rsalmaso/wagtail,gasman/wagtail,inonit/wagtail,WQuanfeng/wagtail,stevenewey/wagtail,stevenewey/wagtail,nealtodd/wagtail,KimGlazebrook/wagtail-experiment,hamsterbacke23/wagtail,kaedroho/wagtail,timorieber/wagtail,thenewguy/wagtail,mephizzle/wagtail,mixxorz/wagtail,janusnic/wagtail,chrxr/wagtail,zerolab/wagtail,mephizzle/wagtail,quru/wagtail,davecranwell/wagtail,takeshineshiro/wagtail,nimasmi/wagtail,thenewguy/wagtail,takeflight/wagtail,jordij/wagtail,Klaudit/wagtail,marctc/wagtail,hamsterbacke23/wagtail,mayapurmedia/wagtail,nutztherookie/wagtail,darith27/wagtail,Toshakins/wagtail,taedori81/wagtail,gogobook/wagtail,JoshBarr/wagtail,nealtodd/wagtail,hamsterbacke23/wagtail,takeshineshiro/wagtail,Klaudit/wagtail,thenewguy/wagtail,jorge-marques/wagtail,hanpama/wagtail,takeflight/wagtail,thenewguy/wagtail,stevenewey/wagtail,mjec/wagtail,hamsterbacke23/wagtail,nutztherookie/wagtail,mikedingjan/wagtail,nrsimha/wagtail,hanpama/wagtail,jnns/wagtail,kurtrwall/wagtail,mikedingjan/wagtail,Toshakins/wagtail,wagtail/wagtail,FlipperPA/wagtail,jordij/wagtail,janusnic/wagtail,gasman/wagtail,nimasmi/wagtail,darith27/wagtail,rsalmaso/wagtail,jorge-marques/wagtail,kurtw/wagtail,mixxorz/wagtail,kurtrwall/wagtail,iansprice/wagtail,serzans/wagtail,serzans/wagtail,iansprice/wagtail,nrsimha/wagtail,JoshBarr/wagtail,taedori81/wagtail,inonit/wagtail,bjesus/wagtail,mayapurmedia/wagtail,FlipperPA/wagtail,nrsimha/wagtail,Tivix/wagtail,marctc/wagtail,janusnic/wagtail,iho/wagtail,takeflight/wagtail,taedori81/wagtail,gogobook/wagtail,hanpama/wagtail,jorge-marques/wagtail,mephizzle/wagtail,jnns/wagtail,tangentlabs/wagtail,nilnvoid/wagtail,rsalmaso/wagtail,m-sanders/wagtail,taedori81/wagtail,nimasmi/wagtail,nutztherookie/wagtail,Pennebaker/wagtail,rjsproxy/wagtail,rjsproxy/wagtail,kaedroho/wagtail,hanpama/wagtail,chrxr/wagtail,jordij/wagtail,mayapurmedia/wagtail,JoshBarr/wagtail,jordij/wagtail,WQuanfeng/wagtail,taedori81/wagtail,gogobook/wagtail,Pennebaker/wagtail,m-sanders/wagtail,jnns/wagtail,timorieber/wagtail,mixxorz/wagtail,thenewguy/wagtail,davecranwell/wagtail,gasman/wagtail,nealtodd/wagtail,mixxorz/wagtail,KimGlazebrook/wagtail-experiment,iansprice/wagtail,tangentlabs/wagtail,wagtail/wagtail,m-sanders/wagtail,takeshineshiro/wagtail,davecranwell/wagtail,timorieber/wagtail,mixxorz/wagtail,rjsproxy/wagtail,Klaudit/wagtail,kaedroho/wagtail,wagtail/wagtail,janusnic/wagtail,jnns/wagtail,gogobook/wagtail,iho/wagtail,rv816/wagtail,KimGlazebrook/wagtail-experiment,mikedingjan/wagtail,torchbox/wagtail,darith27/wagtail,stevenewey/wagtail,rsalmaso/wagtail,torchbox/wagtail,bjesus/wagtail,Pennebaker/wagtail,iho/wagtail,chrxr/wagtail,WQuanfeng/wagtail,Tivix/wagtail,Toshakins/wagtail,rsalmaso/wagtail,mjec/wagtail,nilnvoid/wagtail,rv816/wagtail,kaedroho/wagtail,kurtrwall/wagtail,m-sanders/wagtail,nutztherookie/wagtail,nrsimha/wagtail,inonit/wagtail,tangentlabs/wagtail,FlipperPA/wagtail,kurtrwall/wagtail,FlipperPA/wagtail,torchbox/wagtail,rv816/wagtail,torchbox/wagtail,Tivix/wagtail,davecranwell/wagtail,quru/wagtail,WQuanfeng/wagtail,wagtail/wagtail,zerolab/wagtail,serzans/wagtail,takeshineshiro/wagtail,kaedroho/wagtail,marctc/wagtail,timorieber/wagtail,bjesus/wagtail,tangentlabs/wagtail,marctc/wagtail,rjsproxy/wagtail,jorge-marques/wagtail
|
from django.db import models
from django.http import HttpResponse
from django.conf.urls import url
from wagtail.contrib.wagtailroutablepage.models import RoutablePage
def routable_page_external_view(request, arg):
return HttpResponse("EXTERNAL VIEW: " + arg)
class RoutablePageTest(RoutablePage):
subpage_urls = (
url(r'^$', 'main', name='main'),
url(r'^archive/year/(\d+)/$', 'archive_by_year', name='archive_by_year'),
url(r'^archive/author/(?P<author_slug>.+)/$', 'archive_by_author', name='archive_by_author'),
url(r'^external/(.+)/$', routable_page_external_view, name='external_view')
)
def archive_by_year(self, request, year):
return HttpResponse("ARCHIVE BY YEAR: " + str(year))
def archive_by_author(self, request, author_slug):
return HttpResponse("ARCHIVE BY AUTHOR: " + author_slug)
def main(self, request):
return HttpResponse("MAIN VIEW")
Make subpage_urls a property on RoutablePageTest
|
from django.db import models
from django.http import HttpResponse
from django.conf.urls import url
from wagtail.contrib.wagtailroutablepage.models import RoutablePage
def routable_page_external_view(request, arg):
return HttpResponse("EXTERNAL VIEW: " + arg)
class RoutablePageTest(RoutablePage):
@property
def subpage_urls(self):
return (
url(r'^$', self.main, name='main'),
url(r'^archive/year/(\d+)/$', self.archive_by_year, name='archive_by_year'),
url(r'^archive/author/(?P<author_slug>.+)/$', self.archive_by_author, name='archive_by_author'),
url(r'^external/(.+)/$', routable_page_external_view, name='external_view')
)
def archive_by_year(self, request, year):
return HttpResponse("ARCHIVE BY YEAR: " + str(year))
def archive_by_author(self, request, author_slug):
return HttpResponse("ARCHIVE BY AUTHOR: " + author_slug)
def main(self, request):
return HttpResponse("MAIN VIEW")
|
<commit_before>from django.db import models
from django.http import HttpResponse
from django.conf.urls import url
from wagtail.contrib.wagtailroutablepage.models import RoutablePage
def routable_page_external_view(request, arg):
return HttpResponse("EXTERNAL VIEW: " + arg)
class RoutablePageTest(RoutablePage):
subpage_urls = (
url(r'^$', 'main', name='main'),
url(r'^archive/year/(\d+)/$', 'archive_by_year', name='archive_by_year'),
url(r'^archive/author/(?P<author_slug>.+)/$', 'archive_by_author', name='archive_by_author'),
url(r'^external/(.+)/$', routable_page_external_view, name='external_view')
)
def archive_by_year(self, request, year):
return HttpResponse("ARCHIVE BY YEAR: " + str(year))
def archive_by_author(self, request, author_slug):
return HttpResponse("ARCHIVE BY AUTHOR: " + author_slug)
def main(self, request):
return HttpResponse("MAIN VIEW")
<commit_msg>Make subpage_urls a property on RoutablePageTest<commit_after>
|
from django.db import models
from django.http import HttpResponse
from django.conf.urls import url
from wagtail.contrib.wagtailroutablepage.models import RoutablePage
def routable_page_external_view(request, arg):
return HttpResponse("EXTERNAL VIEW: " + arg)
class RoutablePageTest(RoutablePage):
@property
def subpage_urls(self):
return (
url(r'^$', self.main, name='main'),
url(r'^archive/year/(\d+)/$', self.archive_by_year, name='archive_by_year'),
url(r'^archive/author/(?P<author_slug>.+)/$', self.archive_by_author, name='archive_by_author'),
url(r'^external/(.+)/$', routable_page_external_view, name='external_view')
)
def archive_by_year(self, request, year):
return HttpResponse("ARCHIVE BY YEAR: " + str(year))
def archive_by_author(self, request, author_slug):
return HttpResponse("ARCHIVE BY AUTHOR: " + author_slug)
def main(self, request):
return HttpResponse("MAIN VIEW")
|
from django.db import models
from django.http import HttpResponse
from django.conf.urls import url
from wagtail.contrib.wagtailroutablepage.models import RoutablePage
def routable_page_external_view(request, arg):
return HttpResponse("EXTERNAL VIEW: " + arg)
class RoutablePageTest(RoutablePage):
subpage_urls = (
url(r'^$', 'main', name='main'),
url(r'^archive/year/(\d+)/$', 'archive_by_year', name='archive_by_year'),
url(r'^archive/author/(?P<author_slug>.+)/$', 'archive_by_author', name='archive_by_author'),
url(r'^external/(.+)/$', routable_page_external_view, name='external_view')
)
def archive_by_year(self, request, year):
return HttpResponse("ARCHIVE BY YEAR: " + str(year))
def archive_by_author(self, request, author_slug):
return HttpResponse("ARCHIVE BY AUTHOR: " + author_slug)
def main(self, request):
return HttpResponse("MAIN VIEW")
Make subpage_urls a property on RoutablePageTestfrom django.db import models
from django.http import HttpResponse
from django.conf.urls import url
from wagtail.contrib.wagtailroutablepage.models import RoutablePage
def routable_page_external_view(request, arg):
return HttpResponse("EXTERNAL VIEW: " + arg)
class RoutablePageTest(RoutablePage):
@property
def subpage_urls(self):
return (
url(r'^$', self.main, name='main'),
url(r'^archive/year/(\d+)/$', self.archive_by_year, name='archive_by_year'),
url(r'^archive/author/(?P<author_slug>.+)/$', self.archive_by_author, name='archive_by_author'),
url(r'^external/(.+)/$', routable_page_external_view, name='external_view')
)
def archive_by_year(self, request, year):
return HttpResponse("ARCHIVE BY YEAR: " + str(year))
def archive_by_author(self, request, author_slug):
return HttpResponse("ARCHIVE BY AUTHOR: " + author_slug)
def main(self, request):
return HttpResponse("MAIN VIEW")
|
<commit_before>from django.db import models
from django.http import HttpResponse
from django.conf.urls import url
from wagtail.contrib.wagtailroutablepage.models import RoutablePage
def routable_page_external_view(request, arg):
return HttpResponse("EXTERNAL VIEW: " + arg)
class RoutablePageTest(RoutablePage):
subpage_urls = (
url(r'^$', 'main', name='main'),
url(r'^archive/year/(\d+)/$', 'archive_by_year', name='archive_by_year'),
url(r'^archive/author/(?P<author_slug>.+)/$', 'archive_by_author', name='archive_by_author'),
url(r'^external/(.+)/$', routable_page_external_view, name='external_view')
)
def archive_by_year(self, request, year):
return HttpResponse("ARCHIVE BY YEAR: " + str(year))
def archive_by_author(self, request, author_slug):
return HttpResponse("ARCHIVE BY AUTHOR: " + author_slug)
def main(self, request):
return HttpResponse("MAIN VIEW")
<commit_msg>Make subpage_urls a property on RoutablePageTest<commit_after>from django.db import models
from django.http import HttpResponse
from django.conf.urls import url
from wagtail.contrib.wagtailroutablepage.models import RoutablePage
def routable_page_external_view(request, arg):
return HttpResponse("EXTERNAL VIEW: " + arg)
class RoutablePageTest(RoutablePage):
@property
def subpage_urls(self):
return (
url(r'^$', self.main, name='main'),
url(r'^archive/year/(\d+)/$', self.archive_by_year, name='archive_by_year'),
url(r'^archive/author/(?P<author_slug>.+)/$', self.archive_by_author, name='archive_by_author'),
url(r'^external/(.+)/$', routable_page_external_view, name='external_view')
)
def archive_by_year(self, request, year):
return HttpResponse("ARCHIVE BY YEAR: " + str(year))
def archive_by_author(self, request, author_slug):
return HttpResponse("ARCHIVE BY AUTHOR: " + author_slug)
def main(self, request):
return HttpResponse("MAIN VIEW")
|
e4e8c4e3b98e122e5cf4c9c349c4fb2abfe00ab1
|
api/bioguide/models.py
|
api/bioguide/models.py
|
from django.db import models
class Legislator(models.Model):
"""Model representing a legislator in a session of congress.
"""
bioguide_id = models.CharField(max_length=7, db_index=True)
prefix = models.CharField(max_length=16)
first = models.CharField(max_length=64)
last = models.CharField(max_length=64)
suffix = models.CharField(max_length=16)
birth_death = models.CharField(max_length=16)
position = models.CharField(max_length=24)
party = models.CharField(max_length=32)
state = models.CharField(max_length=2)
congress = models.CharField(max_length=3)
class Meta:
unique_together = (('bioguide_id', 'congress', ))
def __unicode__(self):
return ' '.join([self.prefix, self.first, self.last, self.suffix, ])
|
from django.db import models
class Legislator(models.Model):
"""Model representing a legislator in a session of congress.
"""
bioguide_id = models.CharField(max_length=7, db_index=True)
prefix = models.CharField(max_length=16)
first = models.CharField(max_length=64)
last = models.CharField(max_length=64)
suffix = models.CharField(max_length=16)
birth_death = models.CharField(max_length=16)
position = models.CharField(max_length=24)
party = models.CharField(max_length=32)
state = models.CharField(max_length=2)
congress = models.CharField(max_length=3)
class Meta:
unique_together = (('bioguide_id', 'congress', 'position', ))
def __unicode__(self):
return ' '.join([self.prefix, self.first, self.last, self.suffix, ])
|
Add 'position' to unique_together constraint, to account for members who serve in both houses during a Congress (h/t @derekwillis)
|
Add 'position' to unique_together constraint, to account for members who serve in both houses during a Congress (h/t @derekwillis)
|
Python
|
bsd-3-clause
|
propublica/Capitol-Words,sunlightlabs/Capitol-Words,sunlightlabs/Capitol-Words,sunlightlabs/Capitol-Words,propublica/Capitol-Words,sunlightlabs/Capitol-Words,propublica/Capitol-Words,sunlightlabs/Capitol-Words,sunlightlabs/Capitol-Words,propublica/Capitol-Words,sunlightlabs/Capitol-Words
|
from django.db import models
class Legislator(models.Model):
"""Model representing a legislator in a session of congress.
"""
bioguide_id = models.CharField(max_length=7, db_index=True)
prefix = models.CharField(max_length=16)
first = models.CharField(max_length=64)
last = models.CharField(max_length=64)
suffix = models.CharField(max_length=16)
birth_death = models.CharField(max_length=16)
position = models.CharField(max_length=24)
party = models.CharField(max_length=32)
state = models.CharField(max_length=2)
congress = models.CharField(max_length=3)
class Meta:
unique_together = (('bioguide_id', 'congress', ))
def __unicode__(self):
return ' '.join([self.prefix, self.first, self.last, self.suffix, ])
Add 'position' to unique_together constraint, to account for members who serve in both houses during a Congress (h/t @derekwillis)
|
from django.db import models
class Legislator(models.Model):
"""Model representing a legislator in a session of congress.
"""
bioguide_id = models.CharField(max_length=7, db_index=True)
prefix = models.CharField(max_length=16)
first = models.CharField(max_length=64)
last = models.CharField(max_length=64)
suffix = models.CharField(max_length=16)
birth_death = models.CharField(max_length=16)
position = models.CharField(max_length=24)
party = models.CharField(max_length=32)
state = models.CharField(max_length=2)
congress = models.CharField(max_length=3)
class Meta:
unique_together = (('bioguide_id', 'congress', 'position', ))
def __unicode__(self):
return ' '.join([self.prefix, self.first, self.last, self.suffix, ])
|
<commit_before>from django.db import models
class Legislator(models.Model):
"""Model representing a legislator in a session of congress.
"""
bioguide_id = models.CharField(max_length=7, db_index=True)
prefix = models.CharField(max_length=16)
first = models.CharField(max_length=64)
last = models.CharField(max_length=64)
suffix = models.CharField(max_length=16)
birth_death = models.CharField(max_length=16)
position = models.CharField(max_length=24)
party = models.CharField(max_length=32)
state = models.CharField(max_length=2)
congress = models.CharField(max_length=3)
class Meta:
unique_together = (('bioguide_id', 'congress', ))
def __unicode__(self):
return ' '.join([self.prefix, self.first, self.last, self.suffix, ])
<commit_msg>Add 'position' to unique_together constraint, to account for members who serve in both houses during a Congress (h/t @derekwillis)<commit_after>
|
from django.db import models
class Legislator(models.Model):
"""Model representing a legislator in a session of congress.
"""
bioguide_id = models.CharField(max_length=7, db_index=True)
prefix = models.CharField(max_length=16)
first = models.CharField(max_length=64)
last = models.CharField(max_length=64)
suffix = models.CharField(max_length=16)
birth_death = models.CharField(max_length=16)
position = models.CharField(max_length=24)
party = models.CharField(max_length=32)
state = models.CharField(max_length=2)
congress = models.CharField(max_length=3)
class Meta:
unique_together = (('bioguide_id', 'congress', 'position', ))
def __unicode__(self):
return ' '.join([self.prefix, self.first, self.last, self.suffix, ])
|
from django.db import models
class Legislator(models.Model):
"""Model representing a legislator in a session of congress.
"""
bioguide_id = models.CharField(max_length=7, db_index=True)
prefix = models.CharField(max_length=16)
first = models.CharField(max_length=64)
last = models.CharField(max_length=64)
suffix = models.CharField(max_length=16)
birth_death = models.CharField(max_length=16)
position = models.CharField(max_length=24)
party = models.CharField(max_length=32)
state = models.CharField(max_length=2)
congress = models.CharField(max_length=3)
class Meta:
unique_together = (('bioguide_id', 'congress', ))
def __unicode__(self):
return ' '.join([self.prefix, self.first, self.last, self.suffix, ])
Add 'position' to unique_together constraint, to account for members who serve in both houses during a Congress (h/t @derekwillis)from django.db import models
class Legislator(models.Model):
"""Model representing a legislator in a session of congress.
"""
bioguide_id = models.CharField(max_length=7, db_index=True)
prefix = models.CharField(max_length=16)
first = models.CharField(max_length=64)
last = models.CharField(max_length=64)
suffix = models.CharField(max_length=16)
birth_death = models.CharField(max_length=16)
position = models.CharField(max_length=24)
party = models.CharField(max_length=32)
state = models.CharField(max_length=2)
congress = models.CharField(max_length=3)
class Meta:
unique_together = (('bioguide_id', 'congress', 'position', ))
def __unicode__(self):
return ' '.join([self.prefix, self.first, self.last, self.suffix, ])
|
<commit_before>from django.db import models
class Legislator(models.Model):
"""Model representing a legislator in a session of congress.
"""
bioguide_id = models.CharField(max_length=7, db_index=True)
prefix = models.CharField(max_length=16)
first = models.CharField(max_length=64)
last = models.CharField(max_length=64)
suffix = models.CharField(max_length=16)
birth_death = models.CharField(max_length=16)
position = models.CharField(max_length=24)
party = models.CharField(max_length=32)
state = models.CharField(max_length=2)
congress = models.CharField(max_length=3)
class Meta:
unique_together = (('bioguide_id', 'congress', ))
def __unicode__(self):
return ' '.join([self.prefix, self.first, self.last, self.suffix, ])
<commit_msg>Add 'position' to unique_together constraint, to account for members who serve in both houses during a Congress (h/t @derekwillis)<commit_after>from django.db import models
class Legislator(models.Model):
"""Model representing a legislator in a session of congress.
"""
bioguide_id = models.CharField(max_length=7, db_index=True)
prefix = models.CharField(max_length=16)
first = models.CharField(max_length=64)
last = models.CharField(max_length=64)
suffix = models.CharField(max_length=16)
birth_death = models.CharField(max_length=16)
position = models.CharField(max_length=24)
party = models.CharField(max_length=32)
state = models.CharField(max_length=2)
congress = models.CharField(max_length=3)
class Meta:
unique_together = (('bioguide_id', 'congress', 'position', ))
def __unicode__(self):
return ' '.join([self.prefix, self.first, self.last, self.suffix, ])
|
ee09661f7a40bcecc0dc4d378800a6725a800255
|
GPyOpt/experiment_design/latin_design.py
|
GPyOpt/experiment_design/latin_design.py
|
import numpy as np
from ..core.errors import InvalidConfigError
from .base import ExperimentDesign
from .random_design import RandomDesign
class LatinDesign(ExperimentDesign):
"""
Latin experiment design.
Uses random design for non-continuous variables, and latin hypercube for continuous ones
"""
def __init__(self, space):
if space.has_constraints():
raise InvalidConfigError('Sampling with constraints is not allowed by latin design')
super(LatinDesign, self).__init__(space)
def get_samples(self, init_points_count):
samples = np.empty((init_points_count, self.space.dimensionality))
# Use random design to fill non-continuous variables
random_design = RandomDesign(self.space)
random_design.fill_noncontinous_variables(samples)
if self.space.has_continuous():
bounds = self.space.get_continuous_bounds()
lower_bound = np.asarray(bounds)[:,0].reshape(1, len(bounds))
upper_bound = np.asarray(bounds)[:,1].reshape(1, len(bounds))
diff = upper_bound - lower_bound
from pyDOE import lhs
X_design_aux = lhs(len(self.space.get_continuous_bounds()), init_points_count, criterion='center')
I = np.ones((X_design_aux.shape[0], 1))
X_design = np.dot(I, lower_bound) + X_design_aux * np.dot(I, diff)
samples[:, self.space.get_continuous_dims()] = X_design
return samples
|
import numpy as np
from ..core.errors import InvalidConfigError
from .base import ExperimentDesign
from .random_design import RandomDesign
class LatinDesign(ExperimentDesign):
"""
Latin experiment design.
Uses random design for non-continuous variables, and latin hypercube for continuous ones
"""
def __init__(self, space):
if space.has_constraints():
raise InvalidConfigError('Sampling with constraints is not allowed by latin design')
super(LatinDesign, self).__init__(space)
def get_samples(self, init_points_count, criterion='center'):
samples = np.empty((init_points_count, self.space.dimensionality))
# Use random design to fill non-continuous variables
random_design = RandomDesign(self.space)
random_design.fill_noncontinous_variables(samples)
if self.space.has_continuous():
bounds = self.space.get_continuous_bounds()
lower_bound = np.asarray(bounds)[:,0].reshape(1, len(bounds))
upper_bound = np.asarray(bounds)[:,1].reshape(1, len(bounds))
diff = upper_bound - lower_bound
from pyDOE import lhs
X_design_aux = lhs(len(self.space.get_continuous_bounds()), init_points_count, criterion=criterion)
I = np.ones((X_design_aux.shape[0], 1))
X_design = np.dot(I, lower_bound) + X_design_aux * np.dot(I, diff)
samples[:, self.space.get_continuous_dims()] = X_design
return samples
|
Allow users to choose lhs sampling criteria
|
Allow users to choose lhs sampling criteria
|
Python
|
bsd-3-clause
|
SheffieldML/GPyOpt
|
import numpy as np
from ..core.errors import InvalidConfigError
from .base import ExperimentDesign
from .random_design import RandomDesign
class LatinDesign(ExperimentDesign):
"""
Latin experiment design.
Uses random design for non-continuous variables, and latin hypercube for continuous ones
"""
def __init__(self, space):
if space.has_constraints():
raise InvalidConfigError('Sampling with constraints is not allowed by latin design')
super(LatinDesign, self).__init__(space)
def get_samples(self, init_points_count):
samples = np.empty((init_points_count, self.space.dimensionality))
# Use random design to fill non-continuous variables
random_design = RandomDesign(self.space)
random_design.fill_noncontinous_variables(samples)
if self.space.has_continuous():
bounds = self.space.get_continuous_bounds()
lower_bound = np.asarray(bounds)[:,0].reshape(1, len(bounds))
upper_bound = np.asarray(bounds)[:,1].reshape(1, len(bounds))
diff = upper_bound - lower_bound
from pyDOE import lhs
X_design_aux = lhs(len(self.space.get_continuous_bounds()), init_points_count, criterion='center')
I = np.ones((X_design_aux.shape[0], 1))
X_design = np.dot(I, lower_bound) + X_design_aux * np.dot(I, diff)
samples[:, self.space.get_continuous_dims()] = X_design
return samplesAllow users to choose lhs sampling criteria
|
import numpy as np
from ..core.errors import InvalidConfigError
from .base import ExperimentDesign
from .random_design import RandomDesign
class LatinDesign(ExperimentDesign):
"""
Latin experiment design.
Uses random design for non-continuous variables, and latin hypercube for continuous ones
"""
def __init__(self, space):
if space.has_constraints():
raise InvalidConfigError('Sampling with constraints is not allowed by latin design')
super(LatinDesign, self).__init__(space)
def get_samples(self, init_points_count, criterion='center'):
samples = np.empty((init_points_count, self.space.dimensionality))
# Use random design to fill non-continuous variables
random_design = RandomDesign(self.space)
random_design.fill_noncontinous_variables(samples)
if self.space.has_continuous():
bounds = self.space.get_continuous_bounds()
lower_bound = np.asarray(bounds)[:,0].reshape(1, len(bounds))
upper_bound = np.asarray(bounds)[:,1].reshape(1, len(bounds))
diff = upper_bound - lower_bound
from pyDOE import lhs
X_design_aux = lhs(len(self.space.get_continuous_bounds()), init_points_count, criterion=criterion)
I = np.ones((X_design_aux.shape[0], 1))
X_design = np.dot(I, lower_bound) + X_design_aux * np.dot(I, diff)
samples[:, self.space.get_continuous_dims()] = X_design
return samples
|
<commit_before>import numpy as np
from ..core.errors import InvalidConfigError
from .base import ExperimentDesign
from .random_design import RandomDesign
class LatinDesign(ExperimentDesign):
"""
Latin experiment design.
Uses random design for non-continuous variables, and latin hypercube for continuous ones
"""
def __init__(self, space):
if space.has_constraints():
raise InvalidConfigError('Sampling with constraints is not allowed by latin design')
super(LatinDesign, self).__init__(space)
def get_samples(self, init_points_count):
samples = np.empty((init_points_count, self.space.dimensionality))
# Use random design to fill non-continuous variables
random_design = RandomDesign(self.space)
random_design.fill_noncontinous_variables(samples)
if self.space.has_continuous():
bounds = self.space.get_continuous_bounds()
lower_bound = np.asarray(bounds)[:,0].reshape(1, len(bounds))
upper_bound = np.asarray(bounds)[:,1].reshape(1, len(bounds))
diff = upper_bound - lower_bound
from pyDOE import lhs
X_design_aux = lhs(len(self.space.get_continuous_bounds()), init_points_count, criterion='center')
I = np.ones((X_design_aux.shape[0], 1))
X_design = np.dot(I, lower_bound) + X_design_aux * np.dot(I, diff)
samples[:, self.space.get_continuous_dims()] = X_design
return samples<commit_msg>Allow users to choose lhs sampling criteria<commit_after>
|
import numpy as np
from ..core.errors import InvalidConfigError
from .base import ExperimentDesign
from .random_design import RandomDesign
class LatinDesign(ExperimentDesign):
"""
Latin experiment design.
Uses random design for non-continuous variables, and latin hypercube for continuous ones
"""
def __init__(self, space):
if space.has_constraints():
raise InvalidConfigError('Sampling with constraints is not allowed by latin design')
super(LatinDesign, self).__init__(space)
def get_samples(self, init_points_count, criterion='center'):
samples = np.empty((init_points_count, self.space.dimensionality))
# Use random design to fill non-continuous variables
random_design = RandomDesign(self.space)
random_design.fill_noncontinous_variables(samples)
if self.space.has_continuous():
bounds = self.space.get_continuous_bounds()
lower_bound = np.asarray(bounds)[:,0].reshape(1, len(bounds))
upper_bound = np.asarray(bounds)[:,1].reshape(1, len(bounds))
diff = upper_bound - lower_bound
from pyDOE import lhs
X_design_aux = lhs(len(self.space.get_continuous_bounds()), init_points_count, criterion=criterion)
I = np.ones((X_design_aux.shape[0], 1))
X_design = np.dot(I, lower_bound) + X_design_aux * np.dot(I, diff)
samples[:, self.space.get_continuous_dims()] = X_design
return samples
|
import numpy as np
from ..core.errors import InvalidConfigError
from .base import ExperimentDesign
from .random_design import RandomDesign
class LatinDesign(ExperimentDesign):
"""
Latin experiment design.
Uses random design for non-continuous variables, and latin hypercube for continuous ones
"""
def __init__(self, space):
if space.has_constraints():
raise InvalidConfigError('Sampling with constraints is not allowed by latin design')
super(LatinDesign, self).__init__(space)
def get_samples(self, init_points_count):
samples = np.empty((init_points_count, self.space.dimensionality))
# Use random design to fill non-continuous variables
random_design = RandomDesign(self.space)
random_design.fill_noncontinous_variables(samples)
if self.space.has_continuous():
bounds = self.space.get_continuous_bounds()
lower_bound = np.asarray(bounds)[:,0].reshape(1, len(bounds))
upper_bound = np.asarray(bounds)[:,1].reshape(1, len(bounds))
diff = upper_bound - lower_bound
from pyDOE import lhs
X_design_aux = lhs(len(self.space.get_continuous_bounds()), init_points_count, criterion='center')
I = np.ones((X_design_aux.shape[0], 1))
X_design = np.dot(I, lower_bound) + X_design_aux * np.dot(I, diff)
samples[:, self.space.get_continuous_dims()] = X_design
return samplesAllow users to choose lhs sampling criteriaimport numpy as np
from ..core.errors import InvalidConfigError
from .base import ExperimentDesign
from .random_design import RandomDesign
class LatinDesign(ExperimentDesign):
"""
Latin experiment design.
Uses random design for non-continuous variables, and latin hypercube for continuous ones
"""
def __init__(self, space):
if space.has_constraints():
raise InvalidConfigError('Sampling with constraints is not allowed by latin design')
super(LatinDesign, self).__init__(space)
def get_samples(self, init_points_count, criterion='center'):
samples = np.empty((init_points_count, self.space.dimensionality))
# Use random design to fill non-continuous variables
random_design = RandomDesign(self.space)
random_design.fill_noncontinous_variables(samples)
if self.space.has_continuous():
bounds = self.space.get_continuous_bounds()
lower_bound = np.asarray(bounds)[:,0].reshape(1, len(bounds))
upper_bound = np.asarray(bounds)[:,1].reshape(1, len(bounds))
diff = upper_bound - lower_bound
from pyDOE import lhs
X_design_aux = lhs(len(self.space.get_continuous_bounds()), init_points_count, criterion=criterion)
I = np.ones((X_design_aux.shape[0], 1))
X_design = np.dot(I, lower_bound) + X_design_aux * np.dot(I, diff)
samples[:, self.space.get_continuous_dims()] = X_design
return samples
|
<commit_before>import numpy as np
from ..core.errors import InvalidConfigError
from .base import ExperimentDesign
from .random_design import RandomDesign
class LatinDesign(ExperimentDesign):
"""
Latin experiment design.
Uses random design for non-continuous variables, and latin hypercube for continuous ones
"""
def __init__(self, space):
if space.has_constraints():
raise InvalidConfigError('Sampling with constraints is not allowed by latin design')
super(LatinDesign, self).__init__(space)
def get_samples(self, init_points_count):
samples = np.empty((init_points_count, self.space.dimensionality))
# Use random design to fill non-continuous variables
random_design = RandomDesign(self.space)
random_design.fill_noncontinous_variables(samples)
if self.space.has_continuous():
bounds = self.space.get_continuous_bounds()
lower_bound = np.asarray(bounds)[:,0].reshape(1, len(bounds))
upper_bound = np.asarray(bounds)[:,1].reshape(1, len(bounds))
diff = upper_bound - lower_bound
from pyDOE import lhs
X_design_aux = lhs(len(self.space.get_continuous_bounds()), init_points_count, criterion='center')
I = np.ones((X_design_aux.shape[0], 1))
X_design = np.dot(I, lower_bound) + X_design_aux * np.dot(I, diff)
samples[:, self.space.get_continuous_dims()] = X_design
return samples<commit_msg>Allow users to choose lhs sampling criteria<commit_after>import numpy as np
from ..core.errors import InvalidConfigError
from .base import ExperimentDesign
from .random_design import RandomDesign
class LatinDesign(ExperimentDesign):
"""
Latin experiment design.
Uses random design for non-continuous variables, and latin hypercube for continuous ones
"""
def __init__(self, space):
if space.has_constraints():
raise InvalidConfigError('Sampling with constraints is not allowed by latin design')
super(LatinDesign, self).__init__(space)
def get_samples(self, init_points_count, criterion='center'):
samples = np.empty((init_points_count, self.space.dimensionality))
# Use random design to fill non-continuous variables
random_design = RandomDesign(self.space)
random_design.fill_noncontinous_variables(samples)
if self.space.has_continuous():
bounds = self.space.get_continuous_bounds()
lower_bound = np.asarray(bounds)[:,0].reshape(1, len(bounds))
upper_bound = np.asarray(bounds)[:,1].reshape(1, len(bounds))
diff = upper_bound - lower_bound
from pyDOE import lhs
X_design_aux = lhs(len(self.space.get_continuous_bounds()), init_points_count, criterion=criterion)
I = np.ones((X_design_aux.shape[0], 1))
X_design = np.dot(I, lower_bound) + X_design_aux * np.dot(I, diff)
samples[:, self.space.get_continuous_dims()] = X_design
return samples
|
c2bb36ea80c44d836c3913fadd5b92c24f871dc6
|
dj_geocoding/admin.py
|
dj_geocoding/admin.py
|
from django.utils.translation import ugettext_lazy as _
from django.contrib.admin import SimpleListFilter
class GeocodedFilter(SimpleListFilter):
"""
Admin list filter for filtering locations by whether they have
[complete] geolocation data.
"""
title = _('geocoded')
parameter_name = 'geocoded'
def lookups(self, request, model_admin):
return (
('1', _('Yes')),
('0', _('No')),
)
def queryset(self, request, queryset):
"""
Returns queryset of locations based on whether the locations
have complete geolocation data (latitude and longitude) or
those that lack complete geolocation data (none or only one).
"""
if self.value() == '1':
return queryset.filter(latitude__isnull=False, longitude__isnull=False)
if self.value() == '0':
return queryset.exclude(latitude__isnull=False, longitude__isnull=False)
class GeolocateMixin(object):
"""
ModelAdmin class mixin for adding a simple geocoding interface to the
Django admin.
"""
actions = ['geocode_address']
def geocode_address(self, request, queryset):
"""
Make a request from Google via the Maps API to get the lat/lng
locations for the selected locations.
"""
try:
geocoded = queryset.geocode()
except AttributeError:
# TODO Add a helpful error message here
raise
self.message_user(request,
_("Geocoded {0} locations".format(len(geocoded))))
|
from django.utils.translation import ugettext_lazy as _
from django.contrib.admin import SimpleListFilter
from .utils import bulk_geocode
class GeocodedFilter(SimpleListFilter):
"""
Admin list filter for filtering locations by whether they have
[complete] geolocation data.
"""
title = _('geocoded')
parameter_name = 'geocoded'
def lookups(self, request, model_admin):
return (
('1', _('Yes')),
('0', _('No')),
)
def queryset(self, request, queryset):
"""
Returns queryset of locations based on whether the locations
have complete geolocation data (latitude and longitude) or
those that lack complete geolocation data (none or only one).
"""
if self.value() == '1':
return queryset.filter(latitude__isnull=False, longitude__isnull=False)
if self.value() == '0':
return queryset.exclude(latitude__isnull=False, longitude__isnull=False)
class GeolocateMixin(object):
"""
ModelAdmin class mixin for adding a simple geocoding interface to the
Django admin.
"""
actions = ['geocode_address']
def geocode_address(self, request, queryset):
"""
Make a request from Google via the Maps API to get the lat/lng
locations for the selected locations.
"""
try:
geocoded = bulk_geocode(queryset)
except AttributeError:
# TODO Add a helpful error message here
raise
self.message_user(request,
_("Geocoded {0} locations".format(len(geocoded))))
|
Remove reliance on queryset based geocoding method
|
Remove reliance on queryset based geocoding method
|
Python
|
bsd-3-clause
|
bennylope/dj-geocoding
|
from django.utils.translation import ugettext_lazy as _
from django.contrib.admin import SimpleListFilter
class GeocodedFilter(SimpleListFilter):
"""
Admin list filter for filtering locations by whether they have
[complete] geolocation data.
"""
title = _('geocoded')
parameter_name = 'geocoded'
def lookups(self, request, model_admin):
return (
('1', _('Yes')),
('0', _('No')),
)
def queryset(self, request, queryset):
"""
Returns queryset of locations based on whether the locations
have complete geolocation data (latitude and longitude) or
those that lack complete geolocation data (none or only one).
"""
if self.value() == '1':
return queryset.filter(latitude__isnull=False, longitude__isnull=False)
if self.value() == '0':
return queryset.exclude(latitude__isnull=False, longitude__isnull=False)
class GeolocateMixin(object):
"""
ModelAdmin class mixin for adding a simple geocoding interface to the
Django admin.
"""
actions = ['geocode_address']
def geocode_address(self, request, queryset):
"""
Make a request from Google via the Maps API to get the lat/lng
locations for the selected locations.
"""
try:
geocoded = queryset.geocode()
except AttributeError:
# TODO Add a helpful error message here
raise
self.message_user(request,
_("Geocoded {0} locations".format(len(geocoded))))
Remove reliance on queryset based geocoding method
|
from django.utils.translation import ugettext_lazy as _
from django.contrib.admin import SimpleListFilter
from .utils import bulk_geocode
class GeocodedFilter(SimpleListFilter):
"""
Admin list filter for filtering locations by whether they have
[complete] geolocation data.
"""
title = _('geocoded')
parameter_name = 'geocoded'
def lookups(self, request, model_admin):
return (
('1', _('Yes')),
('0', _('No')),
)
def queryset(self, request, queryset):
"""
Returns queryset of locations based on whether the locations
have complete geolocation data (latitude and longitude) or
those that lack complete geolocation data (none or only one).
"""
if self.value() == '1':
return queryset.filter(latitude__isnull=False, longitude__isnull=False)
if self.value() == '0':
return queryset.exclude(latitude__isnull=False, longitude__isnull=False)
class GeolocateMixin(object):
"""
ModelAdmin class mixin for adding a simple geocoding interface to the
Django admin.
"""
actions = ['geocode_address']
def geocode_address(self, request, queryset):
"""
Make a request from Google via the Maps API to get the lat/lng
locations for the selected locations.
"""
try:
geocoded = bulk_geocode(queryset)
except AttributeError:
# TODO Add a helpful error message here
raise
self.message_user(request,
_("Geocoded {0} locations".format(len(geocoded))))
|
<commit_before>from django.utils.translation import ugettext_lazy as _
from django.contrib.admin import SimpleListFilter
class GeocodedFilter(SimpleListFilter):
"""
Admin list filter for filtering locations by whether they have
[complete] geolocation data.
"""
title = _('geocoded')
parameter_name = 'geocoded'
def lookups(self, request, model_admin):
return (
('1', _('Yes')),
('0', _('No')),
)
def queryset(self, request, queryset):
"""
Returns queryset of locations based on whether the locations
have complete geolocation data (latitude and longitude) or
those that lack complete geolocation data (none or only one).
"""
if self.value() == '1':
return queryset.filter(latitude__isnull=False, longitude__isnull=False)
if self.value() == '0':
return queryset.exclude(latitude__isnull=False, longitude__isnull=False)
class GeolocateMixin(object):
"""
ModelAdmin class mixin for adding a simple geocoding interface to the
Django admin.
"""
actions = ['geocode_address']
def geocode_address(self, request, queryset):
"""
Make a request from Google via the Maps API to get the lat/lng
locations for the selected locations.
"""
try:
geocoded = queryset.geocode()
except AttributeError:
# TODO Add a helpful error message here
raise
self.message_user(request,
_("Geocoded {0} locations".format(len(geocoded))))
<commit_msg>Remove reliance on queryset based geocoding method<commit_after>
|
from django.utils.translation import ugettext_lazy as _
from django.contrib.admin import SimpleListFilter
from .utils import bulk_geocode
class GeocodedFilter(SimpleListFilter):
"""
Admin list filter for filtering locations by whether they have
[complete] geolocation data.
"""
title = _('geocoded')
parameter_name = 'geocoded'
def lookups(self, request, model_admin):
return (
('1', _('Yes')),
('0', _('No')),
)
def queryset(self, request, queryset):
"""
Returns queryset of locations based on whether the locations
have complete geolocation data (latitude and longitude) or
those that lack complete geolocation data (none or only one).
"""
if self.value() == '1':
return queryset.filter(latitude__isnull=False, longitude__isnull=False)
if self.value() == '0':
return queryset.exclude(latitude__isnull=False, longitude__isnull=False)
class GeolocateMixin(object):
"""
ModelAdmin class mixin for adding a simple geocoding interface to the
Django admin.
"""
actions = ['geocode_address']
def geocode_address(self, request, queryset):
"""
Make a request from Google via the Maps API to get the lat/lng
locations for the selected locations.
"""
try:
geocoded = bulk_geocode(queryset)
except AttributeError:
# TODO Add a helpful error message here
raise
self.message_user(request,
_("Geocoded {0} locations".format(len(geocoded))))
|
from django.utils.translation import ugettext_lazy as _
from django.contrib.admin import SimpleListFilter
class GeocodedFilter(SimpleListFilter):
"""
Admin list filter for filtering locations by whether they have
[complete] geolocation data.
"""
title = _('geocoded')
parameter_name = 'geocoded'
def lookups(self, request, model_admin):
return (
('1', _('Yes')),
('0', _('No')),
)
def queryset(self, request, queryset):
"""
Returns queryset of locations based on whether the locations
have complete geolocation data (latitude and longitude) or
those that lack complete geolocation data (none or only one).
"""
if self.value() == '1':
return queryset.filter(latitude__isnull=False, longitude__isnull=False)
if self.value() == '0':
return queryset.exclude(latitude__isnull=False, longitude__isnull=False)
class GeolocateMixin(object):
"""
ModelAdmin class mixin for adding a simple geocoding interface to the
Django admin.
"""
actions = ['geocode_address']
def geocode_address(self, request, queryset):
"""
Make a request from Google via the Maps API to get the lat/lng
locations for the selected locations.
"""
try:
geocoded = queryset.geocode()
except AttributeError:
# TODO Add a helpful error message here
raise
self.message_user(request,
_("Geocoded {0} locations".format(len(geocoded))))
Remove reliance on queryset based geocoding methodfrom django.utils.translation import ugettext_lazy as _
from django.contrib.admin import SimpleListFilter
from .utils import bulk_geocode
class GeocodedFilter(SimpleListFilter):
"""
Admin list filter for filtering locations by whether they have
[complete] geolocation data.
"""
title = _('geocoded')
parameter_name = 'geocoded'
def lookups(self, request, model_admin):
return (
('1', _('Yes')),
('0', _('No')),
)
def queryset(self, request, queryset):
"""
Returns queryset of locations based on whether the locations
have complete geolocation data (latitude and longitude) or
those that lack complete geolocation data (none or only one).
"""
if self.value() == '1':
return queryset.filter(latitude__isnull=False, longitude__isnull=False)
if self.value() == '0':
return queryset.exclude(latitude__isnull=False, longitude__isnull=False)
class GeolocateMixin(object):
"""
ModelAdmin class mixin for adding a simple geocoding interface to the
Django admin.
"""
actions = ['geocode_address']
def geocode_address(self, request, queryset):
"""
Make a request from Google via the Maps API to get the lat/lng
locations for the selected locations.
"""
try:
geocoded = bulk_geocode(queryset)
except AttributeError:
# TODO Add a helpful error message here
raise
self.message_user(request,
_("Geocoded {0} locations".format(len(geocoded))))
|
<commit_before>from django.utils.translation import ugettext_lazy as _
from django.contrib.admin import SimpleListFilter
class GeocodedFilter(SimpleListFilter):
"""
Admin list filter for filtering locations by whether they have
[complete] geolocation data.
"""
title = _('geocoded')
parameter_name = 'geocoded'
def lookups(self, request, model_admin):
return (
('1', _('Yes')),
('0', _('No')),
)
def queryset(self, request, queryset):
"""
Returns queryset of locations based on whether the locations
have complete geolocation data (latitude and longitude) or
those that lack complete geolocation data (none or only one).
"""
if self.value() == '1':
return queryset.filter(latitude__isnull=False, longitude__isnull=False)
if self.value() == '0':
return queryset.exclude(latitude__isnull=False, longitude__isnull=False)
class GeolocateMixin(object):
"""
ModelAdmin class mixin for adding a simple geocoding interface to the
Django admin.
"""
actions = ['geocode_address']
def geocode_address(self, request, queryset):
"""
Make a request from Google via the Maps API to get the lat/lng
locations for the selected locations.
"""
try:
geocoded = queryset.geocode()
except AttributeError:
# TODO Add a helpful error message here
raise
self.message_user(request,
_("Geocoded {0} locations".format(len(geocoded))))
<commit_msg>Remove reliance on queryset based geocoding method<commit_after>from django.utils.translation import ugettext_lazy as _
from django.contrib.admin import SimpleListFilter
from .utils import bulk_geocode
class GeocodedFilter(SimpleListFilter):
"""
Admin list filter for filtering locations by whether they have
[complete] geolocation data.
"""
title = _('geocoded')
parameter_name = 'geocoded'
def lookups(self, request, model_admin):
return (
('1', _('Yes')),
('0', _('No')),
)
def queryset(self, request, queryset):
"""
Returns queryset of locations based on whether the locations
have complete geolocation data (latitude and longitude) or
those that lack complete geolocation data (none or only one).
"""
if self.value() == '1':
return queryset.filter(latitude__isnull=False, longitude__isnull=False)
if self.value() == '0':
return queryset.exclude(latitude__isnull=False, longitude__isnull=False)
class GeolocateMixin(object):
"""
ModelAdmin class mixin for adding a simple geocoding interface to the
Django admin.
"""
actions = ['geocode_address']
def geocode_address(self, request, queryset):
"""
Make a request from Google via the Maps API to get the lat/lng
locations for the selected locations.
"""
try:
geocoded = bulk_geocode(queryset)
except AttributeError:
# TODO Add a helpful error message here
raise
self.message_user(request,
_("Geocoded {0} locations".format(len(geocoded))))
|
5a6399e8c25e5c4bb71a6fa4914b38ea6c66a3eb
|
forms/iforms.py
|
forms/iforms.py
|
from nevow.compy import Interface
class IType(Interface):
def validate(self, value):
pass
class IStructure(Interface):
pass
class IWidget(Interface):
def render(self, ctx, key, args, errors):
pass
def processInput(self, ctx, key, args):
pass
class IFormFactory(Interface):
def formFactory(self, ctx, name):
pass
class IFormData(Interface):
pass
class IFormErrors(Interface):
pass
class IKey(Interface):
def key(self):
pass
class ILabel(Interface):
def label(self):
pass
class IConvertible(Interface):
def fromType(self, value):
pass
def toType(self, value):
pass
class IStringConvertible(IConvertible):
pass
class IBooleanConvertible(IConvertible):
pass
class IDateTupleConvertible(IConvertible):
pass
class IFileConvertible(IConvertible):
pass
class ISequenceConvertible(IConvertible):
pass
class IForm( Interface ):
pass
class IValidator(Interface):
def validate(self, field, value):
pass
|
from nevow.compy import Interface
class IType(Interface):
def validate(self, value):
pass
class IStructure(Interface):
pass
class IWidget(Interface):
def render(self, ctx, key, args, errors):
pass
def renderImmutable(self, ctx, key, args, errors):
pass
def processInput(self, ctx, key, args):
pass
class IFormFactory(Interface):
def formFactory(self, ctx, name):
pass
class IFormData(Interface):
pass
class IFormErrors(Interface):
pass
class IKey(Interface):
def key(self):
pass
class ILabel(Interface):
def label(self):
pass
class IConvertible(Interface):
def fromType(self, value):
pass
def toType(self, value):
pass
class IStringConvertible(IConvertible):
pass
class IBooleanConvertible(IConvertible):
pass
class IDateTupleConvertible(IConvertible):
pass
class IFileConvertible(IConvertible):
pass
class ISequenceConvertible(IConvertible):
pass
class IForm( Interface ):
pass
class IValidator(Interface):
def validate(self, field, value):
pass
|
Add missing method to interface
|
Add missing method to interface
|
Python
|
mit
|
emgee/formal,emgee/formal,emgee/formal
|
from nevow.compy import Interface
class IType(Interface):
def validate(self, value):
pass
class IStructure(Interface):
pass
class IWidget(Interface):
def render(self, ctx, key, args, errors):
pass
def processInput(self, ctx, key, args):
pass
class IFormFactory(Interface):
def formFactory(self, ctx, name):
pass
class IFormData(Interface):
pass
class IFormErrors(Interface):
pass
class IKey(Interface):
def key(self):
pass
class ILabel(Interface):
def label(self):
pass
class IConvertible(Interface):
def fromType(self, value):
pass
def toType(self, value):
pass
class IStringConvertible(IConvertible):
pass
class IBooleanConvertible(IConvertible):
pass
class IDateTupleConvertible(IConvertible):
pass
class IFileConvertible(IConvertible):
pass
class ISequenceConvertible(IConvertible):
pass
class IForm( Interface ):
pass
class IValidator(Interface):
def validate(self, field, value):
pass
Add missing method to interface
|
from nevow.compy import Interface
class IType(Interface):
def validate(self, value):
pass
class IStructure(Interface):
pass
class IWidget(Interface):
def render(self, ctx, key, args, errors):
pass
def renderImmutable(self, ctx, key, args, errors):
pass
def processInput(self, ctx, key, args):
pass
class IFormFactory(Interface):
def formFactory(self, ctx, name):
pass
class IFormData(Interface):
pass
class IFormErrors(Interface):
pass
class IKey(Interface):
def key(self):
pass
class ILabel(Interface):
def label(self):
pass
class IConvertible(Interface):
def fromType(self, value):
pass
def toType(self, value):
pass
class IStringConvertible(IConvertible):
pass
class IBooleanConvertible(IConvertible):
pass
class IDateTupleConvertible(IConvertible):
pass
class IFileConvertible(IConvertible):
pass
class ISequenceConvertible(IConvertible):
pass
class IForm( Interface ):
pass
class IValidator(Interface):
def validate(self, field, value):
pass
|
<commit_before>from nevow.compy import Interface
class IType(Interface):
def validate(self, value):
pass
class IStructure(Interface):
pass
class IWidget(Interface):
def render(self, ctx, key, args, errors):
pass
def processInput(self, ctx, key, args):
pass
class IFormFactory(Interface):
def formFactory(self, ctx, name):
pass
class IFormData(Interface):
pass
class IFormErrors(Interface):
pass
class IKey(Interface):
def key(self):
pass
class ILabel(Interface):
def label(self):
pass
class IConvertible(Interface):
def fromType(self, value):
pass
def toType(self, value):
pass
class IStringConvertible(IConvertible):
pass
class IBooleanConvertible(IConvertible):
pass
class IDateTupleConvertible(IConvertible):
pass
class IFileConvertible(IConvertible):
pass
class ISequenceConvertible(IConvertible):
pass
class IForm( Interface ):
pass
class IValidator(Interface):
def validate(self, field, value):
pass
<commit_msg>Add missing method to interface<commit_after>
|
from nevow.compy import Interface
class IType(Interface):
def validate(self, value):
pass
class IStructure(Interface):
pass
class IWidget(Interface):
def render(self, ctx, key, args, errors):
pass
def renderImmutable(self, ctx, key, args, errors):
pass
def processInput(self, ctx, key, args):
pass
class IFormFactory(Interface):
def formFactory(self, ctx, name):
pass
class IFormData(Interface):
pass
class IFormErrors(Interface):
pass
class IKey(Interface):
def key(self):
pass
class ILabel(Interface):
def label(self):
pass
class IConvertible(Interface):
def fromType(self, value):
pass
def toType(self, value):
pass
class IStringConvertible(IConvertible):
pass
class IBooleanConvertible(IConvertible):
pass
class IDateTupleConvertible(IConvertible):
pass
class IFileConvertible(IConvertible):
pass
class ISequenceConvertible(IConvertible):
pass
class IForm( Interface ):
pass
class IValidator(Interface):
def validate(self, field, value):
pass
|
from nevow.compy import Interface
class IType(Interface):
def validate(self, value):
pass
class IStructure(Interface):
pass
class IWidget(Interface):
def render(self, ctx, key, args, errors):
pass
def processInput(self, ctx, key, args):
pass
class IFormFactory(Interface):
def formFactory(self, ctx, name):
pass
class IFormData(Interface):
pass
class IFormErrors(Interface):
pass
class IKey(Interface):
def key(self):
pass
class ILabel(Interface):
def label(self):
pass
class IConvertible(Interface):
def fromType(self, value):
pass
def toType(self, value):
pass
class IStringConvertible(IConvertible):
pass
class IBooleanConvertible(IConvertible):
pass
class IDateTupleConvertible(IConvertible):
pass
class IFileConvertible(IConvertible):
pass
class ISequenceConvertible(IConvertible):
pass
class IForm( Interface ):
pass
class IValidator(Interface):
def validate(self, field, value):
pass
Add missing method to interfacefrom nevow.compy import Interface
class IType(Interface):
def validate(self, value):
pass
class IStructure(Interface):
pass
class IWidget(Interface):
def render(self, ctx, key, args, errors):
pass
def renderImmutable(self, ctx, key, args, errors):
pass
def processInput(self, ctx, key, args):
pass
class IFormFactory(Interface):
def formFactory(self, ctx, name):
pass
class IFormData(Interface):
pass
class IFormErrors(Interface):
pass
class IKey(Interface):
def key(self):
pass
class ILabel(Interface):
def label(self):
pass
class IConvertible(Interface):
def fromType(self, value):
pass
def toType(self, value):
pass
class IStringConvertible(IConvertible):
pass
class IBooleanConvertible(IConvertible):
pass
class IDateTupleConvertible(IConvertible):
pass
class IFileConvertible(IConvertible):
pass
class ISequenceConvertible(IConvertible):
pass
class IForm( Interface ):
pass
class IValidator(Interface):
def validate(self, field, value):
pass
|
<commit_before>from nevow.compy import Interface
class IType(Interface):
def validate(self, value):
pass
class IStructure(Interface):
pass
class IWidget(Interface):
def render(self, ctx, key, args, errors):
pass
def processInput(self, ctx, key, args):
pass
class IFormFactory(Interface):
def formFactory(self, ctx, name):
pass
class IFormData(Interface):
pass
class IFormErrors(Interface):
pass
class IKey(Interface):
def key(self):
pass
class ILabel(Interface):
def label(self):
pass
class IConvertible(Interface):
def fromType(self, value):
pass
def toType(self, value):
pass
class IStringConvertible(IConvertible):
pass
class IBooleanConvertible(IConvertible):
pass
class IDateTupleConvertible(IConvertible):
pass
class IFileConvertible(IConvertible):
pass
class ISequenceConvertible(IConvertible):
pass
class IForm( Interface ):
pass
class IValidator(Interface):
def validate(self, field, value):
pass
<commit_msg>Add missing method to interface<commit_after>from nevow.compy import Interface
class IType(Interface):
def validate(self, value):
pass
class IStructure(Interface):
pass
class IWidget(Interface):
def render(self, ctx, key, args, errors):
pass
def renderImmutable(self, ctx, key, args, errors):
pass
def processInput(self, ctx, key, args):
pass
class IFormFactory(Interface):
def formFactory(self, ctx, name):
pass
class IFormData(Interface):
pass
class IFormErrors(Interface):
pass
class IKey(Interface):
def key(self):
pass
class ILabel(Interface):
def label(self):
pass
class IConvertible(Interface):
def fromType(self, value):
pass
def toType(self, value):
pass
class IStringConvertible(IConvertible):
pass
class IBooleanConvertible(IConvertible):
pass
class IDateTupleConvertible(IConvertible):
pass
class IFileConvertible(IConvertible):
pass
class ISequenceConvertible(IConvertible):
pass
class IForm( Interface ):
pass
class IValidator(Interface):
def validate(self, field, value):
pass
|
c16edd2f00a45829563dad1a8072bc65418bd528
|
test/validate_test.py
|
test/validate_test.py
|
#! /usr/bin/python
import jsonschema
import json
import sys
import os
import glob
vm_schema = json.loads(open("vm.schema.json").read());
def validate_vm_spec(filename):
# Load and parse as JSON
try:
vm_spec = json.loads(open(filename).read())
except:
raise Exception("JSON load / parse Error for " + filename)
# Validate JSON according to schema
try:
jsonschema.validate(vm_spec, vm_schema)
except Exception as err:
raise Exception("JSON schema validation failed: " + err.message)
def has_required_stuff(path):
# Certain files are mandatory
required_files = [ "Makefile", "test.py", "README.md", "*.cpp" ]
for file in required_files:
if not glob.glob(file):
raise Exception("missing " + file)
# JSON-files must conform to VM-schema
for json in glob.glob("*.json"):
validate_vm_spec(json)
path = sys.argv[1] if len(sys.argv) > 1 else "."
os.chdir(path)
try:
has_required_stuff(path)
print "\tPASS: ",os.getcwd()
except Exception as err:
print "\tFAIL: unmet requirements in " + path, ": " , err.message
|
#! /usr/bin/python
import jsonschema
import json
import sys
import os
import glob
vm_schema = None
jsons = []
valid_vms = []
def load_schema(filename):
global vm_schema
vm_schema = json.loads(open(filename).read());
def validate_vm_spec(filename):
global valid_vms
vm_spec = None
# Load and parse as JSON
try:
vm_spec = json.loads(open(filename).read())
except:
raise Exception("JSON load / parse Error for " + filename)
# Validate JSON according to schema
try:
jsonschema.validate(vm_spec, vm_schema)
except Exception as err:
raise Exception("JSON schema validation failed: " + err.message)
valid_vms.append(vm_spec)
def has_required_stuff(path):
global jsons
# Certain files are mandatory
required_files = [ "Makefile", "test.py", "README.md", "*.cpp" ]
for file in required_files:
if not glob.glob(file):
raise Exception("missing " + file)
# JSON-files must conform to VM-schema
jsons = glob.glob("*.json")
for json in jsons:
validate_vm_spec(json)
if __name__ == "__main__":
path = sys.argv[1] if len(sys.argv) > 1 else "."
load_schema("vm.schema.json")
os.chdir(path)
try:
has_required_stuff(path)
print "<validate_test> \tPASS: ",os.getcwd()
except Exception as err:
print "<validate_test> \tFAIL: unmet requirements in " + path, ": " , err.message
|
Test validator can now be used as a module
|
Test validator can now be used as a module
|
Python
|
apache-2.0
|
alfred-bratterud/IncludeOS,AndreasAakesson/IncludeOS,AndreasAakesson/IncludeOS,alfred-bratterud/IncludeOS,mnordsletten/IncludeOS,alfred-bratterud/IncludeOS,ingve/IncludeOS,hioa-cs/IncludeOS,AndreasAakesson/IncludeOS,hioa-cs/IncludeOS,AndreasAakesson/IncludeOS,AnnikaH/IncludeOS,AndreasAakesson/IncludeOS,mnordsletten/IncludeOS,AnnikaH/IncludeOS,alfred-bratterud/IncludeOS,mnordsletten/IncludeOS,mnordsletten/IncludeOS,ingve/IncludeOS,ingve/IncludeOS,hioa-cs/IncludeOS,AndreasAakesson/IncludeOS,mnordsletten/IncludeOS,ingve/IncludeOS,AnnikaH/IncludeOS,mnordsletten/IncludeOS,ingve/IncludeOS,hioa-cs/IncludeOS,AnnikaH/IncludeOS,hioa-cs/IncludeOS,alfred-bratterud/IncludeOS,AnnikaH/IncludeOS
|
#! /usr/bin/python
import jsonschema
import json
import sys
import os
import glob
vm_schema = json.loads(open("vm.schema.json").read());
def validate_vm_spec(filename):
# Load and parse as JSON
try:
vm_spec = json.loads(open(filename).read())
except:
raise Exception("JSON load / parse Error for " + filename)
# Validate JSON according to schema
try:
jsonschema.validate(vm_spec, vm_schema)
except Exception as err:
raise Exception("JSON schema validation failed: " + err.message)
def has_required_stuff(path):
# Certain files are mandatory
required_files = [ "Makefile", "test.py", "README.md", "*.cpp" ]
for file in required_files:
if not glob.glob(file):
raise Exception("missing " + file)
# JSON-files must conform to VM-schema
for json in glob.glob("*.json"):
validate_vm_spec(json)
path = sys.argv[1] if len(sys.argv) > 1 else "."
os.chdir(path)
try:
has_required_stuff(path)
print "\tPASS: ",os.getcwd()
except Exception as err:
print "\tFAIL: unmet requirements in " + path, ": " , err.message
Test validator can now be used as a module
|
#! /usr/bin/python
import jsonschema
import json
import sys
import os
import glob
vm_schema = None
jsons = []
valid_vms = []
def load_schema(filename):
global vm_schema
vm_schema = json.loads(open(filename).read());
def validate_vm_spec(filename):
global valid_vms
vm_spec = None
# Load and parse as JSON
try:
vm_spec = json.loads(open(filename).read())
except:
raise Exception("JSON load / parse Error for " + filename)
# Validate JSON according to schema
try:
jsonschema.validate(vm_spec, vm_schema)
except Exception as err:
raise Exception("JSON schema validation failed: " + err.message)
valid_vms.append(vm_spec)
def has_required_stuff(path):
global jsons
# Certain files are mandatory
required_files = [ "Makefile", "test.py", "README.md", "*.cpp" ]
for file in required_files:
if not glob.glob(file):
raise Exception("missing " + file)
# JSON-files must conform to VM-schema
jsons = glob.glob("*.json")
for json in jsons:
validate_vm_spec(json)
if __name__ == "__main__":
path = sys.argv[1] if len(sys.argv) > 1 else "."
load_schema("vm.schema.json")
os.chdir(path)
try:
has_required_stuff(path)
print "<validate_test> \tPASS: ",os.getcwd()
except Exception as err:
print "<validate_test> \tFAIL: unmet requirements in " + path, ": " , err.message
|
<commit_before>#! /usr/bin/python
import jsonschema
import json
import sys
import os
import glob
vm_schema = json.loads(open("vm.schema.json").read());
def validate_vm_spec(filename):
# Load and parse as JSON
try:
vm_spec = json.loads(open(filename).read())
except:
raise Exception("JSON load / parse Error for " + filename)
# Validate JSON according to schema
try:
jsonschema.validate(vm_spec, vm_schema)
except Exception as err:
raise Exception("JSON schema validation failed: " + err.message)
def has_required_stuff(path):
# Certain files are mandatory
required_files = [ "Makefile", "test.py", "README.md", "*.cpp" ]
for file in required_files:
if not glob.glob(file):
raise Exception("missing " + file)
# JSON-files must conform to VM-schema
for json in glob.glob("*.json"):
validate_vm_spec(json)
path = sys.argv[1] if len(sys.argv) > 1 else "."
os.chdir(path)
try:
has_required_stuff(path)
print "\tPASS: ",os.getcwd()
except Exception as err:
print "\tFAIL: unmet requirements in " + path, ": " , err.message
<commit_msg>Test validator can now be used as a module<commit_after>
|
#! /usr/bin/python
import jsonschema
import json
import sys
import os
import glob
vm_schema = None
jsons = []
valid_vms = []
def load_schema(filename):
global vm_schema
vm_schema = json.loads(open(filename).read());
def validate_vm_spec(filename):
global valid_vms
vm_spec = None
# Load and parse as JSON
try:
vm_spec = json.loads(open(filename).read())
except:
raise Exception("JSON load / parse Error for " + filename)
# Validate JSON according to schema
try:
jsonschema.validate(vm_spec, vm_schema)
except Exception as err:
raise Exception("JSON schema validation failed: " + err.message)
valid_vms.append(vm_spec)
def has_required_stuff(path):
global jsons
# Certain files are mandatory
required_files = [ "Makefile", "test.py", "README.md", "*.cpp" ]
for file in required_files:
if not glob.glob(file):
raise Exception("missing " + file)
# JSON-files must conform to VM-schema
jsons = glob.glob("*.json")
for json in jsons:
validate_vm_spec(json)
if __name__ == "__main__":
path = sys.argv[1] if len(sys.argv) > 1 else "."
load_schema("vm.schema.json")
os.chdir(path)
try:
has_required_stuff(path)
print "<validate_test> \tPASS: ",os.getcwd()
except Exception as err:
print "<validate_test> \tFAIL: unmet requirements in " + path, ": " , err.message
|
#! /usr/bin/python
import jsonschema
import json
import sys
import os
import glob
vm_schema = json.loads(open("vm.schema.json").read());
def validate_vm_spec(filename):
# Load and parse as JSON
try:
vm_spec = json.loads(open(filename).read())
except:
raise Exception("JSON load / parse Error for " + filename)
# Validate JSON according to schema
try:
jsonschema.validate(vm_spec, vm_schema)
except Exception as err:
raise Exception("JSON schema validation failed: " + err.message)
def has_required_stuff(path):
# Certain files are mandatory
required_files = [ "Makefile", "test.py", "README.md", "*.cpp" ]
for file in required_files:
if not glob.glob(file):
raise Exception("missing " + file)
# JSON-files must conform to VM-schema
for json in glob.glob("*.json"):
validate_vm_spec(json)
path = sys.argv[1] if len(sys.argv) > 1 else "."
os.chdir(path)
try:
has_required_stuff(path)
print "\tPASS: ",os.getcwd()
except Exception as err:
print "\tFAIL: unmet requirements in " + path, ": " , err.message
Test validator can now be used as a module#! /usr/bin/python
import jsonschema
import json
import sys
import os
import glob
vm_schema = None
jsons = []
valid_vms = []
def load_schema(filename):
global vm_schema
vm_schema = json.loads(open(filename).read());
def validate_vm_spec(filename):
global valid_vms
vm_spec = None
# Load and parse as JSON
try:
vm_spec = json.loads(open(filename).read())
except:
raise Exception("JSON load / parse Error for " + filename)
# Validate JSON according to schema
try:
jsonschema.validate(vm_spec, vm_schema)
except Exception as err:
raise Exception("JSON schema validation failed: " + err.message)
valid_vms.append(vm_spec)
def has_required_stuff(path):
global jsons
# Certain files are mandatory
required_files = [ "Makefile", "test.py", "README.md", "*.cpp" ]
for file in required_files:
if not glob.glob(file):
raise Exception("missing " + file)
# JSON-files must conform to VM-schema
jsons = glob.glob("*.json")
for json in jsons:
validate_vm_spec(json)
if __name__ == "__main__":
path = sys.argv[1] if len(sys.argv) > 1 else "."
load_schema("vm.schema.json")
os.chdir(path)
try:
has_required_stuff(path)
print "<validate_test> \tPASS: ",os.getcwd()
except Exception as err:
print "<validate_test> \tFAIL: unmet requirements in " + path, ": " , err.message
|
<commit_before>#! /usr/bin/python
import jsonschema
import json
import sys
import os
import glob
vm_schema = json.loads(open("vm.schema.json").read());
def validate_vm_spec(filename):
# Load and parse as JSON
try:
vm_spec = json.loads(open(filename).read())
except:
raise Exception("JSON load / parse Error for " + filename)
# Validate JSON according to schema
try:
jsonschema.validate(vm_spec, vm_schema)
except Exception as err:
raise Exception("JSON schema validation failed: " + err.message)
def has_required_stuff(path):
# Certain files are mandatory
required_files = [ "Makefile", "test.py", "README.md", "*.cpp" ]
for file in required_files:
if not glob.glob(file):
raise Exception("missing " + file)
# JSON-files must conform to VM-schema
for json in glob.glob("*.json"):
validate_vm_spec(json)
path = sys.argv[1] if len(sys.argv) > 1 else "."
os.chdir(path)
try:
has_required_stuff(path)
print "\tPASS: ",os.getcwd()
except Exception as err:
print "\tFAIL: unmet requirements in " + path, ": " , err.message
<commit_msg>Test validator can now be used as a module<commit_after>#! /usr/bin/python
import jsonschema
import json
import sys
import os
import glob
vm_schema = None
jsons = []
valid_vms = []
def load_schema(filename):
global vm_schema
vm_schema = json.loads(open(filename).read());
def validate_vm_spec(filename):
global valid_vms
vm_spec = None
# Load and parse as JSON
try:
vm_spec = json.loads(open(filename).read())
except:
raise Exception("JSON load / parse Error for " + filename)
# Validate JSON according to schema
try:
jsonschema.validate(vm_spec, vm_schema)
except Exception as err:
raise Exception("JSON schema validation failed: " + err.message)
valid_vms.append(vm_spec)
def has_required_stuff(path):
global jsons
# Certain files are mandatory
required_files = [ "Makefile", "test.py", "README.md", "*.cpp" ]
for file in required_files:
if not glob.glob(file):
raise Exception("missing " + file)
# JSON-files must conform to VM-schema
jsons = glob.glob("*.json")
for json in jsons:
validate_vm_spec(json)
if __name__ == "__main__":
path = sys.argv[1] if len(sys.argv) > 1 else "."
load_schema("vm.schema.json")
os.chdir(path)
try:
has_required_stuff(path)
print "<validate_test> \tPASS: ",os.getcwd()
except Exception as err:
print "<validate_test> \tFAIL: unmet requirements in " + path, ": " , err.message
|
81bd740e60ce850d1617d2323b6e65960129ef0f
|
herana/forms.py
|
herana/forms.py
|
from django.contrib.auth.models import User
from django import forms
from models import ProjectDetail
class ProjectDetailForm(forms.ModelForm):
class Meta:
model = ProjectDetail
exclude = ('record_status', 'reporting_period')
def _clean_fields(self):
# If we are saving a draft, only the header field is required.
if self.data['_draft']:
for name, field in self.fields.items():
if not name == 'header':
field.required = False
super(ProjectDetailForm, self)._clean_fields()
|
from django.contrib.auth.models import User
from django import forms
from models import ProjectDetail
class ProjectDetailForm(forms.ModelForm):
class Meta:
model = ProjectDetail
exclude = ('record_status', 'reporting_period')
def _clean_fields(self):
# If we are saving a draft, only the header field is required.
if '_draft' in self.data:
for name, field in self.fields.items():
if not name == 'header':
field.required = False
super(ProjectDetailForm, self)._clean_fields()
|
Fix check for _draft key in request object
|
Fix check for _draft key in request object
|
Python
|
mit
|
Code4SA/herana,Code4SA/herana,Code4SA/herana,Code4SA/herana
|
from django.contrib.auth.models import User
from django import forms
from models import ProjectDetail
class ProjectDetailForm(forms.ModelForm):
class Meta:
model = ProjectDetail
exclude = ('record_status', 'reporting_period')
def _clean_fields(self):
# If we are saving a draft, only the header field is required.
if self.data['_draft']:
for name, field in self.fields.items():
if not name == 'header':
field.required = False
super(ProjectDetailForm, self)._clean_fields()
Fix check for _draft key in request object
|
from django.contrib.auth.models import User
from django import forms
from models import ProjectDetail
class ProjectDetailForm(forms.ModelForm):
class Meta:
model = ProjectDetail
exclude = ('record_status', 'reporting_period')
def _clean_fields(self):
# If we are saving a draft, only the header field is required.
if '_draft' in self.data:
for name, field in self.fields.items():
if not name == 'header':
field.required = False
super(ProjectDetailForm, self)._clean_fields()
|
<commit_before>from django.contrib.auth.models import User
from django import forms
from models import ProjectDetail
class ProjectDetailForm(forms.ModelForm):
class Meta:
model = ProjectDetail
exclude = ('record_status', 'reporting_period')
def _clean_fields(self):
# If we are saving a draft, only the header field is required.
if self.data['_draft']:
for name, field in self.fields.items():
if not name == 'header':
field.required = False
super(ProjectDetailForm, self)._clean_fields()
<commit_msg>Fix check for _draft key in request object<commit_after>
|
from django.contrib.auth.models import User
from django import forms
from models import ProjectDetail
class ProjectDetailForm(forms.ModelForm):
class Meta:
model = ProjectDetail
exclude = ('record_status', 'reporting_period')
def _clean_fields(self):
# If we are saving a draft, only the header field is required.
if '_draft' in self.data:
for name, field in self.fields.items():
if not name == 'header':
field.required = False
super(ProjectDetailForm, self)._clean_fields()
|
from django.contrib.auth.models import User
from django import forms
from models import ProjectDetail
class ProjectDetailForm(forms.ModelForm):
class Meta:
model = ProjectDetail
exclude = ('record_status', 'reporting_period')
def _clean_fields(self):
# If we are saving a draft, only the header field is required.
if self.data['_draft']:
for name, field in self.fields.items():
if not name == 'header':
field.required = False
super(ProjectDetailForm, self)._clean_fields()
Fix check for _draft key in request objectfrom django.contrib.auth.models import User
from django import forms
from models import ProjectDetail
class ProjectDetailForm(forms.ModelForm):
class Meta:
model = ProjectDetail
exclude = ('record_status', 'reporting_period')
def _clean_fields(self):
# If we are saving a draft, only the header field is required.
if '_draft' in self.data:
for name, field in self.fields.items():
if not name == 'header':
field.required = False
super(ProjectDetailForm, self)._clean_fields()
|
<commit_before>from django.contrib.auth.models import User
from django import forms
from models import ProjectDetail
class ProjectDetailForm(forms.ModelForm):
class Meta:
model = ProjectDetail
exclude = ('record_status', 'reporting_period')
def _clean_fields(self):
# If we are saving a draft, only the header field is required.
if self.data['_draft']:
for name, field in self.fields.items():
if not name == 'header':
field.required = False
super(ProjectDetailForm, self)._clean_fields()
<commit_msg>Fix check for _draft key in request object<commit_after>from django.contrib.auth.models import User
from django import forms
from models import ProjectDetail
class ProjectDetailForm(forms.ModelForm):
class Meta:
model = ProjectDetail
exclude = ('record_status', 'reporting_period')
def _clean_fields(self):
# If we are saving a draft, only the header field is required.
if '_draft' in self.data:
for name, field in self.fields.items():
if not name == 'header':
field.required = False
super(ProjectDetailForm, self)._clean_fields()
|
9e85483d7baef82e7081639e2df746ed80c38418
|
tests/test_wheeler.py
|
tests/test_wheeler.py
|
# coding=utf-8
import os.path as path
import unittest
from devpi_builder import wheeler
class WheelTest(unittest.TestCase):
def test_build(self):
with wheeler.Builder() as builder:
wheel_file = builder('progressbar', '2.2')
self.assertRegexpMatches(wheel_file, '\.whl$')
self.assert_(path.exists(wheel_file))
def test_cleans_up_created_files(self):
with wheeler.Builder() as builder:
wheel_file = builder('progressbar', '2.2')
self.assertFalse(path.exists(wheel_file))
def test_provides_file_that_is_already_a_wheel(self):
with wheeler.Builder() as builder:
wheel_file = builder('wheel', '0.24')
self.assert_(path.exists(wheel_file))
def test_throws_custom_on_build_failure(self):
with wheeler.Builder() as builder:
with self.assertRaises(wheeler.BuildError):
builder('package_that_hopefully_does_not_exist', '99.999')
if __name__ == '__main__':
unittest.main()
|
# coding=utf-8
import os.path as path
import unittest
from devpi_builder import wheeler
class WheelTest(unittest.TestCase):
def test_build(self):
with wheeler.Builder() as builder:
wheel_file = builder('progressbar', '2.2')
self.assertRegexpMatches(wheel_file, '\.whl$')
self.assert_(path.exists(wheel_file))
def test_cleans_up_created_files(self):
with wheeler.Builder() as builder:
wheel_file = builder('progressbar', '2.2')
self.assertFalse(path.exists(wheel_file))
def test_provides_file_that_is_already_a_wheel(self):
with wheeler.Builder() as builder:
wheel_file = builder('wheel', '0.24')
self.assert_(path.exists(wheel_file))
def test_throws_custom_on_build_failure(self):
with wheeler.Builder() as builder:
with self.assertRaises(wheeler.BuildError):
builder('package_that_hopefully_does_not_exist', '99.999')
def test_look_for_non_existing_wheel(self):
with wheeler.Builder() as builder:
with self.assertRaises(wheeler.BuildError):
builder('nothing_can_be_found', '1.1')
if __name__ == '__main__':
unittest.main()
|
Cover the line that handles the pip<=1.5.2 error case.
|
Cover the line that handles the pip<=1.5.2 error case.
|
Python
|
bsd-3-clause
|
tylerdave/devpi-builder
|
# coding=utf-8
import os.path as path
import unittest
from devpi_builder import wheeler
class WheelTest(unittest.TestCase):
def test_build(self):
with wheeler.Builder() as builder:
wheel_file = builder('progressbar', '2.2')
self.assertRegexpMatches(wheel_file, '\.whl$')
self.assert_(path.exists(wheel_file))
def test_cleans_up_created_files(self):
with wheeler.Builder() as builder:
wheel_file = builder('progressbar', '2.2')
self.assertFalse(path.exists(wheel_file))
def test_provides_file_that_is_already_a_wheel(self):
with wheeler.Builder() as builder:
wheel_file = builder('wheel', '0.24')
self.assert_(path.exists(wheel_file))
def test_throws_custom_on_build_failure(self):
with wheeler.Builder() as builder:
with self.assertRaises(wheeler.BuildError):
builder('package_that_hopefully_does_not_exist', '99.999')
if __name__ == '__main__':
unittest.main()
Cover the line that handles the pip<=1.5.2 error case.
|
# coding=utf-8
import os.path as path
import unittest
from devpi_builder import wheeler
class WheelTest(unittest.TestCase):
def test_build(self):
with wheeler.Builder() as builder:
wheel_file = builder('progressbar', '2.2')
self.assertRegexpMatches(wheel_file, '\.whl$')
self.assert_(path.exists(wheel_file))
def test_cleans_up_created_files(self):
with wheeler.Builder() as builder:
wheel_file = builder('progressbar', '2.2')
self.assertFalse(path.exists(wheel_file))
def test_provides_file_that_is_already_a_wheel(self):
with wheeler.Builder() as builder:
wheel_file = builder('wheel', '0.24')
self.assert_(path.exists(wheel_file))
def test_throws_custom_on_build_failure(self):
with wheeler.Builder() as builder:
with self.assertRaises(wheeler.BuildError):
builder('package_that_hopefully_does_not_exist', '99.999')
def test_look_for_non_existing_wheel(self):
with wheeler.Builder() as builder:
with self.assertRaises(wheeler.BuildError):
builder('nothing_can_be_found', '1.1')
if __name__ == '__main__':
unittest.main()
|
<commit_before># coding=utf-8
import os.path as path
import unittest
from devpi_builder import wheeler
class WheelTest(unittest.TestCase):
def test_build(self):
with wheeler.Builder() as builder:
wheel_file = builder('progressbar', '2.2')
self.assertRegexpMatches(wheel_file, '\.whl$')
self.assert_(path.exists(wheel_file))
def test_cleans_up_created_files(self):
with wheeler.Builder() as builder:
wheel_file = builder('progressbar', '2.2')
self.assertFalse(path.exists(wheel_file))
def test_provides_file_that_is_already_a_wheel(self):
with wheeler.Builder() as builder:
wheel_file = builder('wheel', '0.24')
self.assert_(path.exists(wheel_file))
def test_throws_custom_on_build_failure(self):
with wheeler.Builder() as builder:
with self.assertRaises(wheeler.BuildError):
builder('package_that_hopefully_does_not_exist', '99.999')
if __name__ == '__main__':
unittest.main()
<commit_msg>Cover the line that handles the pip<=1.5.2 error case.<commit_after>
|
# coding=utf-8
import os.path as path
import unittest
from devpi_builder import wheeler
class WheelTest(unittest.TestCase):
def test_build(self):
with wheeler.Builder() as builder:
wheel_file = builder('progressbar', '2.2')
self.assertRegexpMatches(wheel_file, '\.whl$')
self.assert_(path.exists(wheel_file))
def test_cleans_up_created_files(self):
with wheeler.Builder() as builder:
wheel_file = builder('progressbar', '2.2')
self.assertFalse(path.exists(wheel_file))
def test_provides_file_that_is_already_a_wheel(self):
with wheeler.Builder() as builder:
wheel_file = builder('wheel', '0.24')
self.assert_(path.exists(wheel_file))
def test_throws_custom_on_build_failure(self):
with wheeler.Builder() as builder:
with self.assertRaises(wheeler.BuildError):
builder('package_that_hopefully_does_not_exist', '99.999')
def test_look_for_non_existing_wheel(self):
with wheeler.Builder() as builder:
with self.assertRaises(wheeler.BuildError):
builder('nothing_can_be_found', '1.1')
if __name__ == '__main__':
unittest.main()
|
# coding=utf-8
import os.path as path
import unittest
from devpi_builder import wheeler
class WheelTest(unittest.TestCase):
def test_build(self):
with wheeler.Builder() as builder:
wheel_file = builder('progressbar', '2.2')
self.assertRegexpMatches(wheel_file, '\.whl$')
self.assert_(path.exists(wheel_file))
def test_cleans_up_created_files(self):
with wheeler.Builder() as builder:
wheel_file = builder('progressbar', '2.2')
self.assertFalse(path.exists(wheel_file))
def test_provides_file_that_is_already_a_wheel(self):
with wheeler.Builder() as builder:
wheel_file = builder('wheel', '0.24')
self.assert_(path.exists(wheel_file))
def test_throws_custom_on_build_failure(self):
with wheeler.Builder() as builder:
with self.assertRaises(wheeler.BuildError):
builder('package_that_hopefully_does_not_exist', '99.999')
if __name__ == '__main__':
unittest.main()
Cover the line that handles the pip<=1.5.2 error case.# coding=utf-8
import os.path as path
import unittest
from devpi_builder import wheeler
class WheelTest(unittest.TestCase):
def test_build(self):
with wheeler.Builder() as builder:
wheel_file = builder('progressbar', '2.2')
self.assertRegexpMatches(wheel_file, '\.whl$')
self.assert_(path.exists(wheel_file))
def test_cleans_up_created_files(self):
with wheeler.Builder() as builder:
wheel_file = builder('progressbar', '2.2')
self.assertFalse(path.exists(wheel_file))
def test_provides_file_that_is_already_a_wheel(self):
with wheeler.Builder() as builder:
wheel_file = builder('wheel', '0.24')
self.assert_(path.exists(wheel_file))
def test_throws_custom_on_build_failure(self):
with wheeler.Builder() as builder:
with self.assertRaises(wheeler.BuildError):
builder('package_that_hopefully_does_not_exist', '99.999')
def test_look_for_non_existing_wheel(self):
with wheeler.Builder() as builder:
with self.assertRaises(wheeler.BuildError):
builder('nothing_can_be_found', '1.1')
if __name__ == '__main__':
unittest.main()
|
<commit_before># coding=utf-8
import os.path as path
import unittest
from devpi_builder import wheeler
class WheelTest(unittest.TestCase):
def test_build(self):
with wheeler.Builder() as builder:
wheel_file = builder('progressbar', '2.2')
self.assertRegexpMatches(wheel_file, '\.whl$')
self.assert_(path.exists(wheel_file))
def test_cleans_up_created_files(self):
with wheeler.Builder() as builder:
wheel_file = builder('progressbar', '2.2')
self.assertFalse(path.exists(wheel_file))
def test_provides_file_that_is_already_a_wheel(self):
with wheeler.Builder() as builder:
wheel_file = builder('wheel', '0.24')
self.assert_(path.exists(wheel_file))
def test_throws_custom_on_build_failure(self):
with wheeler.Builder() as builder:
with self.assertRaises(wheeler.BuildError):
builder('package_that_hopefully_does_not_exist', '99.999')
if __name__ == '__main__':
unittest.main()
<commit_msg>Cover the line that handles the pip<=1.5.2 error case.<commit_after># coding=utf-8
import os.path as path
import unittest
from devpi_builder import wheeler
class WheelTest(unittest.TestCase):
def test_build(self):
with wheeler.Builder() as builder:
wheel_file = builder('progressbar', '2.2')
self.assertRegexpMatches(wheel_file, '\.whl$')
self.assert_(path.exists(wheel_file))
def test_cleans_up_created_files(self):
with wheeler.Builder() as builder:
wheel_file = builder('progressbar', '2.2')
self.assertFalse(path.exists(wheel_file))
def test_provides_file_that_is_already_a_wheel(self):
with wheeler.Builder() as builder:
wheel_file = builder('wheel', '0.24')
self.assert_(path.exists(wheel_file))
def test_throws_custom_on_build_failure(self):
with wheeler.Builder() as builder:
with self.assertRaises(wheeler.BuildError):
builder('package_that_hopefully_does_not_exist', '99.999')
def test_look_for_non_existing_wheel(self):
with wheeler.Builder() as builder:
with self.assertRaises(wheeler.BuildError):
builder('nothing_can_be_found', '1.1')
if __name__ == '__main__':
unittest.main()
|
d4d409e52ce62053dd2ed40c1c5ee3ec7bce3ef3
|
src/hiss/handler/gntp/sync.py
|
src/hiss/handler/gntp/sync.py
|
import socket
from hiss.handler.gntp.message import Response
class GNTPHandler():
def register(self, notifier, target, **kwargs):
pass
def notify(self, notification, target):
pass
def unregister(self, notifier, target):
pass
def send_request(request, target, wait_for_response=True):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(target.address)
s.sendall(request.marshal())
if wait_for_response:
response_data = bytearray()
while True:
data = s.recv(1024)
if not data:
break
response_data.extend(data)
response = Response()
response.unmarshal(response_data)
return response
else:
response = None
s.close()
return response
|
import socket
from hiss.handler.gntp.message import Response
class GNTPHandler():
def register(self, notifier, target, **kwargs):
pass
def notify(self, notification, target):
pass
def unregister(self, notifier, target):
pass
def send_request(request, target, wait_for_response=True):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(target.address)
s.sendall(request.marshal())
if wait_for_response:
response_data = bytearray()
while True:
data = s.recv(1024)
if not data:
break
response_data.extend(data)
response = Response()
response.unmarshal(response_data)
else:
response = None
s.close()
return response
|
Make sure we close the socket
|
Make sure we close the socket
|
Python
|
apache-2.0
|
sffjunkie/hiss
|
import socket
from hiss.handler.gntp.message import Response
class GNTPHandler():
def register(self, notifier, target, **kwargs):
pass
def notify(self, notification, target):
pass
def unregister(self, notifier, target):
pass
def send_request(request, target, wait_for_response=True):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(target.address)
s.sendall(request.marshal())
if wait_for_response:
response_data = bytearray()
while True:
data = s.recv(1024)
if not data:
break
response_data.extend(data)
response = Response()
response.unmarshal(response_data)
return response
else:
response = None
s.close()
return response
Make sure we close the socket
|
import socket
from hiss.handler.gntp.message import Response
class GNTPHandler():
def register(self, notifier, target, **kwargs):
pass
def notify(self, notification, target):
pass
def unregister(self, notifier, target):
pass
def send_request(request, target, wait_for_response=True):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(target.address)
s.sendall(request.marshal())
if wait_for_response:
response_data = bytearray()
while True:
data = s.recv(1024)
if not data:
break
response_data.extend(data)
response = Response()
response.unmarshal(response_data)
else:
response = None
s.close()
return response
|
<commit_before>import socket
from hiss.handler.gntp.message import Response
class GNTPHandler():
def register(self, notifier, target, **kwargs):
pass
def notify(self, notification, target):
pass
def unregister(self, notifier, target):
pass
def send_request(request, target, wait_for_response=True):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(target.address)
s.sendall(request.marshal())
if wait_for_response:
response_data = bytearray()
while True:
data = s.recv(1024)
if not data:
break
response_data.extend(data)
response = Response()
response.unmarshal(response_data)
return response
else:
response = None
s.close()
return response
<commit_msg>Make sure we close the socket<commit_after>
|
import socket
from hiss.handler.gntp.message import Response
class GNTPHandler():
def register(self, notifier, target, **kwargs):
pass
def notify(self, notification, target):
pass
def unregister(self, notifier, target):
pass
def send_request(request, target, wait_for_response=True):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(target.address)
s.sendall(request.marshal())
if wait_for_response:
response_data = bytearray()
while True:
data = s.recv(1024)
if not data:
break
response_data.extend(data)
response = Response()
response.unmarshal(response_data)
else:
response = None
s.close()
return response
|
import socket
from hiss.handler.gntp.message import Response
class GNTPHandler():
def register(self, notifier, target, **kwargs):
pass
def notify(self, notification, target):
pass
def unregister(self, notifier, target):
pass
def send_request(request, target, wait_for_response=True):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(target.address)
s.sendall(request.marshal())
if wait_for_response:
response_data = bytearray()
while True:
data = s.recv(1024)
if not data:
break
response_data.extend(data)
response = Response()
response.unmarshal(response_data)
return response
else:
response = None
s.close()
return response
Make sure we close the socketimport socket
from hiss.handler.gntp.message import Response
class GNTPHandler():
def register(self, notifier, target, **kwargs):
pass
def notify(self, notification, target):
pass
def unregister(self, notifier, target):
pass
def send_request(request, target, wait_for_response=True):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(target.address)
s.sendall(request.marshal())
if wait_for_response:
response_data = bytearray()
while True:
data = s.recv(1024)
if not data:
break
response_data.extend(data)
response = Response()
response.unmarshal(response_data)
else:
response = None
s.close()
return response
|
<commit_before>import socket
from hiss.handler.gntp.message import Response
class GNTPHandler():
def register(self, notifier, target, **kwargs):
pass
def notify(self, notification, target):
pass
def unregister(self, notifier, target):
pass
def send_request(request, target, wait_for_response=True):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(target.address)
s.sendall(request.marshal())
if wait_for_response:
response_data = bytearray()
while True:
data = s.recv(1024)
if not data:
break
response_data.extend(data)
response = Response()
response.unmarshal(response_data)
return response
else:
response = None
s.close()
return response
<commit_msg>Make sure we close the socket<commit_after>import socket
from hiss.handler.gntp.message import Response
class GNTPHandler():
def register(self, notifier, target, **kwargs):
pass
def notify(self, notification, target):
pass
def unregister(self, notifier, target):
pass
def send_request(request, target, wait_for_response=True):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(target.address)
s.sendall(request.marshal())
if wait_for_response:
response_data = bytearray()
while True:
data = s.recv(1024)
if not data:
break
response_data.extend(data)
response = Response()
response.unmarshal(response_data)
else:
response = None
s.close()
return response
|
0cd94ef9c5454ef79544d902fa5397bad5f17d54
|
dashboard/src/configuration.py
|
dashboard/src/configuration.py
|
from server_configuration import *
from s3_configuration import *
class Configuration():
def __init__(self):
self.stage = ServerConfiguration('STAGE')
self.prod = ServerConfiguration('PROD')
self.s3 = S3Configuration()
def __repr__(self):
return "Stage: {s}\nProd: {p}\nS3: {d}".format(s=self.stage, p=self.prod, d=self.s3)
|
"""Configuration for the Dashboard."""
from server_configuration import *
from s3_configuration import *
class Configuration():
"""Class representing configuration for the Dashboard."""
def __init__(self):
"""Construct the configuration structure."""
self.stage = ServerConfiguration('STAGE')
self.prod = ServerConfiguration('PROD')
self.s3 = S3Configuration()
def __repr__(self):
"""Return string representation for the configuration object."""
return "Stage: {s}\nProd: {p}\nS3: {d}".format(s=self.stage, p=self.prod, d=self.s3)
|
Remove excessive parenthesis + add docstrings to module, class, and all public methods
|
Remove excessive parenthesis + add docstrings to module, class, and all public methods
|
Python
|
apache-2.0
|
tisnik/fabric8-analytics-common,tisnik/fabric8-analytics-common,jpopelka/fabric8-analytics-common,tisnik/fabric8-analytics-common,jpopelka/fabric8-analytics-common,jpopelka/fabric8-analytics-common
|
from server_configuration import *
from s3_configuration import *
class Configuration():
def __init__(self):
self.stage = ServerConfiguration('STAGE')
self.prod = ServerConfiguration('PROD')
self.s3 = S3Configuration()
def __repr__(self):
return "Stage: {s}\nProd: {p}\nS3: {d}".format(s=self.stage, p=self.prod, d=self.s3)
Remove excessive parenthesis + add docstrings to module, class, and all public methods
|
"""Configuration for the Dashboard."""
from server_configuration import *
from s3_configuration import *
class Configuration():
"""Class representing configuration for the Dashboard."""
def __init__(self):
"""Construct the configuration structure."""
self.stage = ServerConfiguration('STAGE')
self.prod = ServerConfiguration('PROD')
self.s3 = S3Configuration()
def __repr__(self):
"""Return string representation for the configuration object."""
return "Stage: {s}\nProd: {p}\nS3: {d}".format(s=self.stage, p=self.prod, d=self.s3)
|
<commit_before>from server_configuration import *
from s3_configuration import *
class Configuration():
def __init__(self):
self.stage = ServerConfiguration('STAGE')
self.prod = ServerConfiguration('PROD')
self.s3 = S3Configuration()
def __repr__(self):
return "Stage: {s}\nProd: {p}\nS3: {d}".format(s=self.stage, p=self.prod, d=self.s3)
<commit_msg>Remove excessive parenthesis + add docstrings to module, class, and all public methods<commit_after>
|
"""Configuration for the Dashboard."""
from server_configuration import *
from s3_configuration import *
class Configuration():
"""Class representing configuration for the Dashboard."""
def __init__(self):
"""Construct the configuration structure."""
self.stage = ServerConfiguration('STAGE')
self.prod = ServerConfiguration('PROD')
self.s3 = S3Configuration()
def __repr__(self):
"""Return string representation for the configuration object."""
return "Stage: {s}\nProd: {p}\nS3: {d}".format(s=self.stage, p=self.prod, d=self.s3)
|
from server_configuration import *
from s3_configuration import *
class Configuration():
def __init__(self):
self.stage = ServerConfiguration('STAGE')
self.prod = ServerConfiguration('PROD')
self.s3 = S3Configuration()
def __repr__(self):
return "Stage: {s}\nProd: {p}\nS3: {d}".format(s=self.stage, p=self.prod, d=self.s3)
Remove excessive parenthesis + add docstrings to module, class, and all public methods"""Configuration for the Dashboard."""
from server_configuration import *
from s3_configuration import *
class Configuration():
"""Class representing configuration for the Dashboard."""
def __init__(self):
"""Construct the configuration structure."""
self.stage = ServerConfiguration('STAGE')
self.prod = ServerConfiguration('PROD')
self.s3 = S3Configuration()
def __repr__(self):
"""Return string representation for the configuration object."""
return "Stage: {s}\nProd: {p}\nS3: {d}".format(s=self.stage, p=self.prod, d=self.s3)
|
<commit_before>from server_configuration import *
from s3_configuration import *
class Configuration():
def __init__(self):
self.stage = ServerConfiguration('STAGE')
self.prod = ServerConfiguration('PROD')
self.s3 = S3Configuration()
def __repr__(self):
return "Stage: {s}\nProd: {p}\nS3: {d}".format(s=self.stage, p=self.prod, d=self.s3)
<commit_msg>Remove excessive parenthesis + add docstrings to module, class, and all public methods<commit_after>"""Configuration for the Dashboard."""
from server_configuration import *
from s3_configuration import *
class Configuration():
"""Class representing configuration for the Dashboard."""
def __init__(self):
"""Construct the configuration structure."""
self.stage = ServerConfiguration('STAGE')
self.prod = ServerConfiguration('PROD')
self.s3 = S3Configuration()
def __repr__(self):
"""Return string representation for the configuration object."""
return "Stage: {s}\nProd: {p}\nS3: {d}".format(s=self.stage, p=self.prod, d=self.s3)
|
1f6ba483902c59dc70d15ea1e33957ac6a874f01
|
freesound_datasets/local_settings.example.py
|
freesound_datasets/local_settings.example.py
|
# Freesound keys for download script
# Get credentials at http://www.freesound.org/apiv2/apply
# Set callback url to https://www.freesound.org/home/app_permissions/permission_granted/
FS_CLIENT_ID = 'FREESOUND_KEY'
FS_CLIENT_SECRET = 'FREESOUND_SECRET'
# Freesound keys for "login with" functionality
# Get credentials at http://www.freesound.org/apiv2/apply
# Set callback url to http://localhost:8000/social/complete/freesound/
SOCIAL_AUTH_FREESOUND_KEY = None
SOCIAL_AUTH_FREESOUND_SECRET = 'FREESOUND_SECRET'
# Google keys for "login with" functionality
# Get credentials at https://console.developers.google.com
# Set callback url to http://localhost:8000/social/complete/google-oauth2/
SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = None # (remove the part starting with the dot .)
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = 'GOOGLE_SECRET'
# Facebook keys for "login with" functionality
# See instructions in https://simpleisbetterthancomplex.com/tutorial/2016/10/24/how-to-add-social-login-to-django.html
# NOTE: might not work in localhost
SOCIAL_AUTH_FACEBOOK_KEY = None
SOCIAL_AUTH_FACEBOOK_SECRET = 'FACEBOOK_SECRET'
# Github keys for "login with" functionality
# Get credentials at https://github.com/settings/applications/new
# Set callback url to http://localhost:8000/social/complete/github/
SOCIAL_AUTH_GITHUB_KEY = None
SOCIAL_AUTH_GITHUB_SECRET = 'GITHUB_SECRET'
|
# Freesound keys for download script
# Get credentials at http://www.freesound.org/apiv2/apply
# Set callback url to https://www.freesound.org/home/app_permissions/permission_granted/
FS_CLIENT_ID = 'FREESOUND_KEY'
FS_CLIENT_SECRET = 'FREESOUND_SECRET'
# Freesound keys for "login with" functionality
# Get credentials at http://www.freesound.org/apiv2/apply
# Set callback url to http://localhost:8000/social/complete/freesound/
SOCIAL_AUTH_FREESOUND_KEY = None
SOCIAL_AUTH_FREESOUND_SECRET = 'FREESOUND_SECRET'
|
Remove unused social auth keys
|
Remove unused social auth keys
|
Python
|
agpl-3.0
|
MTG/freesound-datasets,MTG/freesound-datasets,MTG/freesound-datasets,MTG/freesound-datasets
|
# Freesound keys for download script
# Get credentials at http://www.freesound.org/apiv2/apply
# Set callback url to https://www.freesound.org/home/app_permissions/permission_granted/
FS_CLIENT_ID = 'FREESOUND_KEY'
FS_CLIENT_SECRET = 'FREESOUND_SECRET'
# Freesound keys for "login with" functionality
# Get credentials at http://www.freesound.org/apiv2/apply
# Set callback url to http://localhost:8000/social/complete/freesound/
SOCIAL_AUTH_FREESOUND_KEY = None
SOCIAL_AUTH_FREESOUND_SECRET = 'FREESOUND_SECRET'
# Google keys for "login with" functionality
# Get credentials at https://console.developers.google.com
# Set callback url to http://localhost:8000/social/complete/google-oauth2/
SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = None # (remove the part starting with the dot .)
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = 'GOOGLE_SECRET'
# Facebook keys for "login with" functionality
# See instructions in https://simpleisbetterthancomplex.com/tutorial/2016/10/24/how-to-add-social-login-to-django.html
# NOTE: might not work in localhost
SOCIAL_AUTH_FACEBOOK_KEY = None
SOCIAL_AUTH_FACEBOOK_SECRET = 'FACEBOOK_SECRET'
# Github keys for "login with" functionality
# Get credentials at https://github.com/settings/applications/new
# Set callback url to http://localhost:8000/social/complete/github/
SOCIAL_AUTH_GITHUB_KEY = None
SOCIAL_AUTH_GITHUB_SECRET = 'GITHUB_SECRET'
Remove unused social auth keys
|
# Freesound keys for download script
# Get credentials at http://www.freesound.org/apiv2/apply
# Set callback url to https://www.freesound.org/home/app_permissions/permission_granted/
FS_CLIENT_ID = 'FREESOUND_KEY'
FS_CLIENT_SECRET = 'FREESOUND_SECRET'
# Freesound keys for "login with" functionality
# Get credentials at http://www.freesound.org/apiv2/apply
# Set callback url to http://localhost:8000/social/complete/freesound/
SOCIAL_AUTH_FREESOUND_KEY = None
SOCIAL_AUTH_FREESOUND_SECRET = 'FREESOUND_SECRET'
|
<commit_before># Freesound keys for download script
# Get credentials at http://www.freesound.org/apiv2/apply
# Set callback url to https://www.freesound.org/home/app_permissions/permission_granted/
FS_CLIENT_ID = 'FREESOUND_KEY'
FS_CLIENT_SECRET = 'FREESOUND_SECRET'
# Freesound keys for "login with" functionality
# Get credentials at http://www.freesound.org/apiv2/apply
# Set callback url to http://localhost:8000/social/complete/freesound/
SOCIAL_AUTH_FREESOUND_KEY = None
SOCIAL_AUTH_FREESOUND_SECRET = 'FREESOUND_SECRET'
# Google keys for "login with" functionality
# Get credentials at https://console.developers.google.com
# Set callback url to http://localhost:8000/social/complete/google-oauth2/
SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = None # (remove the part starting with the dot .)
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = 'GOOGLE_SECRET'
# Facebook keys for "login with" functionality
# See instructions in https://simpleisbetterthancomplex.com/tutorial/2016/10/24/how-to-add-social-login-to-django.html
# NOTE: might not work in localhost
SOCIAL_AUTH_FACEBOOK_KEY = None
SOCIAL_AUTH_FACEBOOK_SECRET = 'FACEBOOK_SECRET'
# Github keys for "login with" functionality
# Get credentials at https://github.com/settings/applications/new
# Set callback url to http://localhost:8000/social/complete/github/
SOCIAL_AUTH_GITHUB_KEY = None
SOCIAL_AUTH_GITHUB_SECRET = 'GITHUB_SECRET'
<commit_msg>Remove unused social auth keys<commit_after>
|
# Freesound keys for download script
# Get credentials at http://www.freesound.org/apiv2/apply
# Set callback url to https://www.freesound.org/home/app_permissions/permission_granted/
FS_CLIENT_ID = 'FREESOUND_KEY'
FS_CLIENT_SECRET = 'FREESOUND_SECRET'
# Freesound keys for "login with" functionality
# Get credentials at http://www.freesound.org/apiv2/apply
# Set callback url to http://localhost:8000/social/complete/freesound/
SOCIAL_AUTH_FREESOUND_KEY = None
SOCIAL_AUTH_FREESOUND_SECRET = 'FREESOUND_SECRET'
|
# Freesound keys for download script
# Get credentials at http://www.freesound.org/apiv2/apply
# Set callback url to https://www.freesound.org/home/app_permissions/permission_granted/
FS_CLIENT_ID = 'FREESOUND_KEY'
FS_CLIENT_SECRET = 'FREESOUND_SECRET'
# Freesound keys for "login with" functionality
# Get credentials at http://www.freesound.org/apiv2/apply
# Set callback url to http://localhost:8000/social/complete/freesound/
SOCIAL_AUTH_FREESOUND_KEY = None
SOCIAL_AUTH_FREESOUND_SECRET = 'FREESOUND_SECRET'
# Google keys for "login with" functionality
# Get credentials at https://console.developers.google.com
# Set callback url to http://localhost:8000/social/complete/google-oauth2/
SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = None # (remove the part starting with the dot .)
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = 'GOOGLE_SECRET'
# Facebook keys for "login with" functionality
# See instructions in https://simpleisbetterthancomplex.com/tutorial/2016/10/24/how-to-add-social-login-to-django.html
# NOTE: might not work in localhost
SOCIAL_AUTH_FACEBOOK_KEY = None
SOCIAL_AUTH_FACEBOOK_SECRET = 'FACEBOOK_SECRET'
# Github keys for "login with" functionality
# Get credentials at https://github.com/settings/applications/new
# Set callback url to http://localhost:8000/social/complete/github/
SOCIAL_AUTH_GITHUB_KEY = None
SOCIAL_AUTH_GITHUB_SECRET = 'GITHUB_SECRET'
Remove unused social auth keys# Freesound keys for download script
# Get credentials at http://www.freesound.org/apiv2/apply
# Set callback url to https://www.freesound.org/home/app_permissions/permission_granted/
FS_CLIENT_ID = 'FREESOUND_KEY'
FS_CLIENT_SECRET = 'FREESOUND_SECRET'
# Freesound keys for "login with" functionality
# Get credentials at http://www.freesound.org/apiv2/apply
# Set callback url to http://localhost:8000/social/complete/freesound/
SOCIAL_AUTH_FREESOUND_KEY = None
SOCIAL_AUTH_FREESOUND_SECRET = 'FREESOUND_SECRET'
|
<commit_before># Freesound keys for download script
# Get credentials at http://www.freesound.org/apiv2/apply
# Set callback url to https://www.freesound.org/home/app_permissions/permission_granted/
FS_CLIENT_ID = 'FREESOUND_KEY'
FS_CLIENT_SECRET = 'FREESOUND_SECRET'
# Freesound keys for "login with" functionality
# Get credentials at http://www.freesound.org/apiv2/apply
# Set callback url to http://localhost:8000/social/complete/freesound/
SOCIAL_AUTH_FREESOUND_KEY = None
SOCIAL_AUTH_FREESOUND_SECRET = 'FREESOUND_SECRET'
# Google keys for "login with" functionality
# Get credentials at https://console.developers.google.com
# Set callback url to http://localhost:8000/social/complete/google-oauth2/
SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = None # (remove the part starting with the dot .)
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = 'GOOGLE_SECRET'
# Facebook keys for "login with" functionality
# See instructions in https://simpleisbetterthancomplex.com/tutorial/2016/10/24/how-to-add-social-login-to-django.html
# NOTE: might not work in localhost
SOCIAL_AUTH_FACEBOOK_KEY = None
SOCIAL_AUTH_FACEBOOK_SECRET = 'FACEBOOK_SECRET'
# Github keys for "login with" functionality
# Get credentials at https://github.com/settings/applications/new
# Set callback url to http://localhost:8000/social/complete/github/
SOCIAL_AUTH_GITHUB_KEY = None
SOCIAL_AUTH_GITHUB_SECRET = 'GITHUB_SECRET'
<commit_msg>Remove unused social auth keys<commit_after># Freesound keys for download script
# Get credentials at http://www.freesound.org/apiv2/apply
# Set callback url to https://www.freesound.org/home/app_permissions/permission_granted/
FS_CLIENT_ID = 'FREESOUND_KEY'
FS_CLIENT_SECRET = 'FREESOUND_SECRET'
# Freesound keys for "login with" functionality
# Get credentials at http://www.freesound.org/apiv2/apply
# Set callback url to http://localhost:8000/social/complete/freesound/
SOCIAL_AUTH_FREESOUND_KEY = None
SOCIAL_AUTH_FREESOUND_SECRET = 'FREESOUND_SECRET'
|
d8fb1906a66c5be2fb1289196bc07caaccfff0dd
|
php/apache_modules.py
|
php/apache_modules.py
|
import os
import yaml
def load_modules(data):
result = yaml.load(data)
if result:
apache = result.get('apache', {})
if apache:
return apache.get('modules', [])
return []
def install_modules(modules):
installed = 0
for module in modules:
print " Installing Apache module %s" % module
os.system("a2enmod "+module+" >/dev/null 2>&1")
installed = installed + 1
if installed > 0:
os.system('/etc/init.d/apache2 restart')
print " Done enabling Apache modules."
else:
print " No Apache modules to enabled."
def load_file(working_dir="/home/application/current"):
files_name = ["app.yaml", "app.yml"]
for file_name in files_name:
try:
with open(os.path.join(working_dir, file_name)) as f:
return f.read()
except IOError:
pass
return ""
def main():
print ""
print ""
print ""
print "========================================"
print " Parsing Apache modules to enable"
print "========================================"
print ""
data = load_file()
modules = load_modules(data)
install_modules(modules)
main()
|
import os
import yaml
def load_modules(data):
result = yaml.load(data)
if result:
apache = result.get('apache', {})
if apache:
return apache.get('modules', [])
return []
def install_modules(modules):
installed = 0
for module in modules:
print " Installing Apache module %s" % module
os.system("a2enmod "+module+" >/dev/null 2>&1")
installed = installed + 1
if installed > 0:
os.system('/etc/init.d/apache2 restart >/dev/null 2>&1')
print " Done enabling Apache modules."
else:
print " No Apache modules to enabled."
def load_file(working_dir="/home/application/current"):
files_name = ["app.yaml", "app.yml"]
for file_name in files_name:
try:
with open(os.path.join(working_dir, file_name)) as f:
return f.read()
except IOError:
pass
return ""
def main():
print ""
print ""
print ""
print "========================================"
print " Parsing Apache modules to enable"
print "========================================"
print ""
data = load_file()
modules = load_modules(data)
install_modules(modules)
main()
|
Remove output when restarting apache after module enable
|
Remove output when restarting apache after module enable
|
Python
|
bsd-3-clause
|
jusbrasil/basebuilder,axelerant/basebuilder,axelerant/basebuilder,leandrosouza/basebuilder,keymon/basebuilder,actionjack/basebuilder,emerleite/basebuilder,keymon/basebuilder,axelerant/basebuilder,marcuskara/basebuilder,keymon/basebuilder,jusbrasil/basebuilder,marcuskara/basebuilder,ChangjunZhao/basebuilder,emerleite/basebuilder,keymon/basebuilder,leandrosouza/basebuilder,jusbrasil/basebuilder,ChangjunZhao/basebuilder,keymon/basebuilder,keymon/basebuilder,tsuru/basebuilder,emerleite/basebuilder,marcuskara/basebuilder,actionjack/basebuilder,tsuru/basebuilder,actionjack/basebuilder,keymon/basebuilder,leandrosouza/basebuilder,ChangjunZhao/basebuilder,keymon/basebuilder
|
import os
import yaml
def load_modules(data):
result = yaml.load(data)
if result:
apache = result.get('apache', {})
if apache:
return apache.get('modules', [])
return []
def install_modules(modules):
installed = 0
for module in modules:
print " Installing Apache module %s" % module
os.system("a2enmod "+module+" >/dev/null 2>&1")
installed = installed + 1
if installed > 0:
os.system('/etc/init.d/apache2 restart')
print " Done enabling Apache modules."
else:
print " No Apache modules to enabled."
def load_file(working_dir="/home/application/current"):
files_name = ["app.yaml", "app.yml"]
for file_name in files_name:
try:
with open(os.path.join(working_dir, file_name)) as f:
return f.read()
except IOError:
pass
return ""
def main():
print ""
print ""
print ""
print "========================================"
print " Parsing Apache modules to enable"
print "========================================"
print ""
data = load_file()
modules = load_modules(data)
install_modules(modules)
main()
Remove output when restarting apache after module enable
|
import os
import yaml
def load_modules(data):
result = yaml.load(data)
if result:
apache = result.get('apache', {})
if apache:
return apache.get('modules', [])
return []
def install_modules(modules):
installed = 0
for module in modules:
print " Installing Apache module %s" % module
os.system("a2enmod "+module+" >/dev/null 2>&1")
installed = installed + 1
if installed > 0:
os.system('/etc/init.d/apache2 restart >/dev/null 2>&1')
print " Done enabling Apache modules."
else:
print " No Apache modules to enabled."
def load_file(working_dir="/home/application/current"):
files_name = ["app.yaml", "app.yml"]
for file_name in files_name:
try:
with open(os.path.join(working_dir, file_name)) as f:
return f.read()
except IOError:
pass
return ""
def main():
print ""
print ""
print ""
print "========================================"
print " Parsing Apache modules to enable"
print "========================================"
print ""
data = load_file()
modules = load_modules(data)
install_modules(modules)
main()
|
<commit_before>import os
import yaml
def load_modules(data):
result = yaml.load(data)
if result:
apache = result.get('apache', {})
if apache:
return apache.get('modules', [])
return []
def install_modules(modules):
installed = 0
for module in modules:
print " Installing Apache module %s" % module
os.system("a2enmod "+module+" >/dev/null 2>&1")
installed = installed + 1
if installed > 0:
os.system('/etc/init.d/apache2 restart')
print " Done enabling Apache modules."
else:
print " No Apache modules to enabled."
def load_file(working_dir="/home/application/current"):
files_name = ["app.yaml", "app.yml"]
for file_name in files_name:
try:
with open(os.path.join(working_dir, file_name)) as f:
return f.read()
except IOError:
pass
return ""
def main():
print ""
print ""
print ""
print "========================================"
print " Parsing Apache modules to enable"
print "========================================"
print ""
data = load_file()
modules = load_modules(data)
install_modules(modules)
main()
<commit_msg>Remove output when restarting apache after module enable<commit_after>
|
import os
import yaml
def load_modules(data):
result = yaml.load(data)
if result:
apache = result.get('apache', {})
if apache:
return apache.get('modules', [])
return []
def install_modules(modules):
installed = 0
for module in modules:
print " Installing Apache module %s" % module
os.system("a2enmod "+module+" >/dev/null 2>&1")
installed = installed + 1
if installed > 0:
os.system('/etc/init.d/apache2 restart >/dev/null 2>&1')
print " Done enabling Apache modules."
else:
print " No Apache modules to enabled."
def load_file(working_dir="/home/application/current"):
files_name = ["app.yaml", "app.yml"]
for file_name in files_name:
try:
with open(os.path.join(working_dir, file_name)) as f:
return f.read()
except IOError:
pass
return ""
def main():
print ""
print ""
print ""
print "========================================"
print " Parsing Apache modules to enable"
print "========================================"
print ""
data = load_file()
modules = load_modules(data)
install_modules(modules)
main()
|
import os
import yaml
def load_modules(data):
result = yaml.load(data)
if result:
apache = result.get('apache', {})
if apache:
return apache.get('modules', [])
return []
def install_modules(modules):
installed = 0
for module in modules:
print " Installing Apache module %s" % module
os.system("a2enmod "+module+" >/dev/null 2>&1")
installed = installed + 1
if installed > 0:
os.system('/etc/init.d/apache2 restart')
print " Done enabling Apache modules."
else:
print " No Apache modules to enabled."
def load_file(working_dir="/home/application/current"):
files_name = ["app.yaml", "app.yml"]
for file_name in files_name:
try:
with open(os.path.join(working_dir, file_name)) as f:
return f.read()
except IOError:
pass
return ""
def main():
print ""
print ""
print ""
print "========================================"
print " Parsing Apache modules to enable"
print "========================================"
print ""
data = load_file()
modules = load_modules(data)
install_modules(modules)
main()
Remove output when restarting apache after module enableimport os
import yaml
def load_modules(data):
result = yaml.load(data)
if result:
apache = result.get('apache', {})
if apache:
return apache.get('modules', [])
return []
def install_modules(modules):
installed = 0
for module in modules:
print " Installing Apache module %s" % module
os.system("a2enmod "+module+" >/dev/null 2>&1")
installed = installed + 1
if installed > 0:
os.system('/etc/init.d/apache2 restart >/dev/null 2>&1')
print " Done enabling Apache modules."
else:
print " No Apache modules to enabled."
def load_file(working_dir="/home/application/current"):
files_name = ["app.yaml", "app.yml"]
for file_name in files_name:
try:
with open(os.path.join(working_dir, file_name)) as f:
return f.read()
except IOError:
pass
return ""
def main():
print ""
print ""
print ""
print "========================================"
print " Parsing Apache modules to enable"
print "========================================"
print ""
data = load_file()
modules = load_modules(data)
install_modules(modules)
main()
|
<commit_before>import os
import yaml
def load_modules(data):
result = yaml.load(data)
if result:
apache = result.get('apache', {})
if apache:
return apache.get('modules', [])
return []
def install_modules(modules):
installed = 0
for module in modules:
print " Installing Apache module %s" % module
os.system("a2enmod "+module+" >/dev/null 2>&1")
installed = installed + 1
if installed > 0:
os.system('/etc/init.d/apache2 restart')
print " Done enabling Apache modules."
else:
print " No Apache modules to enabled."
def load_file(working_dir="/home/application/current"):
files_name = ["app.yaml", "app.yml"]
for file_name in files_name:
try:
with open(os.path.join(working_dir, file_name)) as f:
return f.read()
except IOError:
pass
return ""
def main():
print ""
print ""
print ""
print "========================================"
print " Parsing Apache modules to enable"
print "========================================"
print ""
data = load_file()
modules = load_modules(data)
install_modules(modules)
main()
<commit_msg>Remove output when restarting apache after module enable<commit_after>import os
import yaml
def load_modules(data):
result = yaml.load(data)
if result:
apache = result.get('apache', {})
if apache:
return apache.get('modules', [])
return []
def install_modules(modules):
installed = 0
for module in modules:
print " Installing Apache module %s" % module
os.system("a2enmod "+module+" >/dev/null 2>&1")
installed = installed + 1
if installed > 0:
os.system('/etc/init.d/apache2 restart >/dev/null 2>&1')
print " Done enabling Apache modules."
else:
print " No Apache modules to enabled."
def load_file(working_dir="/home/application/current"):
files_name = ["app.yaml", "app.yml"]
for file_name in files_name:
try:
with open(os.path.join(working_dir, file_name)) as f:
return f.read()
except IOError:
pass
return ""
def main():
print ""
print ""
print ""
print "========================================"
print " Parsing Apache modules to enable"
print "========================================"
print ""
data = load_file()
modules = load_modules(data)
install_modules(modules)
main()
|
786957cf85a641d49b4cfcceef717ef229ac8238
|
tests/functional/test_requests.py
|
tests/functional/test_requests.py
|
import pytest
@pytest.mark.network
def test_timeout(script):
result = script.pip(
"--timeout",
"0.001",
"install",
"-vvv",
"INITools",
expect_error=True,
)
assert (
"Could not fetch URL https://pypi.org/simple/initools/: "
"connection error: HTTPSConnectionPool(host='pypi.org', port=443): "
"Max retries exceeded with url: /simple/initools/ "
) in result.stdout
|
import pytest
@pytest.mark.network
def test_timeout(script):
result = script.pip(
"--timeout",
"0.0001",
"install",
"-vvv",
"INITools",
expect_error=True,
)
assert (
"Could not fetch URL https://pypi.org/simple/initools/: "
"connection error: HTTPSConnectionPool(host='pypi.org', port=443): "
"Max retries exceeded with url: /simple/initools/ "
) in result.stdout
|
Use a shorter timeout, to ensure that this fails more often
|
Use a shorter timeout, to ensure that this fails more often
|
Python
|
mit
|
pypa/pip,sbidoul/pip,pradyunsg/pip,sbidoul/pip,pradyunsg/pip,pfmoore/pip,pypa/pip,pfmoore/pip
|
import pytest
@pytest.mark.network
def test_timeout(script):
result = script.pip(
"--timeout",
"0.001",
"install",
"-vvv",
"INITools",
expect_error=True,
)
assert (
"Could not fetch URL https://pypi.org/simple/initools/: "
"connection error: HTTPSConnectionPool(host='pypi.org', port=443): "
"Max retries exceeded with url: /simple/initools/ "
) in result.stdout
Use a shorter timeout, to ensure that this fails more often
|
import pytest
@pytest.mark.network
def test_timeout(script):
result = script.pip(
"--timeout",
"0.0001",
"install",
"-vvv",
"INITools",
expect_error=True,
)
assert (
"Could not fetch URL https://pypi.org/simple/initools/: "
"connection error: HTTPSConnectionPool(host='pypi.org', port=443): "
"Max retries exceeded with url: /simple/initools/ "
) in result.stdout
|
<commit_before>import pytest
@pytest.mark.network
def test_timeout(script):
result = script.pip(
"--timeout",
"0.001",
"install",
"-vvv",
"INITools",
expect_error=True,
)
assert (
"Could not fetch URL https://pypi.org/simple/initools/: "
"connection error: HTTPSConnectionPool(host='pypi.org', port=443): "
"Max retries exceeded with url: /simple/initools/ "
) in result.stdout
<commit_msg>Use a shorter timeout, to ensure that this fails more often<commit_after>
|
import pytest
@pytest.mark.network
def test_timeout(script):
result = script.pip(
"--timeout",
"0.0001",
"install",
"-vvv",
"INITools",
expect_error=True,
)
assert (
"Could not fetch URL https://pypi.org/simple/initools/: "
"connection error: HTTPSConnectionPool(host='pypi.org', port=443): "
"Max retries exceeded with url: /simple/initools/ "
) in result.stdout
|
import pytest
@pytest.mark.network
def test_timeout(script):
result = script.pip(
"--timeout",
"0.001",
"install",
"-vvv",
"INITools",
expect_error=True,
)
assert (
"Could not fetch URL https://pypi.org/simple/initools/: "
"connection error: HTTPSConnectionPool(host='pypi.org', port=443): "
"Max retries exceeded with url: /simple/initools/ "
) in result.stdout
Use a shorter timeout, to ensure that this fails more oftenimport pytest
@pytest.mark.network
def test_timeout(script):
result = script.pip(
"--timeout",
"0.0001",
"install",
"-vvv",
"INITools",
expect_error=True,
)
assert (
"Could not fetch URL https://pypi.org/simple/initools/: "
"connection error: HTTPSConnectionPool(host='pypi.org', port=443): "
"Max retries exceeded with url: /simple/initools/ "
) in result.stdout
|
<commit_before>import pytest
@pytest.mark.network
def test_timeout(script):
result = script.pip(
"--timeout",
"0.001",
"install",
"-vvv",
"INITools",
expect_error=True,
)
assert (
"Could not fetch URL https://pypi.org/simple/initools/: "
"connection error: HTTPSConnectionPool(host='pypi.org', port=443): "
"Max retries exceeded with url: /simple/initools/ "
) in result.stdout
<commit_msg>Use a shorter timeout, to ensure that this fails more often<commit_after>import pytest
@pytest.mark.network
def test_timeout(script):
result = script.pip(
"--timeout",
"0.0001",
"install",
"-vvv",
"INITools",
expect_error=True,
)
assert (
"Could not fetch URL https://pypi.org/simple/initools/: "
"connection error: HTTPSConnectionPool(host='pypi.org', port=443): "
"Max retries exceeded with url: /simple/initools/ "
) in result.stdout
|
efc857403d3c67589c1046d60e7f91132c844393
|
picdescbot/twitter.py
|
picdescbot/twitter.py
|
# coding=utf-8
# picdescbot: a tiny twitter/tumblr bot that tweets random pictures from wikipedia and their descriptions
# this file implements twitter-related functionality
# Copyright (C) 2016 Elad Alfassa <[email protected]>
import time
import tweepy
from . import logger
class Client(object):
name = "twitter"
def __init__(self, config):
auth = tweepy.OAuthHandler(config['consumer_key'],
config['consumer_secret'])
auth.set_access_token(config['token'], config['token_secret'])
self.api = tweepy.API(auth)
self.log = logger.get(__name__)
def send(self, picture):
"Send a tweet. `picture` is a `Result` object from `picdescbot.common`"
retries = 0
status = None
filename = picture.url.split('/')[-1]
data = picture.download_picture()
try:
while retries < 3 and not status:
if retries > 0:
self.log.info('retrying...')
data.seek(0)
try:
status = self.api.update_with_media(filename=filename,
status=picture.caption,
file=data)
except tweepy.TweepError as e:
self.log.error("Error when sending tweet: %s" % e)
retries += 1
if retries >= 3:
raise
else:
time.sleep(5)
finally:
data.close(really=True)
return status.id
|
# coding=utf-8
# picdescbot: a tiny twitter/tumblr bot that tweets random pictures from wikipedia and their descriptions
# this file implements twitter-related functionality
# Copyright (C) 2016 Elad Alfassa <[email protected]>
import time
import tweepy
from . import logger
class Client(object):
name = "twitter"
def __init__(self, config):
auth = tweepy.OAuthHandler(config['consumer_key'],
config['consumer_secret'])
auth.set_access_token(config['token'], config['token_secret'])
self.api = tweepy.API(auth)
self.log = logger.get(__name__)
def send(self, picture):
"Send a tweet. `picture` is a `Result` object from `picdescbot.common`"
retries = 0
status = None
filename = picture.url.split('/')[-1]
data = picture.download_picture()
try:
while retries < 3 and not status:
if retries > 0:
self.log.info('retrying...')
data.seek(0)
try:
text = f"{picture.caption}\n\n{picture.source_url}"
status = self.api.update_with_media(filename=filename,
status=text,
file=data)
except tweepy.TweepError as e:
self.log.error("Error when sending tweet: %s" % e)
retries += 1
if retries >= 3:
raise
else:
time.sleep(5)
finally:
data.close(really=True)
return status.id
|
Add source links for tweets
|
Add source links for tweets
|
Python
|
mit
|
elad661/picdescbot
|
# coding=utf-8
# picdescbot: a tiny twitter/tumblr bot that tweets random pictures from wikipedia and their descriptions
# this file implements twitter-related functionality
# Copyright (C) 2016 Elad Alfassa <[email protected]>
import time
import tweepy
from . import logger
class Client(object):
name = "twitter"
def __init__(self, config):
auth = tweepy.OAuthHandler(config['consumer_key'],
config['consumer_secret'])
auth.set_access_token(config['token'], config['token_secret'])
self.api = tweepy.API(auth)
self.log = logger.get(__name__)
def send(self, picture):
"Send a tweet. `picture` is a `Result` object from `picdescbot.common`"
retries = 0
status = None
filename = picture.url.split('/')[-1]
data = picture.download_picture()
try:
while retries < 3 and not status:
if retries > 0:
self.log.info('retrying...')
data.seek(0)
try:
status = self.api.update_with_media(filename=filename,
status=picture.caption,
file=data)
except tweepy.TweepError as e:
self.log.error("Error when sending tweet: %s" % e)
retries += 1
if retries >= 3:
raise
else:
time.sleep(5)
finally:
data.close(really=True)
return status.id
Add source links for tweets
|
# coding=utf-8
# picdescbot: a tiny twitter/tumblr bot that tweets random pictures from wikipedia and their descriptions
# this file implements twitter-related functionality
# Copyright (C) 2016 Elad Alfassa <[email protected]>
import time
import tweepy
from . import logger
class Client(object):
name = "twitter"
def __init__(self, config):
auth = tweepy.OAuthHandler(config['consumer_key'],
config['consumer_secret'])
auth.set_access_token(config['token'], config['token_secret'])
self.api = tweepy.API(auth)
self.log = logger.get(__name__)
def send(self, picture):
"Send a tweet. `picture` is a `Result` object from `picdescbot.common`"
retries = 0
status = None
filename = picture.url.split('/')[-1]
data = picture.download_picture()
try:
while retries < 3 and not status:
if retries > 0:
self.log.info('retrying...')
data.seek(0)
try:
text = f"{picture.caption}\n\n{picture.source_url}"
status = self.api.update_with_media(filename=filename,
status=text,
file=data)
except tweepy.TweepError as e:
self.log.error("Error when sending tweet: %s" % e)
retries += 1
if retries >= 3:
raise
else:
time.sleep(5)
finally:
data.close(really=True)
return status.id
|
<commit_before># coding=utf-8
# picdescbot: a tiny twitter/tumblr bot that tweets random pictures from wikipedia and their descriptions
# this file implements twitter-related functionality
# Copyright (C) 2016 Elad Alfassa <[email protected]>
import time
import tweepy
from . import logger
class Client(object):
name = "twitter"
def __init__(self, config):
auth = tweepy.OAuthHandler(config['consumer_key'],
config['consumer_secret'])
auth.set_access_token(config['token'], config['token_secret'])
self.api = tweepy.API(auth)
self.log = logger.get(__name__)
def send(self, picture):
"Send a tweet. `picture` is a `Result` object from `picdescbot.common`"
retries = 0
status = None
filename = picture.url.split('/')[-1]
data = picture.download_picture()
try:
while retries < 3 and not status:
if retries > 0:
self.log.info('retrying...')
data.seek(0)
try:
status = self.api.update_with_media(filename=filename,
status=picture.caption,
file=data)
except tweepy.TweepError as e:
self.log.error("Error when sending tweet: %s" % e)
retries += 1
if retries >= 3:
raise
else:
time.sleep(5)
finally:
data.close(really=True)
return status.id
<commit_msg>Add source links for tweets<commit_after>
|
# coding=utf-8
# picdescbot: a tiny twitter/tumblr bot that tweets random pictures from wikipedia and their descriptions
# this file implements twitter-related functionality
# Copyright (C) 2016 Elad Alfassa <[email protected]>
import time
import tweepy
from . import logger
class Client(object):
name = "twitter"
def __init__(self, config):
auth = tweepy.OAuthHandler(config['consumer_key'],
config['consumer_secret'])
auth.set_access_token(config['token'], config['token_secret'])
self.api = tweepy.API(auth)
self.log = logger.get(__name__)
def send(self, picture):
"Send a tweet. `picture` is a `Result` object from `picdescbot.common`"
retries = 0
status = None
filename = picture.url.split('/')[-1]
data = picture.download_picture()
try:
while retries < 3 and not status:
if retries > 0:
self.log.info('retrying...')
data.seek(0)
try:
text = f"{picture.caption}\n\n{picture.source_url}"
status = self.api.update_with_media(filename=filename,
status=text,
file=data)
except tweepy.TweepError as e:
self.log.error("Error when sending tweet: %s" % e)
retries += 1
if retries >= 3:
raise
else:
time.sleep(5)
finally:
data.close(really=True)
return status.id
|
# coding=utf-8
# picdescbot: a tiny twitter/tumblr bot that tweets random pictures from wikipedia and their descriptions
# this file implements twitter-related functionality
# Copyright (C) 2016 Elad Alfassa <[email protected]>
import time
import tweepy
from . import logger
class Client(object):
name = "twitter"
def __init__(self, config):
auth = tweepy.OAuthHandler(config['consumer_key'],
config['consumer_secret'])
auth.set_access_token(config['token'], config['token_secret'])
self.api = tweepy.API(auth)
self.log = logger.get(__name__)
def send(self, picture):
"Send a tweet. `picture` is a `Result` object from `picdescbot.common`"
retries = 0
status = None
filename = picture.url.split('/')[-1]
data = picture.download_picture()
try:
while retries < 3 and not status:
if retries > 0:
self.log.info('retrying...')
data.seek(0)
try:
status = self.api.update_with_media(filename=filename,
status=picture.caption,
file=data)
except tweepy.TweepError as e:
self.log.error("Error when sending tweet: %s" % e)
retries += 1
if retries >= 3:
raise
else:
time.sleep(5)
finally:
data.close(really=True)
return status.id
Add source links for tweets# coding=utf-8
# picdescbot: a tiny twitter/tumblr bot that tweets random pictures from wikipedia and their descriptions
# this file implements twitter-related functionality
# Copyright (C) 2016 Elad Alfassa <[email protected]>
import time
import tweepy
from . import logger
class Client(object):
name = "twitter"
def __init__(self, config):
auth = tweepy.OAuthHandler(config['consumer_key'],
config['consumer_secret'])
auth.set_access_token(config['token'], config['token_secret'])
self.api = tweepy.API(auth)
self.log = logger.get(__name__)
def send(self, picture):
"Send a tweet. `picture` is a `Result` object from `picdescbot.common`"
retries = 0
status = None
filename = picture.url.split('/')[-1]
data = picture.download_picture()
try:
while retries < 3 and not status:
if retries > 0:
self.log.info('retrying...')
data.seek(0)
try:
text = f"{picture.caption}\n\n{picture.source_url}"
status = self.api.update_with_media(filename=filename,
status=text,
file=data)
except tweepy.TweepError as e:
self.log.error("Error when sending tweet: %s" % e)
retries += 1
if retries >= 3:
raise
else:
time.sleep(5)
finally:
data.close(really=True)
return status.id
|
<commit_before># coding=utf-8
# picdescbot: a tiny twitter/tumblr bot that tweets random pictures from wikipedia and their descriptions
# this file implements twitter-related functionality
# Copyright (C) 2016 Elad Alfassa <[email protected]>
import time
import tweepy
from . import logger
class Client(object):
name = "twitter"
def __init__(self, config):
auth = tweepy.OAuthHandler(config['consumer_key'],
config['consumer_secret'])
auth.set_access_token(config['token'], config['token_secret'])
self.api = tweepy.API(auth)
self.log = logger.get(__name__)
def send(self, picture):
"Send a tweet. `picture` is a `Result` object from `picdescbot.common`"
retries = 0
status = None
filename = picture.url.split('/')[-1]
data = picture.download_picture()
try:
while retries < 3 and not status:
if retries > 0:
self.log.info('retrying...')
data.seek(0)
try:
status = self.api.update_with_media(filename=filename,
status=picture.caption,
file=data)
except tweepy.TweepError as e:
self.log.error("Error when sending tweet: %s" % e)
retries += 1
if retries >= 3:
raise
else:
time.sleep(5)
finally:
data.close(really=True)
return status.id
<commit_msg>Add source links for tweets<commit_after># coding=utf-8
# picdescbot: a tiny twitter/tumblr bot that tweets random pictures from wikipedia and their descriptions
# this file implements twitter-related functionality
# Copyright (C) 2016 Elad Alfassa <[email protected]>
import time
import tweepy
from . import logger
class Client(object):
name = "twitter"
def __init__(self, config):
auth = tweepy.OAuthHandler(config['consumer_key'],
config['consumer_secret'])
auth.set_access_token(config['token'], config['token_secret'])
self.api = tweepy.API(auth)
self.log = logger.get(__name__)
def send(self, picture):
"Send a tweet. `picture` is a `Result` object from `picdescbot.common`"
retries = 0
status = None
filename = picture.url.split('/')[-1]
data = picture.download_picture()
try:
while retries < 3 and not status:
if retries > 0:
self.log.info('retrying...')
data.seek(0)
try:
text = f"{picture.caption}\n\n{picture.source_url}"
status = self.api.update_with_media(filename=filename,
status=text,
file=data)
except tweepy.TweepError as e:
self.log.error("Error when sending tweet: %s" % e)
retries += 1
if retries >= 3:
raise
else:
time.sleep(5)
finally:
data.close(really=True)
return status.id
|
e40a8ce30f574a8e2745fdf2c1a74e4f1c00bc0d
|
cached_counts/tests.py
|
cached_counts/tests.py
|
import unittest
from django.test import TestCase
from candidates.tests.test_create_person import mock_create_person
from .models import CachedCount
class CachedCountTechCase(TestCase):
def setUp(self):
initial_counts = (
{
'count_type': 'constituency',
'name': 'Dulwich and West Norwood',
'count': 10,
'object_id': '65808'
},
{
'count_type': 'party',
'name': 'Labour',
'count': 0,
'object_id': 'party:53'
},
)
for count in initial_counts:
CachedCount(**count).save()
def test_object_urls(self):
for count in CachedCount.objects.filter(count_type='constituency'):
self.assertTrue(count.object_url)
def test_increment_count(self):
self.assertEqual(CachedCount.objects.get(object_id='party:53').count, 0)
self.assertEqual(CachedCount.objects.get(object_id='65808').count, 10)
mock_create_person()
self.assertEqual(CachedCount.objects.get(object_id='65808').count, 11)
self.assertEqual(CachedCount.objects.get(object_id='party:53').count, 1)
|
import unittest
from django.test import TestCase
from candidates.tests.test_create_person import mock_create_person
from .models import CachedCount
def create_initial_counts(extra=()):
initial_counts = (
{
'count_type': 'constituency',
'name': 'Dulwich and West Norwood',
'count': 10,
'object_id': '65808'
},
{
'count_type': 'party',
'name': 'Labour',
'count': 0,
'object_id': 'party:53'
},
)
initial_counts = initial_counts + extra
for count in initial_counts:
CachedCount(**count).save()
class CachedCountTechCase(TestCase):
def setUp(self):
create_initial_counts()
def test_object_urls(self):
for count in CachedCount.objects.filter(count_type='constituency'):
self.assertTrue(count.object_url)
def test_increment_count(self):
self.assertEqual(CachedCount.objects.get(object_id='party:53').count, 0)
self.assertEqual(CachedCount.objects.get(object_id='65808').count, 10)
mock_create_person()
self.assertEqual(CachedCount.objects.get(object_id='65808').count, 11)
self.assertEqual(CachedCount.objects.get(object_id='party:53').count, 1)
|
Create initial counts outside the test class
|
Create initial counts outside the test class
|
Python
|
agpl-3.0
|
mysociety/yournextmp-popit,DemocracyClub/yournextrepresentative,openstate/yournextrepresentative,openstate/yournextrepresentative,YoQuieroSaber/yournextrepresentative,neavouli/yournextrepresentative,DemocracyClub/yournextrepresentative,openstate/yournextrepresentative,mysociety/yournextmp-popit,neavouli/yournextrepresentative,neavouli/yournextrepresentative,mysociety/yournextrepresentative,neavouli/yournextrepresentative,YoQuieroSaber/yournextrepresentative,YoQuieroSaber/yournextrepresentative,mysociety/yournextmp-popit,datamade/yournextmp-popit,DemocracyClub/yournextrepresentative,openstate/yournextrepresentative,YoQuieroSaber/yournextrepresentative,openstate/yournextrepresentative,mysociety/yournextrepresentative,mysociety/yournextmp-popit,datamade/yournextmp-popit,YoQuieroSaber/yournextrepresentative,datamade/yournextmp-popit,datamade/yournextmp-popit,mysociety/yournextmp-popit,neavouli/yournextrepresentative,mysociety/yournextrepresentative,mysociety/yournextrepresentative,datamade/yournextmp-popit,mysociety/yournextrepresentative
|
import unittest
from django.test import TestCase
from candidates.tests.test_create_person import mock_create_person
from .models import CachedCount
class CachedCountTechCase(TestCase):
def setUp(self):
initial_counts = (
{
'count_type': 'constituency',
'name': 'Dulwich and West Norwood',
'count': 10,
'object_id': '65808'
},
{
'count_type': 'party',
'name': 'Labour',
'count': 0,
'object_id': 'party:53'
},
)
for count in initial_counts:
CachedCount(**count).save()
def test_object_urls(self):
for count in CachedCount.objects.filter(count_type='constituency'):
self.assertTrue(count.object_url)
def test_increment_count(self):
self.assertEqual(CachedCount.objects.get(object_id='party:53').count, 0)
self.assertEqual(CachedCount.objects.get(object_id='65808').count, 10)
mock_create_person()
self.assertEqual(CachedCount.objects.get(object_id='65808').count, 11)
self.assertEqual(CachedCount.objects.get(object_id='party:53').count, 1)
Create initial counts outside the test class
|
import unittest
from django.test import TestCase
from candidates.tests.test_create_person import mock_create_person
from .models import CachedCount
def create_initial_counts(extra=()):
initial_counts = (
{
'count_type': 'constituency',
'name': 'Dulwich and West Norwood',
'count': 10,
'object_id': '65808'
},
{
'count_type': 'party',
'name': 'Labour',
'count': 0,
'object_id': 'party:53'
},
)
initial_counts = initial_counts + extra
for count in initial_counts:
CachedCount(**count).save()
class CachedCountTechCase(TestCase):
def setUp(self):
create_initial_counts()
def test_object_urls(self):
for count in CachedCount.objects.filter(count_type='constituency'):
self.assertTrue(count.object_url)
def test_increment_count(self):
self.assertEqual(CachedCount.objects.get(object_id='party:53').count, 0)
self.assertEqual(CachedCount.objects.get(object_id='65808').count, 10)
mock_create_person()
self.assertEqual(CachedCount.objects.get(object_id='65808').count, 11)
self.assertEqual(CachedCount.objects.get(object_id='party:53').count, 1)
|
<commit_before>import unittest
from django.test import TestCase
from candidates.tests.test_create_person import mock_create_person
from .models import CachedCount
class CachedCountTechCase(TestCase):
def setUp(self):
initial_counts = (
{
'count_type': 'constituency',
'name': 'Dulwich and West Norwood',
'count': 10,
'object_id': '65808'
},
{
'count_type': 'party',
'name': 'Labour',
'count': 0,
'object_id': 'party:53'
},
)
for count in initial_counts:
CachedCount(**count).save()
def test_object_urls(self):
for count in CachedCount.objects.filter(count_type='constituency'):
self.assertTrue(count.object_url)
def test_increment_count(self):
self.assertEqual(CachedCount.objects.get(object_id='party:53').count, 0)
self.assertEqual(CachedCount.objects.get(object_id='65808').count, 10)
mock_create_person()
self.assertEqual(CachedCount.objects.get(object_id='65808').count, 11)
self.assertEqual(CachedCount.objects.get(object_id='party:53').count, 1)
<commit_msg>Create initial counts outside the test class<commit_after>
|
import unittest
from django.test import TestCase
from candidates.tests.test_create_person import mock_create_person
from .models import CachedCount
def create_initial_counts(extra=()):
initial_counts = (
{
'count_type': 'constituency',
'name': 'Dulwich and West Norwood',
'count': 10,
'object_id': '65808'
},
{
'count_type': 'party',
'name': 'Labour',
'count': 0,
'object_id': 'party:53'
},
)
initial_counts = initial_counts + extra
for count in initial_counts:
CachedCount(**count).save()
class CachedCountTechCase(TestCase):
def setUp(self):
create_initial_counts()
def test_object_urls(self):
for count in CachedCount.objects.filter(count_type='constituency'):
self.assertTrue(count.object_url)
def test_increment_count(self):
self.assertEqual(CachedCount.objects.get(object_id='party:53').count, 0)
self.assertEqual(CachedCount.objects.get(object_id='65808').count, 10)
mock_create_person()
self.assertEqual(CachedCount.objects.get(object_id='65808').count, 11)
self.assertEqual(CachedCount.objects.get(object_id='party:53').count, 1)
|
import unittest
from django.test import TestCase
from candidates.tests.test_create_person import mock_create_person
from .models import CachedCount
class CachedCountTechCase(TestCase):
def setUp(self):
initial_counts = (
{
'count_type': 'constituency',
'name': 'Dulwich and West Norwood',
'count': 10,
'object_id': '65808'
},
{
'count_type': 'party',
'name': 'Labour',
'count': 0,
'object_id': 'party:53'
},
)
for count in initial_counts:
CachedCount(**count).save()
def test_object_urls(self):
for count in CachedCount.objects.filter(count_type='constituency'):
self.assertTrue(count.object_url)
def test_increment_count(self):
self.assertEqual(CachedCount.objects.get(object_id='party:53').count, 0)
self.assertEqual(CachedCount.objects.get(object_id='65808').count, 10)
mock_create_person()
self.assertEqual(CachedCount.objects.get(object_id='65808').count, 11)
self.assertEqual(CachedCount.objects.get(object_id='party:53').count, 1)
Create initial counts outside the test classimport unittest
from django.test import TestCase
from candidates.tests.test_create_person import mock_create_person
from .models import CachedCount
def create_initial_counts(extra=()):
initial_counts = (
{
'count_type': 'constituency',
'name': 'Dulwich and West Norwood',
'count': 10,
'object_id': '65808'
},
{
'count_type': 'party',
'name': 'Labour',
'count': 0,
'object_id': 'party:53'
},
)
initial_counts = initial_counts + extra
for count in initial_counts:
CachedCount(**count).save()
class CachedCountTechCase(TestCase):
def setUp(self):
create_initial_counts()
def test_object_urls(self):
for count in CachedCount.objects.filter(count_type='constituency'):
self.assertTrue(count.object_url)
def test_increment_count(self):
self.assertEqual(CachedCount.objects.get(object_id='party:53').count, 0)
self.assertEqual(CachedCount.objects.get(object_id='65808').count, 10)
mock_create_person()
self.assertEqual(CachedCount.objects.get(object_id='65808').count, 11)
self.assertEqual(CachedCount.objects.get(object_id='party:53').count, 1)
|
<commit_before>import unittest
from django.test import TestCase
from candidates.tests.test_create_person import mock_create_person
from .models import CachedCount
class CachedCountTechCase(TestCase):
def setUp(self):
initial_counts = (
{
'count_type': 'constituency',
'name': 'Dulwich and West Norwood',
'count': 10,
'object_id': '65808'
},
{
'count_type': 'party',
'name': 'Labour',
'count': 0,
'object_id': 'party:53'
},
)
for count in initial_counts:
CachedCount(**count).save()
def test_object_urls(self):
for count in CachedCount.objects.filter(count_type='constituency'):
self.assertTrue(count.object_url)
def test_increment_count(self):
self.assertEqual(CachedCount.objects.get(object_id='party:53').count, 0)
self.assertEqual(CachedCount.objects.get(object_id='65808').count, 10)
mock_create_person()
self.assertEqual(CachedCount.objects.get(object_id='65808').count, 11)
self.assertEqual(CachedCount.objects.get(object_id='party:53').count, 1)
<commit_msg>Create initial counts outside the test class<commit_after>import unittest
from django.test import TestCase
from candidates.tests.test_create_person import mock_create_person
from .models import CachedCount
def create_initial_counts(extra=()):
initial_counts = (
{
'count_type': 'constituency',
'name': 'Dulwich and West Norwood',
'count': 10,
'object_id': '65808'
},
{
'count_type': 'party',
'name': 'Labour',
'count': 0,
'object_id': 'party:53'
},
)
initial_counts = initial_counts + extra
for count in initial_counts:
CachedCount(**count).save()
class CachedCountTechCase(TestCase):
def setUp(self):
create_initial_counts()
def test_object_urls(self):
for count in CachedCount.objects.filter(count_type='constituency'):
self.assertTrue(count.object_url)
def test_increment_count(self):
self.assertEqual(CachedCount.objects.get(object_id='party:53').count, 0)
self.assertEqual(CachedCount.objects.get(object_id='65808').count, 10)
mock_create_person()
self.assertEqual(CachedCount.objects.get(object_id='65808').count, 11)
self.assertEqual(CachedCount.objects.get(object_id='party:53').count, 1)
|
df57dacf8f5ec7f697247fed39ce86d3cde45615
|
tests/tests_plotting/test_misc.py
|
tests/tests_plotting/test_misc.py
|
import pytest
from matplotlib import pyplot as plt
from poliastro.plotting import OrbitPlotter2D, OrbitPlotter3D
from poliastro.plotting.misc import plot_solar_system
@pytest.mark.parametrize("outer,expected", [(True, 8), (False, 4)])
def test_plot_solar_system_has_expected_number_of_orbits(outer, expected):
assert len(plot_solar_system(outer).trajectories) == expected
@pytest.mark.parametrize(
"use_3d, plotter_class", [(True, OrbitPlotter3D), (False, OrbitPlotter2D)]
)
def test_plot_solar_system_uses_expected_orbitplotter(use_3d, plotter_class):
assert isinstance(plot_solar_system(use_3d=use_3d, interactive=True), plotter_class)
@pytest.mark.mpl_image_compare
def test_plot_inner_solar_system_static(earth_perihelion):
plot_solar_system(outer=False, epoch=earth_perihelion)
return plt.gcf()
@pytest.mark.mpl_image_compare
def test_plot_outer_solar_system_static(earth_perihelion):
plot_solar_system(outer=True, epoch=earth_perihelion)
return plt.gcf()
|
import pytest
from matplotlib import pyplot as plt
from poliastro.plotting import OrbitPlotter2D, OrbitPlotter3D
from poliastro.plotting.misc import plot_solar_system
@pytest.mark.parametrize("outer,expected", [(True, 8), (False, 4)])
def test_plot_solar_system_has_expected_number_of_orbits(outer, expected):
assert len(plot_solar_system(outer).trajectories) == expected
@pytest.mark.parametrize(
"use_3d, plotter_class", [(True, OrbitPlotter3D), (False, OrbitPlotter2D)]
)
def test_plot_solar_system_uses_expected_orbitplotter(use_3d, plotter_class):
assert isinstance(plot_solar_system(use_3d=use_3d, interactive=True), plotter_class)
if use_3d:
with pytest.raises(ValueError) as excinfo:
plot_solar_system(use_3d=use_3d)
assert ("The static plotter does not support 3D" in excinfo.exconly())
@pytest.mark.mpl_image_compare
def test_plot_inner_solar_system_static(earth_perihelion):
plot_solar_system(outer=False, epoch=earth_perihelion)
return plt.gcf()
@pytest.mark.mpl_image_compare
def test_plot_outer_solar_system_static(earth_perihelion):
plot_solar_system(outer=True, epoch=earth_perihelion)
return plt.gcf()
|
Check for error if use_3D and non-interactive
|
Check for error if use_3D and non-interactive
|
Python
|
mit
|
poliastro/poliastro
|
import pytest
from matplotlib import pyplot as plt
from poliastro.plotting import OrbitPlotter2D, OrbitPlotter3D
from poliastro.plotting.misc import plot_solar_system
@pytest.mark.parametrize("outer,expected", [(True, 8), (False, 4)])
def test_plot_solar_system_has_expected_number_of_orbits(outer, expected):
assert len(plot_solar_system(outer).trajectories) == expected
@pytest.mark.parametrize(
"use_3d, plotter_class", [(True, OrbitPlotter3D), (False, OrbitPlotter2D)]
)
def test_plot_solar_system_uses_expected_orbitplotter(use_3d, plotter_class):
assert isinstance(plot_solar_system(use_3d=use_3d, interactive=True), plotter_class)
@pytest.mark.mpl_image_compare
def test_plot_inner_solar_system_static(earth_perihelion):
plot_solar_system(outer=False, epoch=earth_perihelion)
return plt.gcf()
@pytest.mark.mpl_image_compare
def test_plot_outer_solar_system_static(earth_perihelion):
plot_solar_system(outer=True, epoch=earth_perihelion)
return plt.gcf()
Check for error if use_3D and non-interactive
|
import pytest
from matplotlib import pyplot as plt
from poliastro.plotting import OrbitPlotter2D, OrbitPlotter3D
from poliastro.plotting.misc import plot_solar_system
@pytest.mark.parametrize("outer,expected", [(True, 8), (False, 4)])
def test_plot_solar_system_has_expected_number_of_orbits(outer, expected):
assert len(plot_solar_system(outer).trajectories) == expected
@pytest.mark.parametrize(
"use_3d, plotter_class", [(True, OrbitPlotter3D), (False, OrbitPlotter2D)]
)
def test_plot_solar_system_uses_expected_orbitplotter(use_3d, plotter_class):
assert isinstance(plot_solar_system(use_3d=use_3d, interactive=True), plotter_class)
if use_3d:
with pytest.raises(ValueError) as excinfo:
plot_solar_system(use_3d=use_3d)
assert ("The static plotter does not support 3D" in excinfo.exconly())
@pytest.mark.mpl_image_compare
def test_plot_inner_solar_system_static(earth_perihelion):
plot_solar_system(outer=False, epoch=earth_perihelion)
return plt.gcf()
@pytest.mark.mpl_image_compare
def test_plot_outer_solar_system_static(earth_perihelion):
plot_solar_system(outer=True, epoch=earth_perihelion)
return plt.gcf()
|
<commit_before>import pytest
from matplotlib import pyplot as plt
from poliastro.plotting import OrbitPlotter2D, OrbitPlotter3D
from poliastro.plotting.misc import plot_solar_system
@pytest.mark.parametrize("outer,expected", [(True, 8), (False, 4)])
def test_plot_solar_system_has_expected_number_of_orbits(outer, expected):
assert len(plot_solar_system(outer).trajectories) == expected
@pytest.mark.parametrize(
"use_3d, plotter_class", [(True, OrbitPlotter3D), (False, OrbitPlotter2D)]
)
def test_plot_solar_system_uses_expected_orbitplotter(use_3d, plotter_class):
assert isinstance(plot_solar_system(use_3d=use_3d, interactive=True), plotter_class)
@pytest.mark.mpl_image_compare
def test_plot_inner_solar_system_static(earth_perihelion):
plot_solar_system(outer=False, epoch=earth_perihelion)
return plt.gcf()
@pytest.mark.mpl_image_compare
def test_plot_outer_solar_system_static(earth_perihelion):
plot_solar_system(outer=True, epoch=earth_perihelion)
return plt.gcf()
<commit_msg>Check for error if use_3D and non-interactive<commit_after>
|
import pytest
from matplotlib import pyplot as plt
from poliastro.plotting import OrbitPlotter2D, OrbitPlotter3D
from poliastro.plotting.misc import plot_solar_system
@pytest.mark.parametrize("outer,expected", [(True, 8), (False, 4)])
def test_plot_solar_system_has_expected_number_of_orbits(outer, expected):
assert len(plot_solar_system(outer).trajectories) == expected
@pytest.mark.parametrize(
"use_3d, plotter_class", [(True, OrbitPlotter3D), (False, OrbitPlotter2D)]
)
def test_plot_solar_system_uses_expected_orbitplotter(use_3d, plotter_class):
assert isinstance(plot_solar_system(use_3d=use_3d, interactive=True), plotter_class)
if use_3d:
with pytest.raises(ValueError) as excinfo:
plot_solar_system(use_3d=use_3d)
assert ("The static plotter does not support 3D" in excinfo.exconly())
@pytest.mark.mpl_image_compare
def test_plot_inner_solar_system_static(earth_perihelion):
plot_solar_system(outer=False, epoch=earth_perihelion)
return plt.gcf()
@pytest.mark.mpl_image_compare
def test_plot_outer_solar_system_static(earth_perihelion):
plot_solar_system(outer=True, epoch=earth_perihelion)
return plt.gcf()
|
import pytest
from matplotlib import pyplot as plt
from poliastro.plotting import OrbitPlotter2D, OrbitPlotter3D
from poliastro.plotting.misc import plot_solar_system
@pytest.mark.parametrize("outer,expected", [(True, 8), (False, 4)])
def test_plot_solar_system_has_expected_number_of_orbits(outer, expected):
assert len(plot_solar_system(outer).trajectories) == expected
@pytest.mark.parametrize(
"use_3d, plotter_class", [(True, OrbitPlotter3D), (False, OrbitPlotter2D)]
)
def test_plot_solar_system_uses_expected_orbitplotter(use_3d, plotter_class):
assert isinstance(plot_solar_system(use_3d=use_3d, interactive=True), plotter_class)
@pytest.mark.mpl_image_compare
def test_plot_inner_solar_system_static(earth_perihelion):
plot_solar_system(outer=False, epoch=earth_perihelion)
return plt.gcf()
@pytest.mark.mpl_image_compare
def test_plot_outer_solar_system_static(earth_perihelion):
plot_solar_system(outer=True, epoch=earth_perihelion)
return plt.gcf()
Check for error if use_3D and non-interactiveimport pytest
from matplotlib import pyplot as plt
from poliastro.plotting import OrbitPlotter2D, OrbitPlotter3D
from poliastro.plotting.misc import plot_solar_system
@pytest.mark.parametrize("outer,expected", [(True, 8), (False, 4)])
def test_plot_solar_system_has_expected_number_of_orbits(outer, expected):
assert len(plot_solar_system(outer).trajectories) == expected
@pytest.mark.parametrize(
"use_3d, plotter_class", [(True, OrbitPlotter3D), (False, OrbitPlotter2D)]
)
def test_plot_solar_system_uses_expected_orbitplotter(use_3d, plotter_class):
assert isinstance(plot_solar_system(use_3d=use_3d, interactive=True), plotter_class)
if use_3d:
with pytest.raises(ValueError) as excinfo:
plot_solar_system(use_3d=use_3d)
assert ("The static plotter does not support 3D" in excinfo.exconly())
@pytest.mark.mpl_image_compare
def test_plot_inner_solar_system_static(earth_perihelion):
plot_solar_system(outer=False, epoch=earth_perihelion)
return plt.gcf()
@pytest.mark.mpl_image_compare
def test_plot_outer_solar_system_static(earth_perihelion):
plot_solar_system(outer=True, epoch=earth_perihelion)
return plt.gcf()
|
<commit_before>import pytest
from matplotlib import pyplot as plt
from poliastro.plotting import OrbitPlotter2D, OrbitPlotter3D
from poliastro.plotting.misc import plot_solar_system
@pytest.mark.parametrize("outer,expected", [(True, 8), (False, 4)])
def test_plot_solar_system_has_expected_number_of_orbits(outer, expected):
assert len(plot_solar_system(outer).trajectories) == expected
@pytest.mark.parametrize(
"use_3d, plotter_class", [(True, OrbitPlotter3D), (False, OrbitPlotter2D)]
)
def test_plot_solar_system_uses_expected_orbitplotter(use_3d, plotter_class):
assert isinstance(plot_solar_system(use_3d=use_3d, interactive=True), plotter_class)
@pytest.mark.mpl_image_compare
def test_plot_inner_solar_system_static(earth_perihelion):
plot_solar_system(outer=False, epoch=earth_perihelion)
return plt.gcf()
@pytest.mark.mpl_image_compare
def test_plot_outer_solar_system_static(earth_perihelion):
plot_solar_system(outer=True, epoch=earth_perihelion)
return plt.gcf()
<commit_msg>Check for error if use_3D and non-interactive<commit_after>import pytest
from matplotlib import pyplot as plt
from poliastro.plotting import OrbitPlotter2D, OrbitPlotter3D
from poliastro.plotting.misc import plot_solar_system
@pytest.mark.parametrize("outer,expected", [(True, 8), (False, 4)])
def test_plot_solar_system_has_expected_number_of_orbits(outer, expected):
assert len(plot_solar_system(outer).trajectories) == expected
@pytest.mark.parametrize(
"use_3d, plotter_class", [(True, OrbitPlotter3D), (False, OrbitPlotter2D)]
)
def test_plot_solar_system_uses_expected_orbitplotter(use_3d, plotter_class):
assert isinstance(plot_solar_system(use_3d=use_3d, interactive=True), plotter_class)
if use_3d:
with pytest.raises(ValueError) as excinfo:
plot_solar_system(use_3d=use_3d)
assert ("The static plotter does not support 3D" in excinfo.exconly())
@pytest.mark.mpl_image_compare
def test_plot_inner_solar_system_static(earth_perihelion):
plot_solar_system(outer=False, epoch=earth_perihelion)
return plt.gcf()
@pytest.mark.mpl_image_compare
def test_plot_outer_solar_system_static(earth_perihelion):
plot_solar_system(outer=True, epoch=earth_perihelion)
return plt.gcf()
|
fae9990c2cd12ebc65abb9cbabe1b53fde9b4eec
|
wtforms/ext/i18n/form.py
|
wtforms/ext/i18n/form.py
|
import warnings
from wtforms import form
from wtforms.ext.i18n.utils import get_translations
translations_cache = {}
class Form(form.Form):
"""
Base form for a simple localized WTForms form.
This will use the stdlib gettext library to retrieve an appropriate
translations object for the language, by default using the locale
information from the environment.
If the LANGUAGES class variable is overridden and set to a sequence of
strings, this will be a list of languages by priority to use instead, e.g::
LANGUAGES = ['en_GB', 'en']
One can also provide the languages by passing `LANGUAGES=` to the
constructor of the form.
Translations objects are cached to prevent having to get a new one for the
same languages every instantiation.
"""
LANGUAGES = None
def __init__(self, *args, **kwargs):
warnings.warn('wtforms.ext.i18n will be removed in WTForms 1.2', DeprecationWarning)
super(Form, self).__init__(*args, **kwargs)
def _get_translations(self):
languages = tuple(self.LANGUAGES) if self.LANGUAGES else None
if languages not in translations_cache:
translations_cache[languages] = get_translations(languages)
return translations_cache[languages]
|
import warnings
from wtforms import form
from wtforms.ext.i18n.utils import get_translations
translations_cache = {}
class Form(form.Form):
"""
Base form for a simple localized WTForms form.
**NOTE** this class is now un-necessary as the i18n features have
been moved into the core of WTForms, but it will be kept for
compatibility reasons until WTForms 1.2.
This will use the stdlib gettext library to retrieve an appropriate
translations object for the language, by default using the locale
information from the environment.
If the LANGUAGES class variable is overridden and set to a sequence of
strings, this will be a list of languages by priority to use instead, e.g::
LANGUAGES = ['en_GB', 'en']
One can also provide the languages by passing `LANGUAGES=` to the
constructor of the form.
Translations objects are cached to prevent having to get a new one for the
same languages every instantiation.
"""
LANGUAGES = None
def __init__(self, *args, **kwargs):
warnings.warn('i18n is now in core, wtforms.ext.i18n will be removed in WTForms 1.2', DeprecationWarning)
super(Form, self).__init__(*args, **kwargs)
def _get_translations(self):
languages = tuple(self.LANGUAGES) if self.LANGUAGES else None
if languages not in translations_cache:
translations_cache[languages] = get_translations(languages)
return translations_cache[languages]
|
Make documentation more explicit for WTForms deprecation.
|
Make documentation more explicit for WTForms deprecation.
|
Python
|
bsd-3-clause
|
cklein/wtforms,jmagnusson/wtforms,crast/wtforms,pawl/wtforms,subyraman/wtforms,Aaron1992/wtforms,hsum/wtforms,wtforms/wtforms,Xender/wtforms,skytreader/wtforms,pawl/wtforms,Aaron1992/wtforms
|
import warnings
from wtforms import form
from wtforms.ext.i18n.utils import get_translations
translations_cache = {}
class Form(form.Form):
"""
Base form for a simple localized WTForms form.
This will use the stdlib gettext library to retrieve an appropriate
translations object for the language, by default using the locale
information from the environment.
If the LANGUAGES class variable is overridden and set to a sequence of
strings, this will be a list of languages by priority to use instead, e.g::
LANGUAGES = ['en_GB', 'en']
One can also provide the languages by passing `LANGUAGES=` to the
constructor of the form.
Translations objects are cached to prevent having to get a new one for the
same languages every instantiation.
"""
LANGUAGES = None
def __init__(self, *args, **kwargs):
warnings.warn('wtforms.ext.i18n will be removed in WTForms 1.2', DeprecationWarning)
super(Form, self).__init__(*args, **kwargs)
def _get_translations(self):
languages = tuple(self.LANGUAGES) if self.LANGUAGES else None
if languages not in translations_cache:
translations_cache[languages] = get_translations(languages)
return translations_cache[languages]
Make documentation more explicit for WTForms deprecation.
|
import warnings
from wtforms import form
from wtforms.ext.i18n.utils import get_translations
translations_cache = {}
class Form(form.Form):
"""
Base form for a simple localized WTForms form.
**NOTE** this class is now un-necessary as the i18n features have
been moved into the core of WTForms, but it will be kept for
compatibility reasons until WTForms 1.2.
This will use the stdlib gettext library to retrieve an appropriate
translations object for the language, by default using the locale
information from the environment.
If the LANGUAGES class variable is overridden and set to a sequence of
strings, this will be a list of languages by priority to use instead, e.g::
LANGUAGES = ['en_GB', 'en']
One can also provide the languages by passing `LANGUAGES=` to the
constructor of the form.
Translations objects are cached to prevent having to get a new one for the
same languages every instantiation.
"""
LANGUAGES = None
def __init__(self, *args, **kwargs):
warnings.warn('i18n is now in core, wtforms.ext.i18n will be removed in WTForms 1.2', DeprecationWarning)
super(Form, self).__init__(*args, **kwargs)
def _get_translations(self):
languages = tuple(self.LANGUAGES) if self.LANGUAGES else None
if languages not in translations_cache:
translations_cache[languages] = get_translations(languages)
return translations_cache[languages]
|
<commit_before>import warnings
from wtforms import form
from wtforms.ext.i18n.utils import get_translations
translations_cache = {}
class Form(form.Form):
"""
Base form for a simple localized WTForms form.
This will use the stdlib gettext library to retrieve an appropriate
translations object for the language, by default using the locale
information from the environment.
If the LANGUAGES class variable is overridden and set to a sequence of
strings, this will be a list of languages by priority to use instead, e.g::
LANGUAGES = ['en_GB', 'en']
One can also provide the languages by passing `LANGUAGES=` to the
constructor of the form.
Translations objects are cached to prevent having to get a new one for the
same languages every instantiation.
"""
LANGUAGES = None
def __init__(self, *args, **kwargs):
warnings.warn('wtforms.ext.i18n will be removed in WTForms 1.2', DeprecationWarning)
super(Form, self).__init__(*args, **kwargs)
def _get_translations(self):
languages = tuple(self.LANGUAGES) if self.LANGUAGES else None
if languages not in translations_cache:
translations_cache[languages] = get_translations(languages)
return translations_cache[languages]
<commit_msg>Make documentation more explicit for WTForms deprecation.<commit_after>
|
import warnings
from wtforms import form
from wtforms.ext.i18n.utils import get_translations
translations_cache = {}
class Form(form.Form):
"""
Base form for a simple localized WTForms form.
**NOTE** this class is now un-necessary as the i18n features have
been moved into the core of WTForms, but it will be kept for
compatibility reasons until WTForms 1.2.
This will use the stdlib gettext library to retrieve an appropriate
translations object for the language, by default using the locale
information from the environment.
If the LANGUAGES class variable is overridden and set to a sequence of
strings, this will be a list of languages by priority to use instead, e.g::
LANGUAGES = ['en_GB', 'en']
One can also provide the languages by passing `LANGUAGES=` to the
constructor of the form.
Translations objects are cached to prevent having to get a new one for the
same languages every instantiation.
"""
LANGUAGES = None
def __init__(self, *args, **kwargs):
warnings.warn('i18n is now in core, wtforms.ext.i18n will be removed in WTForms 1.2', DeprecationWarning)
super(Form, self).__init__(*args, **kwargs)
def _get_translations(self):
languages = tuple(self.LANGUAGES) if self.LANGUAGES else None
if languages not in translations_cache:
translations_cache[languages] = get_translations(languages)
return translations_cache[languages]
|
import warnings
from wtforms import form
from wtforms.ext.i18n.utils import get_translations
translations_cache = {}
class Form(form.Form):
"""
Base form for a simple localized WTForms form.
This will use the stdlib gettext library to retrieve an appropriate
translations object for the language, by default using the locale
information from the environment.
If the LANGUAGES class variable is overridden and set to a sequence of
strings, this will be a list of languages by priority to use instead, e.g::
LANGUAGES = ['en_GB', 'en']
One can also provide the languages by passing `LANGUAGES=` to the
constructor of the form.
Translations objects are cached to prevent having to get a new one for the
same languages every instantiation.
"""
LANGUAGES = None
def __init__(self, *args, **kwargs):
warnings.warn('wtforms.ext.i18n will be removed in WTForms 1.2', DeprecationWarning)
super(Form, self).__init__(*args, **kwargs)
def _get_translations(self):
languages = tuple(self.LANGUAGES) if self.LANGUAGES else None
if languages not in translations_cache:
translations_cache[languages] = get_translations(languages)
return translations_cache[languages]
Make documentation more explicit for WTForms deprecation.import warnings
from wtforms import form
from wtforms.ext.i18n.utils import get_translations
translations_cache = {}
class Form(form.Form):
"""
Base form for a simple localized WTForms form.
**NOTE** this class is now un-necessary as the i18n features have
been moved into the core of WTForms, but it will be kept for
compatibility reasons until WTForms 1.2.
This will use the stdlib gettext library to retrieve an appropriate
translations object for the language, by default using the locale
information from the environment.
If the LANGUAGES class variable is overridden and set to a sequence of
strings, this will be a list of languages by priority to use instead, e.g::
LANGUAGES = ['en_GB', 'en']
One can also provide the languages by passing `LANGUAGES=` to the
constructor of the form.
Translations objects are cached to prevent having to get a new one for the
same languages every instantiation.
"""
LANGUAGES = None
def __init__(self, *args, **kwargs):
warnings.warn('i18n is now in core, wtforms.ext.i18n will be removed in WTForms 1.2', DeprecationWarning)
super(Form, self).__init__(*args, **kwargs)
def _get_translations(self):
languages = tuple(self.LANGUAGES) if self.LANGUAGES else None
if languages not in translations_cache:
translations_cache[languages] = get_translations(languages)
return translations_cache[languages]
|
<commit_before>import warnings
from wtforms import form
from wtforms.ext.i18n.utils import get_translations
translations_cache = {}
class Form(form.Form):
"""
Base form for a simple localized WTForms form.
This will use the stdlib gettext library to retrieve an appropriate
translations object for the language, by default using the locale
information from the environment.
If the LANGUAGES class variable is overridden and set to a sequence of
strings, this will be a list of languages by priority to use instead, e.g::
LANGUAGES = ['en_GB', 'en']
One can also provide the languages by passing `LANGUAGES=` to the
constructor of the form.
Translations objects are cached to prevent having to get a new one for the
same languages every instantiation.
"""
LANGUAGES = None
def __init__(self, *args, **kwargs):
warnings.warn('wtforms.ext.i18n will be removed in WTForms 1.2', DeprecationWarning)
super(Form, self).__init__(*args, **kwargs)
def _get_translations(self):
languages = tuple(self.LANGUAGES) if self.LANGUAGES else None
if languages not in translations_cache:
translations_cache[languages] = get_translations(languages)
return translations_cache[languages]
<commit_msg>Make documentation more explicit for WTForms deprecation.<commit_after>import warnings
from wtforms import form
from wtforms.ext.i18n.utils import get_translations
translations_cache = {}
class Form(form.Form):
"""
Base form for a simple localized WTForms form.
**NOTE** this class is now un-necessary as the i18n features have
been moved into the core of WTForms, but it will be kept for
compatibility reasons until WTForms 1.2.
This will use the stdlib gettext library to retrieve an appropriate
translations object for the language, by default using the locale
information from the environment.
If the LANGUAGES class variable is overridden and set to a sequence of
strings, this will be a list of languages by priority to use instead, e.g::
LANGUAGES = ['en_GB', 'en']
One can also provide the languages by passing `LANGUAGES=` to the
constructor of the form.
Translations objects are cached to prevent having to get a new one for the
same languages every instantiation.
"""
LANGUAGES = None
def __init__(self, *args, **kwargs):
warnings.warn('i18n is now in core, wtforms.ext.i18n will be removed in WTForms 1.2', DeprecationWarning)
super(Form, self).__init__(*args, **kwargs)
def _get_translations(self):
languages = tuple(self.LANGUAGES) if self.LANGUAGES else None
if languages not in translations_cache:
translations_cache[languages] = get_translations(languages)
return translations_cache[languages]
|
8dff67fbffbb87ec81226ce376bc42fbcf66ea4f
|
xos/helloworld/models.py
|
xos/helloworld/models.py
|
from django.db import models
from core.models import User, Service, SingletonModel, PlCoreBase, Instance
from core.models.plcorebase import StrippedCharField
import os
from django.db import models
from django.forms.models import model_to_dict
from django.db.models import Q
# Create your models here.
class Hello(PlCoreBase):
name = models.CharField(max_length=254,help_text="Salutation e.g. Hello or Bonjour")
sliver_backref = models.ForeignKey(Instance)
class World(PlCoreBase):
name = models.CharField(max_length=254,help_text="Name of planet")
hello = models.ForeignKey(Hello)
|
from django.db import models
from core.models import User, Service, SingletonModel, PlCoreBase, Instance
from core.models.plcorebase import StrippedCharField
import os
from django.db import models
from django.forms.models import model_to_dict
from django.db.models import Q
# Create your models here.
class Hello(PlCoreBase):
name = models.CharField(max_length=254,help_text="Salutation e.g. Hello or Bonjour")
instance_backref = models.ForeignKey(Instance)
class World(PlCoreBase):
name = models.CharField(max_length=254,help_text="Name of planet")
hello = models.ForeignKey(Hello)
|
Change old 'sliver' ref to instance
|
Change old 'sliver' ref to instance
|
Python
|
apache-2.0
|
opencord/xos,cboling/xos,zdw/xos,cboling/xos,zdw/xos,cboling/xos,zdw/xos,zdw/xos,open-cloud/xos,open-cloud/xos,opencord/xos,open-cloud/xos,cboling/xos,opencord/xos,cboling/xos
|
from django.db import models
from core.models import User, Service, SingletonModel, PlCoreBase, Instance
from core.models.plcorebase import StrippedCharField
import os
from django.db import models
from django.forms.models import model_to_dict
from django.db.models import Q
# Create your models here.
class Hello(PlCoreBase):
name = models.CharField(max_length=254,help_text="Salutation e.g. Hello or Bonjour")
sliver_backref = models.ForeignKey(Instance)
class World(PlCoreBase):
name = models.CharField(max_length=254,help_text="Name of planet")
hello = models.ForeignKey(Hello)
Change old 'sliver' ref to instance
|
from django.db import models
from core.models import User, Service, SingletonModel, PlCoreBase, Instance
from core.models.plcorebase import StrippedCharField
import os
from django.db import models
from django.forms.models import model_to_dict
from django.db.models import Q
# Create your models here.
class Hello(PlCoreBase):
name = models.CharField(max_length=254,help_text="Salutation e.g. Hello or Bonjour")
instance_backref = models.ForeignKey(Instance)
class World(PlCoreBase):
name = models.CharField(max_length=254,help_text="Name of planet")
hello = models.ForeignKey(Hello)
|
<commit_before>from django.db import models
from core.models import User, Service, SingletonModel, PlCoreBase, Instance
from core.models.plcorebase import StrippedCharField
import os
from django.db import models
from django.forms.models import model_to_dict
from django.db.models import Q
# Create your models here.
class Hello(PlCoreBase):
name = models.CharField(max_length=254,help_text="Salutation e.g. Hello or Bonjour")
sliver_backref = models.ForeignKey(Instance)
class World(PlCoreBase):
name = models.CharField(max_length=254,help_text="Name of planet")
hello = models.ForeignKey(Hello)
<commit_msg>Change old 'sliver' ref to instance<commit_after>
|
from django.db import models
from core.models import User, Service, SingletonModel, PlCoreBase, Instance
from core.models.plcorebase import StrippedCharField
import os
from django.db import models
from django.forms.models import model_to_dict
from django.db.models import Q
# Create your models here.
class Hello(PlCoreBase):
name = models.CharField(max_length=254,help_text="Salutation e.g. Hello or Bonjour")
instance_backref = models.ForeignKey(Instance)
class World(PlCoreBase):
name = models.CharField(max_length=254,help_text="Name of planet")
hello = models.ForeignKey(Hello)
|
from django.db import models
from core.models import User, Service, SingletonModel, PlCoreBase, Instance
from core.models.plcorebase import StrippedCharField
import os
from django.db import models
from django.forms.models import model_to_dict
from django.db.models import Q
# Create your models here.
class Hello(PlCoreBase):
name = models.CharField(max_length=254,help_text="Salutation e.g. Hello or Bonjour")
sliver_backref = models.ForeignKey(Instance)
class World(PlCoreBase):
name = models.CharField(max_length=254,help_text="Name of planet")
hello = models.ForeignKey(Hello)
Change old 'sliver' ref to instancefrom django.db import models
from core.models import User, Service, SingletonModel, PlCoreBase, Instance
from core.models.plcorebase import StrippedCharField
import os
from django.db import models
from django.forms.models import model_to_dict
from django.db.models import Q
# Create your models here.
class Hello(PlCoreBase):
name = models.CharField(max_length=254,help_text="Salutation e.g. Hello or Bonjour")
instance_backref = models.ForeignKey(Instance)
class World(PlCoreBase):
name = models.CharField(max_length=254,help_text="Name of planet")
hello = models.ForeignKey(Hello)
|
<commit_before>from django.db import models
from core.models import User, Service, SingletonModel, PlCoreBase, Instance
from core.models.plcorebase import StrippedCharField
import os
from django.db import models
from django.forms.models import model_to_dict
from django.db.models import Q
# Create your models here.
class Hello(PlCoreBase):
name = models.CharField(max_length=254,help_text="Salutation e.g. Hello or Bonjour")
sliver_backref = models.ForeignKey(Instance)
class World(PlCoreBase):
name = models.CharField(max_length=254,help_text="Name of planet")
hello = models.ForeignKey(Hello)
<commit_msg>Change old 'sliver' ref to instance<commit_after>from django.db import models
from core.models import User, Service, SingletonModel, PlCoreBase, Instance
from core.models.plcorebase import StrippedCharField
import os
from django.db import models
from django.forms.models import model_to_dict
from django.db.models import Q
# Create your models here.
class Hello(PlCoreBase):
name = models.CharField(max_length=254,help_text="Salutation e.g. Hello or Bonjour")
instance_backref = models.ForeignKey(Instance)
class World(PlCoreBase):
name = models.CharField(max_length=254,help_text="Name of planet")
hello = models.ForeignKey(Hello)
|
eb15105976fd054878e0fb16a8ee6e884496b2db
|
dmoj/executors/RKT.py
|
dmoj/executors/RKT.py
|
from dmoj.executors.base_executor import CompiledExecutor
from dmoj.executors.mixins import ScriptDirectoryMixin
class Executor(ScriptDirectoryMixin, CompiledExecutor):
ext = '.rkt'
name = 'RKT'
fs = ['/etc/nsswitch.conf$', '/etc/passwd$']
command = 'racket'
syscalls = ['epoll_create', 'epoll_wait', 'poll', 'select']
address_grace = 131072
test_program = '''\
#lang racket
(displayln (read-line))
'''
def get_compile_args(self):
return [self.runtime_dict['raco'], 'make', self._code]
def get_cmdline(self):
return [self.get_command(), self._code]
def get_executable(self):
return self.get_command()
@classmethod
def initialize(cls, sandbox=True):
if 'raco' not in cls.runtime_dict:
return False
return super(Executor, cls).initialize(sandbox)
@classmethod
def get_versionable_commands(cls):
return [('racket', cls.get_command())]
@classmethod
def get_find_first_mapping(cls):
return {
'racket': ['racket'],
'raco': ['raco']
}
|
from dmoj.executors.base_executor import CompiledExecutor
from dmoj.executors.mixins import ScriptDirectoryMixin
import os
class Executor(ScriptDirectoryMixin, CompiledExecutor):
ext = '.rkt'
name = 'RKT'
fs = ['/etc/nsswitch.conf$', '/etc/passwd$', os.path.expanduser('~/\.racket/.*?')]
command = 'racket'
syscalls = ['epoll_create', 'epoll_wait', 'poll', 'select']
address_grace = 131072
test_program = '''\
#lang racket
(displayln (read-line))
'''
def get_compile_args(self):
return [self.runtime_dict['raco'], 'make', self._code]
def get_cmdline(self):
return [self.get_command(), self._code]
def get_executable(self):
return self.get_command()
@classmethod
def initialize(cls, sandbox=True):
if 'raco' not in cls.runtime_dict:
return False
return super(Executor, cls).initialize(sandbox)
@classmethod
def get_versionable_commands(cls):
return [('racket', cls.get_command())]
@classmethod
def get_find_first_mapping(cls):
return {
'racket': ['racket'],
'raco': ['raco']
}
|
Fix Racket on FreeBSD after openat changes
|
Fix Racket on FreeBSD after openat changes
@quantum5 this feels iffy, but I think it's (marginally) better than allowing all .racket folders to be read
|
Python
|
agpl-3.0
|
DMOJ/judge,DMOJ/judge,DMOJ/judge
|
from dmoj.executors.base_executor import CompiledExecutor
from dmoj.executors.mixins import ScriptDirectoryMixin
class Executor(ScriptDirectoryMixin, CompiledExecutor):
ext = '.rkt'
name = 'RKT'
fs = ['/etc/nsswitch.conf$', '/etc/passwd$']
command = 'racket'
syscalls = ['epoll_create', 'epoll_wait', 'poll', 'select']
address_grace = 131072
test_program = '''\
#lang racket
(displayln (read-line))
'''
def get_compile_args(self):
return [self.runtime_dict['raco'], 'make', self._code]
def get_cmdline(self):
return [self.get_command(), self._code]
def get_executable(self):
return self.get_command()
@classmethod
def initialize(cls, sandbox=True):
if 'raco' not in cls.runtime_dict:
return False
return super(Executor, cls).initialize(sandbox)
@classmethod
def get_versionable_commands(cls):
return [('racket', cls.get_command())]
@classmethod
def get_find_first_mapping(cls):
return {
'racket': ['racket'],
'raco': ['raco']
}
Fix Racket on FreeBSD after openat changes
@quantum5 this feels iffy, but I think it's (marginally) better than allowing all .racket folders to be read
|
from dmoj.executors.base_executor import CompiledExecutor
from dmoj.executors.mixins import ScriptDirectoryMixin
import os
class Executor(ScriptDirectoryMixin, CompiledExecutor):
ext = '.rkt'
name = 'RKT'
fs = ['/etc/nsswitch.conf$', '/etc/passwd$', os.path.expanduser('~/\.racket/.*?')]
command = 'racket'
syscalls = ['epoll_create', 'epoll_wait', 'poll', 'select']
address_grace = 131072
test_program = '''\
#lang racket
(displayln (read-line))
'''
def get_compile_args(self):
return [self.runtime_dict['raco'], 'make', self._code]
def get_cmdline(self):
return [self.get_command(), self._code]
def get_executable(self):
return self.get_command()
@classmethod
def initialize(cls, sandbox=True):
if 'raco' not in cls.runtime_dict:
return False
return super(Executor, cls).initialize(sandbox)
@classmethod
def get_versionable_commands(cls):
return [('racket', cls.get_command())]
@classmethod
def get_find_first_mapping(cls):
return {
'racket': ['racket'],
'raco': ['raco']
}
|
<commit_before>from dmoj.executors.base_executor import CompiledExecutor
from dmoj.executors.mixins import ScriptDirectoryMixin
class Executor(ScriptDirectoryMixin, CompiledExecutor):
ext = '.rkt'
name = 'RKT'
fs = ['/etc/nsswitch.conf$', '/etc/passwd$']
command = 'racket'
syscalls = ['epoll_create', 'epoll_wait', 'poll', 'select']
address_grace = 131072
test_program = '''\
#lang racket
(displayln (read-line))
'''
def get_compile_args(self):
return [self.runtime_dict['raco'], 'make', self._code]
def get_cmdline(self):
return [self.get_command(), self._code]
def get_executable(self):
return self.get_command()
@classmethod
def initialize(cls, sandbox=True):
if 'raco' not in cls.runtime_dict:
return False
return super(Executor, cls).initialize(sandbox)
@classmethod
def get_versionable_commands(cls):
return [('racket', cls.get_command())]
@classmethod
def get_find_first_mapping(cls):
return {
'racket': ['racket'],
'raco': ['raco']
}
<commit_msg>Fix Racket on FreeBSD after openat changes
@quantum5 this feels iffy, but I think it's (marginally) better than allowing all .racket folders to be read<commit_after>
|
from dmoj.executors.base_executor import CompiledExecutor
from dmoj.executors.mixins import ScriptDirectoryMixin
import os
class Executor(ScriptDirectoryMixin, CompiledExecutor):
ext = '.rkt'
name = 'RKT'
fs = ['/etc/nsswitch.conf$', '/etc/passwd$', os.path.expanduser('~/\.racket/.*?')]
command = 'racket'
syscalls = ['epoll_create', 'epoll_wait', 'poll', 'select']
address_grace = 131072
test_program = '''\
#lang racket
(displayln (read-line))
'''
def get_compile_args(self):
return [self.runtime_dict['raco'], 'make', self._code]
def get_cmdline(self):
return [self.get_command(), self._code]
def get_executable(self):
return self.get_command()
@classmethod
def initialize(cls, sandbox=True):
if 'raco' not in cls.runtime_dict:
return False
return super(Executor, cls).initialize(sandbox)
@classmethod
def get_versionable_commands(cls):
return [('racket', cls.get_command())]
@classmethod
def get_find_first_mapping(cls):
return {
'racket': ['racket'],
'raco': ['raco']
}
|
from dmoj.executors.base_executor import CompiledExecutor
from dmoj.executors.mixins import ScriptDirectoryMixin
class Executor(ScriptDirectoryMixin, CompiledExecutor):
ext = '.rkt'
name = 'RKT'
fs = ['/etc/nsswitch.conf$', '/etc/passwd$']
command = 'racket'
syscalls = ['epoll_create', 'epoll_wait', 'poll', 'select']
address_grace = 131072
test_program = '''\
#lang racket
(displayln (read-line))
'''
def get_compile_args(self):
return [self.runtime_dict['raco'], 'make', self._code]
def get_cmdline(self):
return [self.get_command(), self._code]
def get_executable(self):
return self.get_command()
@classmethod
def initialize(cls, sandbox=True):
if 'raco' not in cls.runtime_dict:
return False
return super(Executor, cls).initialize(sandbox)
@classmethod
def get_versionable_commands(cls):
return [('racket', cls.get_command())]
@classmethod
def get_find_first_mapping(cls):
return {
'racket': ['racket'],
'raco': ['raco']
}
Fix Racket on FreeBSD after openat changes
@quantum5 this feels iffy, but I think it's (marginally) better than allowing all .racket folders to be readfrom dmoj.executors.base_executor import CompiledExecutor
from dmoj.executors.mixins import ScriptDirectoryMixin
import os
class Executor(ScriptDirectoryMixin, CompiledExecutor):
ext = '.rkt'
name = 'RKT'
fs = ['/etc/nsswitch.conf$', '/etc/passwd$', os.path.expanduser('~/\.racket/.*?')]
command = 'racket'
syscalls = ['epoll_create', 'epoll_wait', 'poll', 'select']
address_grace = 131072
test_program = '''\
#lang racket
(displayln (read-line))
'''
def get_compile_args(self):
return [self.runtime_dict['raco'], 'make', self._code]
def get_cmdline(self):
return [self.get_command(), self._code]
def get_executable(self):
return self.get_command()
@classmethod
def initialize(cls, sandbox=True):
if 'raco' not in cls.runtime_dict:
return False
return super(Executor, cls).initialize(sandbox)
@classmethod
def get_versionable_commands(cls):
return [('racket', cls.get_command())]
@classmethod
def get_find_first_mapping(cls):
return {
'racket': ['racket'],
'raco': ['raco']
}
|
<commit_before>from dmoj.executors.base_executor import CompiledExecutor
from dmoj.executors.mixins import ScriptDirectoryMixin
class Executor(ScriptDirectoryMixin, CompiledExecutor):
ext = '.rkt'
name = 'RKT'
fs = ['/etc/nsswitch.conf$', '/etc/passwd$']
command = 'racket'
syscalls = ['epoll_create', 'epoll_wait', 'poll', 'select']
address_grace = 131072
test_program = '''\
#lang racket
(displayln (read-line))
'''
def get_compile_args(self):
return [self.runtime_dict['raco'], 'make', self._code]
def get_cmdline(self):
return [self.get_command(), self._code]
def get_executable(self):
return self.get_command()
@classmethod
def initialize(cls, sandbox=True):
if 'raco' not in cls.runtime_dict:
return False
return super(Executor, cls).initialize(sandbox)
@classmethod
def get_versionable_commands(cls):
return [('racket', cls.get_command())]
@classmethod
def get_find_first_mapping(cls):
return {
'racket': ['racket'],
'raco': ['raco']
}
<commit_msg>Fix Racket on FreeBSD after openat changes
@quantum5 this feels iffy, but I think it's (marginally) better than allowing all .racket folders to be read<commit_after>from dmoj.executors.base_executor import CompiledExecutor
from dmoj.executors.mixins import ScriptDirectoryMixin
import os
class Executor(ScriptDirectoryMixin, CompiledExecutor):
ext = '.rkt'
name = 'RKT'
fs = ['/etc/nsswitch.conf$', '/etc/passwd$', os.path.expanduser('~/\.racket/.*?')]
command = 'racket'
syscalls = ['epoll_create', 'epoll_wait', 'poll', 'select']
address_grace = 131072
test_program = '''\
#lang racket
(displayln (read-line))
'''
def get_compile_args(self):
return [self.runtime_dict['raco'], 'make', self._code]
def get_cmdline(self):
return [self.get_command(), self._code]
def get_executable(self):
return self.get_command()
@classmethod
def initialize(cls, sandbox=True):
if 'raco' not in cls.runtime_dict:
return False
return super(Executor, cls).initialize(sandbox)
@classmethod
def get_versionable_commands(cls):
return [('racket', cls.get_command())]
@classmethod
def get_find_first_mapping(cls):
return {
'racket': ['racket'],
'raco': ['raco']
}
|
ae2dd4b9fe3686aca44a21ff72a4226c6110f2ee
|
presentation/views.py
|
presentation/views.py
|
from django.views.generic import DetailView
from django.views.generic import ListView
from django.shortcuts import redirect, render
from .forms import PresentationCreateForm
from .models import Presentation, Slide
class PresentationList(ListView):
model = Presentation
paginate_by = 9
context_object_name = 'presentations'
class PresentationDetail(DetailView):
model = Presentation
context_object_name = 'presentation'
template_name = 'presentation/presentation_list.html'
def presentation_create(request):
form = PresentationCreateForm(request.POST)
if request.method == 'POST':
if form.is_valid():
presentation = Presentation.objects.create(
subject=form.cleaned_data.get('subject'),
author=request.user,
is_public=form.cleaned_data.get('is_public')
)
slide_list = request.POST.getlist('slide_list[]', [])
for slide in slide_list:
Slide.objects.create(
presentation=presentation,
slide_order=slide['slide_order'],
markdown=slide['markdown'],
html=slide['html'],
)
return redirect('presentation:list')
context = {'form': form}
return render(request, 'presentation/presentation_create.html', context)
|
from django.views.generic import DetailView
from django.views.generic import ListView
from django.shortcuts import redirect, render
from pure_pagination import PaginationMixin
from .forms import PresentationCreateForm
from .models import Presentation, Slide
class PresentationList(PaginationMixin, ListView):
model = Presentation
paginate_by = 9
context_object_name = 'presentations'
ordering = ['-pk']
class PresentationDetail(DetailView):
model = Presentation
context_object_name = 'presentation'
template_name = 'presentation/presentation_list.html'
def presentation_create(request):
form = PresentationCreateForm(request.POST)
if request.method == 'POST':
if form.is_valid():
presentation = Presentation.objects.create(
subject=form.cleaned_data.get('subject'),
author=request.user,
is_public=form.cleaned_data.get('is_public')
)
slide_list = request.POST.getlist('slide_list[]', [])
for slide in slide_list:
Slide.objects.create(
presentation=presentation,
slide_order=slide['slide_order'],
markdown=slide['markdown'],
html=slide['html'],
)
return redirect('presentation:list')
context = {'form': form}
return render(request, 'presentation/presentation_create.html', context)
|
Add Ordering and PaginationMixin on Listview
|
Add Ordering and PaginationMixin on Listview
|
Python
|
mit
|
SaturDJang/warp,SaturDJang/warp,SaturDJang/warp,SaturDJang/warp
|
from django.views.generic import DetailView
from django.views.generic import ListView
from django.shortcuts import redirect, render
from .forms import PresentationCreateForm
from .models import Presentation, Slide
class PresentationList(ListView):
model = Presentation
paginate_by = 9
context_object_name = 'presentations'
class PresentationDetail(DetailView):
model = Presentation
context_object_name = 'presentation'
template_name = 'presentation/presentation_list.html'
def presentation_create(request):
form = PresentationCreateForm(request.POST)
if request.method == 'POST':
if form.is_valid():
presentation = Presentation.objects.create(
subject=form.cleaned_data.get('subject'),
author=request.user,
is_public=form.cleaned_data.get('is_public')
)
slide_list = request.POST.getlist('slide_list[]', [])
for slide in slide_list:
Slide.objects.create(
presentation=presentation,
slide_order=slide['slide_order'],
markdown=slide['markdown'],
html=slide['html'],
)
return redirect('presentation:list')
context = {'form': form}
return render(request, 'presentation/presentation_create.html', context)
Add Ordering and PaginationMixin on Listview
|
from django.views.generic import DetailView
from django.views.generic import ListView
from django.shortcuts import redirect, render
from pure_pagination import PaginationMixin
from .forms import PresentationCreateForm
from .models import Presentation, Slide
class PresentationList(PaginationMixin, ListView):
model = Presentation
paginate_by = 9
context_object_name = 'presentations'
ordering = ['-pk']
class PresentationDetail(DetailView):
model = Presentation
context_object_name = 'presentation'
template_name = 'presentation/presentation_list.html'
def presentation_create(request):
form = PresentationCreateForm(request.POST)
if request.method == 'POST':
if form.is_valid():
presentation = Presentation.objects.create(
subject=form.cleaned_data.get('subject'),
author=request.user,
is_public=form.cleaned_data.get('is_public')
)
slide_list = request.POST.getlist('slide_list[]', [])
for slide in slide_list:
Slide.objects.create(
presentation=presentation,
slide_order=slide['slide_order'],
markdown=slide['markdown'],
html=slide['html'],
)
return redirect('presentation:list')
context = {'form': form}
return render(request, 'presentation/presentation_create.html', context)
|
<commit_before>from django.views.generic import DetailView
from django.views.generic import ListView
from django.shortcuts import redirect, render
from .forms import PresentationCreateForm
from .models import Presentation, Slide
class PresentationList(ListView):
model = Presentation
paginate_by = 9
context_object_name = 'presentations'
class PresentationDetail(DetailView):
model = Presentation
context_object_name = 'presentation'
template_name = 'presentation/presentation_list.html'
def presentation_create(request):
form = PresentationCreateForm(request.POST)
if request.method == 'POST':
if form.is_valid():
presentation = Presentation.objects.create(
subject=form.cleaned_data.get('subject'),
author=request.user,
is_public=form.cleaned_data.get('is_public')
)
slide_list = request.POST.getlist('slide_list[]', [])
for slide in slide_list:
Slide.objects.create(
presentation=presentation,
slide_order=slide['slide_order'],
markdown=slide['markdown'],
html=slide['html'],
)
return redirect('presentation:list')
context = {'form': form}
return render(request, 'presentation/presentation_create.html', context)
<commit_msg>Add Ordering and PaginationMixin on Listview<commit_after>
|
from django.views.generic import DetailView
from django.views.generic import ListView
from django.shortcuts import redirect, render
from pure_pagination import PaginationMixin
from .forms import PresentationCreateForm
from .models import Presentation, Slide
class PresentationList(PaginationMixin, ListView):
model = Presentation
paginate_by = 9
context_object_name = 'presentations'
ordering = ['-pk']
class PresentationDetail(DetailView):
model = Presentation
context_object_name = 'presentation'
template_name = 'presentation/presentation_list.html'
def presentation_create(request):
form = PresentationCreateForm(request.POST)
if request.method == 'POST':
if form.is_valid():
presentation = Presentation.objects.create(
subject=form.cleaned_data.get('subject'),
author=request.user,
is_public=form.cleaned_data.get('is_public')
)
slide_list = request.POST.getlist('slide_list[]', [])
for slide in slide_list:
Slide.objects.create(
presentation=presentation,
slide_order=slide['slide_order'],
markdown=slide['markdown'],
html=slide['html'],
)
return redirect('presentation:list')
context = {'form': form}
return render(request, 'presentation/presentation_create.html', context)
|
from django.views.generic import DetailView
from django.views.generic import ListView
from django.shortcuts import redirect, render
from .forms import PresentationCreateForm
from .models import Presentation, Slide
class PresentationList(ListView):
model = Presentation
paginate_by = 9
context_object_name = 'presentations'
class PresentationDetail(DetailView):
model = Presentation
context_object_name = 'presentation'
template_name = 'presentation/presentation_list.html'
def presentation_create(request):
form = PresentationCreateForm(request.POST)
if request.method == 'POST':
if form.is_valid():
presentation = Presentation.objects.create(
subject=form.cleaned_data.get('subject'),
author=request.user,
is_public=form.cleaned_data.get('is_public')
)
slide_list = request.POST.getlist('slide_list[]', [])
for slide in slide_list:
Slide.objects.create(
presentation=presentation,
slide_order=slide['slide_order'],
markdown=slide['markdown'],
html=slide['html'],
)
return redirect('presentation:list')
context = {'form': form}
return render(request, 'presentation/presentation_create.html', context)
Add Ordering and PaginationMixin on Listviewfrom django.views.generic import DetailView
from django.views.generic import ListView
from django.shortcuts import redirect, render
from pure_pagination import PaginationMixin
from .forms import PresentationCreateForm
from .models import Presentation, Slide
class PresentationList(PaginationMixin, ListView):
model = Presentation
paginate_by = 9
context_object_name = 'presentations'
ordering = ['-pk']
class PresentationDetail(DetailView):
model = Presentation
context_object_name = 'presentation'
template_name = 'presentation/presentation_list.html'
def presentation_create(request):
form = PresentationCreateForm(request.POST)
if request.method == 'POST':
if form.is_valid():
presentation = Presentation.objects.create(
subject=form.cleaned_data.get('subject'),
author=request.user,
is_public=form.cleaned_data.get('is_public')
)
slide_list = request.POST.getlist('slide_list[]', [])
for slide in slide_list:
Slide.objects.create(
presentation=presentation,
slide_order=slide['slide_order'],
markdown=slide['markdown'],
html=slide['html'],
)
return redirect('presentation:list')
context = {'form': form}
return render(request, 'presentation/presentation_create.html', context)
|
<commit_before>from django.views.generic import DetailView
from django.views.generic import ListView
from django.shortcuts import redirect, render
from .forms import PresentationCreateForm
from .models import Presentation, Slide
class PresentationList(ListView):
model = Presentation
paginate_by = 9
context_object_name = 'presentations'
class PresentationDetail(DetailView):
model = Presentation
context_object_name = 'presentation'
template_name = 'presentation/presentation_list.html'
def presentation_create(request):
form = PresentationCreateForm(request.POST)
if request.method == 'POST':
if form.is_valid():
presentation = Presentation.objects.create(
subject=form.cleaned_data.get('subject'),
author=request.user,
is_public=form.cleaned_data.get('is_public')
)
slide_list = request.POST.getlist('slide_list[]', [])
for slide in slide_list:
Slide.objects.create(
presentation=presentation,
slide_order=slide['slide_order'],
markdown=slide['markdown'],
html=slide['html'],
)
return redirect('presentation:list')
context = {'form': form}
return render(request, 'presentation/presentation_create.html', context)
<commit_msg>Add Ordering and PaginationMixin on Listview<commit_after>from django.views.generic import DetailView
from django.views.generic import ListView
from django.shortcuts import redirect, render
from pure_pagination import PaginationMixin
from .forms import PresentationCreateForm
from .models import Presentation, Slide
class PresentationList(PaginationMixin, ListView):
model = Presentation
paginate_by = 9
context_object_name = 'presentations'
ordering = ['-pk']
class PresentationDetail(DetailView):
model = Presentation
context_object_name = 'presentation'
template_name = 'presentation/presentation_list.html'
def presentation_create(request):
form = PresentationCreateForm(request.POST)
if request.method == 'POST':
if form.is_valid():
presentation = Presentation.objects.create(
subject=form.cleaned_data.get('subject'),
author=request.user,
is_public=form.cleaned_data.get('is_public')
)
slide_list = request.POST.getlist('slide_list[]', [])
for slide in slide_list:
Slide.objects.create(
presentation=presentation,
slide_order=slide['slide_order'],
markdown=slide['markdown'],
html=slide['html'],
)
return redirect('presentation:list')
context = {'form': form}
return render(request, 'presentation/presentation_create.html', context)
|
a1ad77dac17766bf8cd3427aa147b90fc094083f
|
dsub/_dsub_version.py
|
dsub/_dsub_version.py
|
# Copyright 2017 Google Inc. All Rights Reserved.
#
# 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.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
The version should follow formatting requirements specified in PEP-440.
- https://www.python.org/dev/peps/pep-0440
A typical release sequence will be versioned as:
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
DSUB_VERSION = '0.3.1.dev0'
|
# Copyright 2017 Google Inc. All Rights Reserved.
#
# 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.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
The version should follow formatting requirements specified in PEP-440.
- https://www.python.org/dev/peps/pep-0440
A typical release sequence will be versioned as:
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
DSUB_VERSION = '0.3.1'
|
Update dsub version to 0.3.1
|
Update dsub version to 0.3.1
PiperOrigin-RevId: 243828346
|
Python
|
apache-2.0
|
DataBiosphere/dsub,DataBiosphere/dsub
|
# Copyright 2017 Google Inc. All Rights Reserved.
#
# 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.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
The version should follow formatting requirements specified in PEP-440.
- https://www.python.org/dev/peps/pep-0440
A typical release sequence will be versioned as:
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
DSUB_VERSION = '0.3.1.dev0'
Update dsub version to 0.3.1
PiperOrigin-RevId: 243828346
|
# Copyright 2017 Google Inc. All Rights Reserved.
#
# 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.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
The version should follow formatting requirements specified in PEP-440.
- https://www.python.org/dev/peps/pep-0440
A typical release sequence will be versioned as:
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
DSUB_VERSION = '0.3.1'
|
<commit_before># Copyright 2017 Google Inc. All Rights Reserved.
#
# 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.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
The version should follow formatting requirements specified in PEP-440.
- https://www.python.org/dev/peps/pep-0440
A typical release sequence will be versioned as:
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
DSUB_VERSION = '0.3.1.dev0'
<commit_msg>Update dsub version to 0.3.1
PiperOrigin-RevId: 243828346<commit_after>
|
# Copyright 2017 Google Inc. All Rights Reserved.
#
# 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.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
The version should follow formatting requirements specified in PEP-440.
- https://www.python.org/dev/peps/pep-0440
A typical release sequence will be versioned as:
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
DSUB_VERSION = '0.3.1'
|
# Copyright 2017 Google Inc. All Rights Reserved.
#
# 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.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
The version should follow formatting requirements specified in PEP-440.
- https://www.python.org/dev/peps/pep-0440
A typical release sequence will be versioned as:
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
DSUB_VERSION = '0.3.1.dev0'
Update dsub version to 0.3.1
PiperOrigin-RevId: 243828346# Copyright 2017 Google Inc. All Rights Reserved.
#
# 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.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
The version should follow formatting requirements specified in PEP-440.
- https://www.python.org/dev/peps/pep-0440
A typical release sequence will be versioned as:
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
DSUB_VERSION = '0.3.1'
|
<commit_before># Copyright 2017 Google Inc. All Rights Reserved.
#
# 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.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
The version should follow formatting requirements specified in PEP-440.
- https://www.python.org/dev/peps/pep-0440
A typical release sequence will be versioned as:
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
DSUB_VERSION = '0.3.1.dev0'
<commit_msg>Update dsub version to 0.3.1
PiperOrigin-RevId: 243828346<commit_after># Copyright 2017 Google Inc. All Rights Reserved.
#
# 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.
"""Single source of truth for dsub's version.
This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.
The version should follow formatting requirements specified in PEP-440.
- https://www.python.org/dev/peps/pep-0440
A typical release sequence will be versioned as:
0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""
DSUB_VERSION = '0.3.1'
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.